]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
update
[l4.git] / l4 / pkg / sqlite / lib / contrib / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.0.1.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a one translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
219 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
220 ** and the fact that the page size must be a power of 2.
221 **
222 ** If this limit is changed, then the compiled library is technically
223 ** incompatible with an SQLite library compiled with a different limit. If
224 ** a process operating on a database with a page-size of 65536 bytes 
225 ** crashes, then an instance of SQLite compiled with the default page-size 
226 ** limit will not be able to rollback the aborted transaction. This could
227 ** lead to database corruption.
228 */
229 #ifndef SQLITE_MAX_PAGE_SIZE
230 # define SQLITE_MAX_PAGE_SIZE 32768
231 #endif
232
233
234 /*
235 ** The default size of a database page.
236 */
237 #ifndef SQLITE_DEFAULT_PAGE_SIZE
238 # define SQLITE_DEFAULT_PAGE_SIZE 1024
239 #endif
240 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
241 # undef SQLITE_DEFAULT_PAGE_SIZE
242 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
243 #endif
244
245 /*
246 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
247 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
248 ** device characteristics (sector-size and atomic write() support),
249 ** SQLite may choose a larger value. This constant is the maximum value
250 ** SQLite will choose on its own.
251 */
252 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
253 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
254 #endif
255 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
256 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
257 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
258 #endif
259
260
261 /*
262 ** Maximum number of pages in one database file.
263 **
264 ** This is really just the default value for the max_page_count pragma.
265 ** This value can be lowered (or raised) at run-time using that the
266 ** max_page_count macro.
267 */
268 #ifndef SQLITE_MAX_PAGE_COUNT
269 # define SQLITE_MAX_PAGE_COUNT 1073741823
270 #endif
271
272 /*
273 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
274 ** operator.
275 */
276 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
277 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
278 #endif
279
280 /*
281 ** Maximum depth of recursion for triggers.
282 **
283 ** A value of 1 means that a trigger program will not be able to itself
284 ** fire any triggers. A value of 0 means that no trigger programs at all 
285 ** may be executed.
286 */
287 #ifndef SQLITE_MAX_TRIGGER_DEPTH
288 # define SQLITE_MAX_TRIGGER_DEPTH 1000
289 #endif
290
291 /************** End of sqliteLimit.h *****************************************/
292 /************** Continuing where we left off in sqliteInt.h ******************/
293
294 /* Disable nuisance warnings on Borland compilers */
295 #if defined(__BORLANDC__)
296 #pragma warn -rch /* unreachable code */
297 #pragma warn -ccc /* Condition is always true or false */
298 #pragma warn -aus /* Assigned value is never used */
299 #pragma warn -csu /* Comparing signed and unsigned */
300 #pragma warn -spa /* Suspicious pointer arithmetic */
301 #endif
302
303 /* Needed for various definitions... */
304 #ifndef _GNU_SOURCE
305 # define _GNU_SOURCE
306 #endif
307
308 /*
309 ** Include standard header files as necessary
310 */
311 #ifdef HAVE_STDINT_H
312 #include <stdint.h>
313 #endif
314 #ifdef HAVE_INTTYPES_H
315 #include <inttypes.h>
316 #endif
317
318 /*
319 ** The number of samples of an index that SQLite takes in order to 
320 ** construct a histogram of the table content when running ANALYZE
321 ** and with SQLITE_ENABLE_STAT2
322 */
323 #define SQLITE_INDEX_SAMPLES 10
324
325 /*
326 ** The following macros are used to cast pointers to integers and
327 ** integers to pointers.  The way you do this varies from one compiler
328 ** to the next, so we have developed the following set of #if statements
329 ** to generate appropriate macros for a wide range of compilers.
330 **
331 ** The correct "ANSI" way to do this is to use the intptr_t type. 
332 ** Unfortunately, that typedef is not available on all compilers, or
333 ** if it is available, it requires an #include of specific headers
334 ** that vary from one machine to the next.
335 **
336 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
337 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
338 ** So we have to define the macros in different ways depending on the
339 ** compiler.
340 */
341 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
342 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
343 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
344 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
345 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
346 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
347 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
348 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
349 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
350 #else                          /* Generates a warning - but it always works */
351 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
352 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
353 #endif
354
355 /*
356 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
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
365 #endif
366 #endif
367
368 /*
369 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
370 ** It determines whether or not the features related to 
371 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
372 ** be overridden at runtime using the sqlite3_config() API.
373 */
374 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
375 # define SQLITE_DEFAULT_MEMSTATUS 1
376 #endif
377
378 /*
379 ** Exactly one of the following macros must be defined in order to
380 ** specify which memory allocation subsystem to use.
381 **
382 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
383 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
384 **
385 ** (Historical note:  There used to be several other options, but we've
386 ** pared it down to just these two.)
387 **
388 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
389 ** the default.
390 */
391 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
392 # error "At most one of the following compile-time configuration options\
393  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
394 #endif
395 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
396 # define SQLITE_SYSTEM_MALLOC 1
397 #endif
398
399 /*
400 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
401 ** sizes of memory allocations below this value where possible.
402 */
403 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
404 # define SQLITE_MALLOC_SOFT_LIMIT 1024
405 #endif
406
407 /*
408 ** We need to define _XOPEN_SOURCE as follows in order to enable
409 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
410 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
411 ** so it is omitted there.  See ticket #2673.
412 **
413 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
414 ** implemented on some systems.  So we avoid defining it at all
415 ** if it is already defined or if it is unneeded because we are
416 ** not doing a threadsafe build.  Ticket #2681.
417 **
418 ** See also ticket #2741.
419 */
420 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
421 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
422 #endif
423
424 /*
425 ** The TCL headers are only needed when compiling the TCL bindings.
426 */
427 #if defined(SQLITE_TCL) || defined(TCLSH)
428 # include <tcl.h>
429 #endif
430
431 /*
432 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
433 ** Setting NDEBUG makes the code smaller and run faster.  So the following
434 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
435 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
436 ** feature.
437 */
438 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
439 # define NDEBUG 1
440 #endif
441
442 /*
443 ** The testcase() macro is used to aid in coverage testing.  When 
444 ** doing coverage testing, the condition inside the argument to
445 ** testcase() must be evaluated both true and false in order to
446 ** get full branch coverage.  The testcase() macro is inserted
447 ** to help ensure adequate test coverage in places where simple
448 ** condition/decision coverage is inadequate.  For example, testcase()
449 ** can be used to make sure boundary values are tested.  For
450 ** bitmask tests, testcase() can be used to make sure each bit
451 ** is significant and used at least once.  On switch statements
452 ** where multiple cases go to the same block of code, testcase()
453 ** can insure that all cases are evaluated.
454 **
455 */
456 #ifdef SQLITE_COVERAGE_TEST
457 SQLITE_PRIVATE   void sqlite3Coverage(int);
458 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
459 #else
460 # define testcase(X)
461 #endif
462
463 /*
464 ** The TESTONLY macro is used to enclose variable declarations or
465 ** other bits of code that are needed to support the arguments
466 ** within testcase() and assert() macros.
467 */
468 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
469 # define TESTONLY(X)  X
470 #else
471 # define TESTONLY(X)
472 #endif
473
474 /*
475 ** Sometimes we need a small amount of code such as a variable initialization
476 ** to setup for a later assert() statement.  We do not want this code to
477 ** appear when assert() is disabled.  The following macro is therefore
478 ** used to contain that setup code.  The "VVA" acronym stands for
479 ** "Verification, Validation, and Accreditation".  In other words, the
480 ** code within VVA_ONLY() will only run during verification processes.
481 */
482 #ifndef NDEBUG
483 # define VVA_ONLY(X)  X
484 #else
485 # define VVA_ONLY(X)
486 #endif
487
488 /*
489 ** The ALWAYS and NEVER macros surround boolean expressions which 
490 ** are intended to always be true or false, respectively.  Such
491 ** expressions could be omitted from the code completely.  But they
492 ** are included in a few cases in order to enhance the resilience
493 ** of SQLite to unexpected behavior - to make the code "self-healing"
494 ** or "ductile" rather than being "brittle" and crashing at the first
495 ** hint of unplanned behavior.
496 **
497 ** In other words, ALWAYS and NEVER are added for defensive code.
498 **
499 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
500 ** be true and false so that the unreachable code then specify will
501 ** not be counted as untested code.
502 */
503 #if defined(SQLITE_COVERAGE_TEST)
504 # define ALWAYS(X)      (1)
505 # define NEVER(X)       (0)
506 #elif !defined(NDEBUG)
507 # define ALWAYS(X)      ((X)?1:(assert(0),0))
508 # define NEVER(X)       ((X)?(assert(0),1):0)
509 #else
510 # define ALWAYS(X)      (X)
511 # define NEVER(X)       (X)
512 #endif
513
514 /*
515 ** Return true (non-zero) if the input is a integer that is too large
516 ** to fit in 32-bits.  This macro is used inside of various testcase()
517 ** macros to verify that we have tested SQLite for large-file support.
518 */
519 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
520
521 /*
522 ** The macro unlikely() is a hint that surrounds a boolean
523 ** expression that is usually false.  Macro likely() surrounds
524 ** a boolean expression that is usually true.  GCC is able to
525 ** use these hints to generate better code, sometimes.
526 */
527 #if defined(__GNUC__) && 0
528 # define likely(X)    __builtin_expect((X),1)
529 # define unlikely(X)  __builtin_expect((X),0)
530 #else
531 # define likely(X)    !!(X)
532 # define unlikely(X)  !!(X)
533 #endif
534
535 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
536 /************** Begin file sqlite3.h *****************************************/
537 /*
538 ** 2001 September 15
539 **
540 ** The author disclaims copyright to this source code.  In place of
541 ** a legal notice, here is a blessing:
542 **
543 **    May you do good and not evil.
544 **    May you find forgiveness for yourself and forgive others.
545 **    May you share freely, never taking more than you give.
546 **
547 *************************************************************************
548 ** This header file defines the interface that the SQLite library
549 ** presents to client programs.  If a C-function, structure, datatype,
550 ** or constant definition does not appear in this file, then it is
551 ** not a published API of SQLite, is subject to change without
552 ** notice, and should not be referenced by programs that use SQLite.
553 **
554 ** Some of the definitions that are in this file are marked as
555 ** "experimental".  Experimental interfaces are normally new
556 ** features recently added to SQLite.  We do not anticipate changes
557 ** to experimental interfaces but reserve the right to make minor changes
558 ** if experience from use "in the wild" suggest such changes are prudent.
559 **
560 ** The official C-language API documentation for SQLite is derived
561 ** from comments in this file.  This file is the authoritative source
562 ** on how SQLite interfaces are suppose to operate.
563 **
564 ** The name of this file under configuration management is "sqlite.h.in".
565 ** The makefile makes some minor changes to this file (such as inserting
566 ** the version number) and changes its name to "sqlite3.h" as
567 ** part of the build process.
568 */
569 #ifndef _SQLITE3_H_
570 #define _SQLITE3_H_
571 #include <stdarg.h>     /* Needed for the definition of va_list */
572
573 /*
574 ** Make sure we can call this stuff from C++.
575 */
576 #if 0
577 extern "C" {
578 #endif
579
580
581 /*
582 ** Add the ability to override 'extern'
583 */
584 #ifndef SQLITE_EXTERN
585 # define SQLITE_EXTERN extern
586 #endif
587
588 #ifndef SQLITE_API
589 # define SQLITE_API
590 #endif
591
592
593 /*
594 ** These no-op macros are used in front of interfaces to mark those
595 ** interfaces as either deprecated or experimental.  New applications
596 ** should not use deprecated interfaces - they are support for backwards
597 ** compatibility only.  Application writers should be aware that
598 ** experimental interfaces are subject to change in point releases.
599 **
600 ** These macros used to resolve to various kinds of compiler magic that
601 ** would generate warning messages when they were used.  But that
602 ** compiler magic ended up generating such a flurry of bug reports
603 ** that we have taken it all out and gone back to using simple
604 ** noop macros.
605 */
606 #define SQLITE_DEPRECATED
607 #define SQLITE_EXPERIMENTAL
608
609 /*
610 ** Ensure these symbols were not defined by some previous header file.
611 */
612 #ifdef SQLITE_VERSION
613 # undef SQLITE_VERSION
614 #endif
615 #ifdef SQLITE_VERSION_NUMBER
616 # undef SQLITE_VERSION_NUMBER
617 #endif
618
619 /*
620 ** CAPI3REF: Compile-Time Library Version Numbers
621 **
622 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
623 ** evaluates to a string literal that is the SQLite version in the
624 ** format "X.Y.Z" where X is the major version number (always 3 for
625 ** SQLite3) and Y is the minor version number and Z is the release number.)^
626 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
627 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
628 ** numbers used in [SQLITE_VERSION].)^
629 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
630 ** be larger than the release from which it is derived.  Either Y will
631 ** be held constant and Z will be incremented or else Y will be incremented
632 ** and Z will be reset to zero.
633 **
634 ** Since version 3.6.18, SQLite source code has been stored in the
635 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
636 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
637 ** a string which identifies a particular check-in of SQLite
638 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
639 ** string contains the date and time of the check-in (UTC) and an SHA1
640 ** hash of the entire source tree.
641 **
642 ** See also: [sqlite3_libversion()],
643 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
644 ** [sqlite_version()] and [sqlite_source_id()].
645 */
646 #define SQLITE_VERSION        "3.7.0.1"
647 #define SQLITE_VERSION_NUMBER 3007000
648 #define SQLITE_SOURCE_ID      "2010-08-04 12:31:11 042a1abb030a0711386add7eb6e10832cc8b0f57"
649
650 /*
651 ** CAPI3REF: Run-Time Library Version Numbers
652 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
653 **
654 ** These interfaces provide the same information as the [SQLITE_VERSION],
655 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
656 ** but are associated with the library instead of the header file.  ^(Cautious
657 ** programmers might include assert() statements in their application to
658 ** verify that values returned by these interfaces match the macros in
659 ** the header, and thus insure that the application is
660 ** compiled with matching library and header files.
661 **
662 ** <blockquote><pre>
663 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
664 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
665 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
666 ** </pre></blockquote>)^
667 **
668 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
669 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
670 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
671 ** function is provided for use in DLLs since DLL users usually do not have
672 ** direct access to string constants within the DLL.  ^The
673 ** sqlite3_libversion_number() function returns an integer equal to
674 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
675 ** a pointer to a string constant whose value is the same as the 
676 ** [SQLITE_SOURCE_ID] C preprocessor macro.
677 **
678 ** See also: [sqlite_version()] and [sqlite_source_id()].
679 */
680 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
681 SQLITE_API const char *sqlite3_libversion(void);
682 SQLITE_API const char *sqlite3_sourceid(void);
683 SQLITE_API int sqlite3_libversion_number(void);
684
685 /*
686 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
687 **
688 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
689 ** indicating whether the specified option was defined at 
690 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
691 ** option name passed to sqlite3_compileoption_used().  
692 **
693 ** ^The sqlite3_compileoption_get() function allows interating
694 ** over the list of options that were defined at compile time by
695 ** returning the N-th compile time option string.  ^If N is out of range,
696 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
697 ** prefix is omitted from any strings returned by 
698 ** sqlite3_compileoption_get().
699 **
700 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
701 ** and sqlite3_compileoption_get() may be omitted by specifing the 
702 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
703 **
704 ** See also: SQL functions [sqlite_compileoption_used()] and
705 ** [sqlite_compileoption_get()] and the [compile_options pragma].
706 */
707 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
708 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
709 SQLITE_API const char *sqlite3_compileoption_get(int N);
710 #endif
711
712 /*
713 ** CAPI3REF: Test To See If The Library Is Threadsafe
714 **
715 ** ^The sqlite3_threadsafe() function returns zero if and only if
716 ** SQLite was compiled mutexing code omitted due to the
717 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
718 **
719 ** SQLite can be compiled with or without mutexes.  When
720 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
721 ** are enabled and SQLite is threadsafe.  When the
722 ** [SQLITE_THREADSAFE] macro is 0, 
723 ** the mutexes are omitted.  Without the mutexes, it is not safe
724 ** to use SQLite concurrently from more than one thread.
725 **
726 ** Enabling mutexes incurs a measurable performance penalty.
727 ** So if speed is of utmost importance, it makes sense to disable
728 ** the mutexes.  But for maximum safety, mutexes should be enabled.
729 ** ^The default behavior is for mutexes to be enabled.
730 **
731 ** This interface can be used by an application to make sure that the
732 ** version of SQLite that it is linking against was compiled with
733 ** the desired setting of the [SQLITE_THREADSAFE] macro.
734 **
735 ** This interface only reports on the compile-time mutex setting
736 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
737 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
738 ** can be fully or partially disabled using a call to [sqlite3_config()]
739 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
740 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
741 ** sqlite3_threadsafe() function shows only the compile-time setting of
742 ** thread safety, not any run-time changes to that setting made by
743 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
744 ** is unchanged by calls to sqlite3_config().)^
745 **
746 ** See the [threading mode] documentation for additional information.
747 */
748 SQLITE_API int sqlite3_threadsafe(void);
749
750 /*
751 ** CAPI3REF: Database Connection Handle
752 ** KEYWORDS: {database connection} {database connections}
753 **
754 ** Each open SQLite database is represented by a pointer to an instance of
755 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
756 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
757 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
758 ** is its destructor.  There are many other interfaces (such as
759 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
760 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
761 ** sqlite3 object.
762 */
763 typedef struct sqlite3 sqlite3;
764
765 /*
766 ** CAPI3REF: 64-Bit Integer Types
767 ** KEYWORDS: sqlite_int64 sqlite_uint64
768 **
769 ** Because there is no cross-platform way to specify 64-bit integer types
770 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
771 **
772 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
773 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
774 ** compatibility only.
775 **
776 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
777 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
778 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
779 ** between 0 and +18446744073709551615 inclusive.
780 */
781 #ifdef SQLITE_INT64_TYPE
782   typedef SQLITE_INT64_TYPE sqlite_int64;
783   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
784 #elif defined(_MSC_VER) || defined(__BORLANDC__)
785   typedef __int64 sqlite_int64;
786   typedef unsigned __int64 sqlite_uint64;
787 #else
788   typedef long long int sqlite_int64;
789   typedef unsigned long long int sqlite_uint64;
790 #endif
791 typedef sqlite_int64 sqlite3_int64;
792 typedef sqlite_uint64 sqlite3_uint64;
793
794 /*
795 ** If compiling for a processor that lacks floating point support,
796 ** substitute integer for floating-point.
797 */
798 #ifdef SQLITE_OMIT_FLOATING_POINT
799 # define double sqlite3_int64
800 #endif
801
802 /*
803 ** CAPI3REF: Closing A Database Connection
804 **
805 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
806 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
807 ** successfullly destroyed and all associated resources are deallocated.
808 **
809 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
810 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
811 ** the [sqlite3] object prior to attempting to close the object.  ^If
812 ** sqlite3_close() is called on a [database connection] that still has
813 ** outstanding [prepared statements] or [BLOB handles], then it returns
814 ** SQLITE_BUSY.
815 **
816 ** ^If [sqlite3_close()] is invoked while a transaction is open,
817 ** the transaction is automatically rolled back.
818 **
819 ** The C parameter to [sqlite3_close(C)] must be either a NULL
820 ** pointer or an [sqlite3] object pointer obtained
821 ** from [sqlite3_open()], [sqlite3_open16()], or
822 ** [sqlite3_open_v2()], and not previously closed.
823 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
824 ** harmless no-op.
825 */
826 SQLITE_API int sqlite3_close(sqlite3 *);
827
828 /*
829 ** The type for a callback function.
830 ** This is legacy and deprecated.  It is included for historical
831 ** compatibility and is not documented.
832 */
833 typedef int (*sqlite3_callback)(void*,int,char**, char**);
834
835 /*
836 ** CAPI3REF: One-Step Query Execution Interface
837 **
838 ** The sqlite3_exec() interface is a convenience wrapper around
839 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
840 ** that allows an application to run multiple statements of SQL
841 ** without having to use a lot of C code. 
842 **
843 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
844 ** semicolon-separate SQL statements passed into its 2nd argument,
845 ** in the context of the [database connection] passed in as its 1st
846 ** argument.  ^If the callback function of the 3rd argument to
847 ** sqlite3_exec() is not NULL, then it is invoked for each result row
848 ** coming out of the evaluated SQL statements.  ^The 4th argument to
849 ** to sqlite3_exec() is relayed through to the 1st argument of each
850 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
851 ** is NULL, then no callback is ever invoked and result rows are
852 ** ignored.
853 **
854 ** ^If an error occurs while evaluating the SQL statements passed into
855 ** sqlite3_exec(), then execution of the current statement stops and
856 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
857 ** is not NULL then any error message is written into memory obtained
858 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
859 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
860 ** on error message strings returned through the 5th parameter of
861 ** of sqlite3_exec() after the error message string is no longer needed.
862 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
863 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
864 ** NULL before returning.
865 **
866 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
867 ** routine returns SQLITE_ABORT without invoking the callback again and
868 ** without running any subsequent SQL statements.
869 **
870 ** ^The 2nd argument to the sqlite3_exec() callback function is the
871 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
872 ** callback is an array of pointers to strings obtained as if from
873 ** [sqlite3_column_text()], one for each column.  ^If an element of a
874 ** result row is NULL then the corresponding string pointer for the
875 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
876 ** sqlite3_exec() callback is an array of pointers to strings where each
877 ** entry represents the name of corresponding result column as obtained
878 ** from [sqlite3_column_name()].
879 **
880 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
881 ** to an empty string, or a pointer that contains only whitespace and/or 
882 ** SQL comments, then no SQL statements are evaluated and the database
883 ** is not changed.
884 **
885 ** Restrictions:
886 **
887 ** <ul>
888 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
889 **      is a valid and open [database connection].
890 ** <li> The application must not close [database connection] specified by
891 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
892 ** <li> The application must not modify the SQL statement text passed into
893 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
894 ** </ul>
895 */
896 SQLITE_API int sqlite3_exec(
897   sqlite3*,                                  /* An open database */
898   const char *sql,                           /* SQL to be evaluated */
899   int (*callback)(void*,int,char**,char**),  /* Callback function */
900   void *,                                    /* 1st argument to callback */
901   char **errmsg                              /* Error msg written here */
902 );
903
904 /*
905 ** CAPI3REF: Result Codes
906 ** KEYWORDS: SQLITE_OK {error code} {error codes}
907 ** KEYWORDS: {result code} {result codes}
908 **
909 ** Many SQLite functions return an integer result code from the set shown
910 ** here in order to indicates success or failure.
911 **
912 ** New error codes may be added in future versions of SQLite.
913 **
914 ** See also: [SQLITE_IOERR_READ | extended result codes]
915 */
916 #define SQLITE_OK           0   /* Successful result */
917 /* beginning-of-error-codes */
918 #define SQLITE_ERROR        1   /* SQL error or missing database */
919 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
920 #define SQLITE_PERM         3   /* Access permission denied */
921 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
922 #define SQLITE_BUSY         5   /* The database file is locked */
923 #define SQLITE_LOCKED       6   /* A table in the database is locked */
924 #define SQLITE_NOMEM        7   /* A malloc() failed */
925 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
926 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
927 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
928 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
929 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
930 #define SQLITE_FULL        13   /* Insertion failed because database is full */
931 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
932 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
933 #define SQLITE_EMPTY       16   /* Database is empty */
934 #define SQLITE_SCHEMA      17   /* The database schema changed */
935 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
936 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
937 #define SQLITE_MISMATCH    20   /* Data type mismatch */
938 #define SQLITE_MISUSE      21   /* Library used incorrectly */
939 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
940 #define SQLITE_AUTH        23   /* Authorization denied */
941 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
942 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
943 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
944 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
945 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
946 /* end-of-error-codes */
947
948 /*
949 ** CAPI3REF: Extended Result Codes
950 ** KEYWORDS: {extended error code} {extended error codes}
951 ** KEYWORDS: {extended result code} {extended result codes}
952 **
953 ** In its default configuration, SQLite API routines return one of 26 integer
954 ** [SQLITE_OK | result codes].  However, experience has shown that many of
955 ** these result codes are too coarse-grained.  They do not provide as
956 ** much information about problems as programmers might like.  In an effort to
957 ** address this, newer versions of SQLite (version 3.3.8 and later) include
958 ** support for additional result codes that provide more detailed information
959 ** about errors. The extended result codes are enabled or disabled
960 ** on a per database connection basis using the
961 ** [sqlite3_extended_result_codes()] API.
962 **
963 ** Some of the available extended result codes are listed here.
964 ** One may expect the number of extended result codes will be expand
965 ** over time.  Software that uses extended result codes should expect
966 ** to see new result codes in future releases of SQLite.
967 **
968 ** The SQLITE_OK result code will never be extended.  It will always
969 ** be exactly zero.
970 */
971 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
972 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
973 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
974 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
975 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
976 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
977 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
978 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
979 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
980 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
981 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
982 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
983 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
984 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
985 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
986 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
987 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
988 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
989 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
990 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
991 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
992 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
993 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
994
995 /*
996 ** CAPI3REF: Flags For File Open Operations
997 **
998 ** These bit values are intended for use in the
999 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1000 ** in the 4th parameter to the xOpen method of the
1001 ** [sqlite3_vfs] object.
1002 */
1003 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1004 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1005 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1006 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1007 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1008 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1009 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1010 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1011 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1012 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1013 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1014 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1015 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1016 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1017 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1018 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1019 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1020 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1021
1022 /*
1023 ** CAPI3REF: Device Characteristics
1024 **
1025 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1026 ** object returns an integer which is a vector of the these
1027 ** bit values expressing I/O characteristics of the mass storage
1028 ** device that holds the file that the [sqlite3_io_methods]
1029 ** refers to.
1030 **
1031 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1032 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1033 ** mean that writes of blocks that are nnn bytes in size and
1034 ** are aligned to an address which is an integer multiple of
1035 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1036 ** that when data is appended to a file, the data is appended
1037 ** first then the size of the file is extended, never the other
1038 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1039 ** information is written to disk in the same order as calls
1040 ** to xWrite().
1041 */
1042 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1043 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1044 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1045 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1046 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1047 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1048 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1049 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1050 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1051 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1052 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1053 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1054
1055 /*
1056 ** CAPI3REF: File Locking Levels
1057 **
1058 ** SQLite uses one of these integer values as the second
1059 ** argument to calls it makes to the xLock() and xUnlock() methods
1060 ** of an [sqlite3_io_methods] object.
1061 */
1062 #define SQLITE_LOCK_NONE          0
1063 #define SQLITE_LOCK_SHARED        1
1064 #define SQLITE_LOCK_RESERVED      2
1065 #define SQLITE_LOCK_PENDING       3
1066 #define SQLITE_LOCK_EXCLUSIVE     4
1067
1068 /*
1069 ** CAPI3REF: Synchronization Type Flags
1070 **
1071 ** When SQLite invokes the xSync() method of an
1072 ** [sqlite3_io_methods] object it uses a combination of
1073 ** these integer values as the second argument.
1074 **
1075 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1076 ** sync operation only needs to flush data to mass storage.  Inode
1077 ** information need not be flushed. If the lower four bits of the flag
1078 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1079 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1080 ** to use Mac OS X style fullsync instead of fsync().
1081 */
1082 #define SQLITE_SYNC_NORMAL        0x00002
1083 #define SQLITE_SYNC_FULL          0x00003
1084 #define SQLITE_SYNC_DATAONLY      0x00010
1085
1086 /*
1087 ** CAPI3REF: OS Interface Open File Handle
1088 **
1089 ** An [sqlite3_file] object represents an open file in the 
1090 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1091 ** implementations will
1092 ** want to subclass this object by appending additional fields
1093 ** for their own use.  The pMethods entry is a pointer to an
1094 ** [sqlite3_io_methods] object that defines methods for performing
1095 ** I/O operations on the open file.
1096 */
1097 typedef struct sqlite3_file sqlite3_file;
1098 struct sqlite3_file {
1099   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1100 };
1101
1102 /*
1103 ** CAPI3REF: OS Interface File Virtual Methods Object
1104 **
1105 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1106 ** [sqlite3_file] object (or, more commonly, a subclass of the
1107 ** [sqlite3_file] object) with a pointer to an instance of this object.
1108 ** This object defines the methods used to perform various operations
1109 ** against the open file represented by the [sqlite3_file] object.
1110 **
1111 ** If the xOpen method sets the sqlite3_file.pMethods element 
1112 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1113 ** may be invoked even if the xOpen reported that it failed.  The
1114 ** only way to prevent a call to xClose following a failed xOpen
1115 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1116 **
1117 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1118 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1119 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1120 ** flag may be ORed in to indicate that only the data of the file
1121 ** and not its inode needs to be synced.
1122 **
1123 ** The integer values to xLock() and xUnlock() are one of
1124 ** <ul>
1125 ** <li> [SQLITE_LOCK_NONE],
1126 ** <li> [SQLITE_LOCK_SHARED],
1127 ** <li> [SQLITE_LOCK_RESERVED],
1128 ** <li> [SQLITE_LOCK_PENDING], or
1129 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1130 ** </ul>
1131 ** xLock() increases the lock. xUnlock() decreases the lock.
1132 ** The xCheckReservedLock() method checks whether any database connection,
1133 ** either in this process or in some other process, is holding a RESERVED,
1134 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1135 ** if such a lock exists and false otherwise.
1136 **
1137 ** The xFileControl() method is a generic interface that allows custom
1138 ** VFS implementations to directly control an open file using the
1139 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1140 ** integer opcode.  The third argument is a generic pointer intended to
1141 ** point to a structure that may contain arguments or space in which to
1142 ** write return values.  Potential uses for xFileControl() might be
1143 ** functions to enable blocking locks with timeouts, to change the
1144 ** locking strategy (for example to use dot-file locks), to inquire
1145 ** about the status of a lock, or to break stale locks.  The SQLite
1146 ** core reserves all opcodes less than 100 for its own use.
1147 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1148 ** Applications that define a custom xFileControl method should use opcodes
1149 ** greater than 100 to avoid conflicts.
1150 **
1151 ** The xSectorSize() method returns the sector size of the
1152 ** device that underlies the file.  The sector size is the
1153 ** minimum write that can be performed without disturbing
1154 ** other bytes in the file.  The xDeviceCharacteristics()
1155 ** method returns a bit vector describing behaviors of the
1156 ** underlying device:
1157 **
1158 ** <ul>
1159 ** <li> [SQLITE_IOCAP_ATOMIC]
1160 ** <li> [SQLITE_IOCAP_ATOMIC512]
1161 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1162 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1163 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1164 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1165 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1166 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1167 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1168 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1169 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1170 ** </ul>
1171 **
1172 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1173 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1174 ** mean that writes of blocks that are nnn bytes in size and
1175 ** are aligned to an address which is an integer multiple of
1176 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1177 ** that when data is appended to a file, the data is appended
1178 ** first then the size of the file is extended, never the other
1179 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1180 ** information is written to disk in the same order as calls
1181 ** to xWrite().
1182 **
1183 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1184 ** in the unread portions of the buffer with zeros.  A VFS that
1185 ** fails to zero-fill short reads might seem to work.  However,
1186 ** failure to zero-fill short reads will eventually lead to
1187 ** database corruption.
1188 */
1189 typedef struct sqlite3_io_methods sqlite3_io_methods;
1190 struct sqlite3_io_methods {
1191   int iVersion;
1192   int (*xClose)(sqlite3_file*);
1193   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1194   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1195   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1196   int (*xSync)(sqlite3_file*, int flags);
1197   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1198   int (*xLock)(sqlite3_file*, int);
1199   int (*xUnlock)(sqlite3_file*, int);
1200   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1201   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1202   int (*xSectorSize)(sqlite3_file*);
1203   int (*xDeviceCharacteristics)(sqlite3_file*);
1204   /* Methods above are valid for version 1 */
1205   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1206   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1207   void (*xShmBarrier)(sqlite3_file*);
1208   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1209   /* Methods above are valid for version 2 */
1210   /* Additional methods may be added in future releases */
1211 };
1212
1213 /*
1214 ** CAPI3REF: Standard File Control Opcodes
1215 **
1216 ** These integer constants are opcodes for the xFileControl method
1217 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1218 ** interface.
1219 **
1220 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1221 ** opcode causes the xFileControl method to write the current state of
1222 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1223 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1224 ** into an integer that the pArg argument points to. This capability
1225 ** is used during testing and only needs to be supported when SQLITE_TEST
1226 ** is defined.
1227 **
1228 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1229 ** layer a hint of how large the database file will grow to be during the
1230 ** current transaction.  This hint is not guaranteed to be accurate but it
1231 ** is often close.  The underlying VFS might choose to preallocate database
1232 ** file space based on this hint in order to help writes to the database
1233 ** file run faster.
1234 */
1235 #define SQLITE_FCNTL_LOCKSTATE        1
1236 #define SQLITE_GET_LOCKPROXYFILE      2
1237 #define SQLITE_SET_LOCKPROXYFILE      3
1238 #define SQLITE_LAST_ERRNO             4
1239 #define SQLITE_FCNTL_SIZE_HINT        5
1240
1241 /*
1242 ** CAPI3REF: Mutex Handle
1243 **
1244 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1245 ** abstract type for a mutex object.  The SQLite core never looks
1246 ** at the internal representation of an [sqlite3_mutex].  It only
1247 ** deals with pointers to the [sqlite3_mutex] object.
1248 **
1249 ** Mutexes are created using [sqlite3_mutex_alloc()].
1250 */
1251 typedef struct sqlite3_mutex sqlite3_mutex;
1252
1253 /*
1254 ** CAPI3REF: OS Interface Object
1255 **
1256 ** An instance of the sqlite3_vfs object defines the interface between
1257 ** the SQLite core and the underlying operating system.  The "vfs"
1258 ** in the name of the object stands for "virtual file system".
1259 **
1260 ** The value of the iVersion field is initially 1 but may be larger in
1261 ** future versions of SQLite.  Additional fields may be appended to this
1262 ** object when the iVersion value is increased.  Note that the structure
1263 ** of the sqlite3_vfs object changes in the transaction between
1264 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1265 ** modified.
1266 **
1267 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1268 ** structure used by this VFS.  mxPathname is the maximum length of
1269 ** a pathname in this VFS.
1270 **
1271 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1272 ** the pNext pointer.  The [sqlite3_vfs_register()]
1273 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1274 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1275 ** searches the list.  Neither the application code nor the VFS
1276 ** implementation should use the pNext pointer.
1277 **
1278 ** The pNext field is the only field in the sqlite3_vfs
1279 ** structure that SQLite will ever modify.  SQLite will only access
1280 ** or modify this field while holding a particular static mutex.
1281 ** The application should never modify anything within the sqlite3_vfs
1282 ** object once the object has been registered.
1283 **
1284 ** The zName field holds the name of the VFS module.  The name must
1285 ** be unique across all VFS modules.
1286 **
1287 ** SQLite will guarantee that the zFilename parameter to xOpen
1288 ** is either a NULL pointer or string obtained
1289 ** from xFullPathname().  SQLite further guarantees that
1290 ** the string will be valid and unchanged until xClose() is
1291 ** called. Because of the previous sentence,
1292 ** the [sqlite3_file] can safely store a pointer to the
1293 ** filename if it needs to remember the filename for some reason.
1294 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1295 ** must invent its own temporary name for the file.  Whenever the 
1296 ** xFilename parameter is NULL it will also be the case that the
1297 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1298 **
1299 ** The flags argument to xOpen() includes all bits set in
1300 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1301 ** or [sqlite3_open16()] is used, then flags includes at least
1302 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1303 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1304 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1305 **
1306 ** SQLite will also add one of the following flags to the xOpen()
1307 ** call, depending on the object being opened:
1308 **
1309 ** <ul>
1310 ** <li>  [SQLITE_OPEN_MAIN_DB]
1311 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1312 ** <li>  [SQLITE_OPEN_TEMP_DB]
1313 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1314 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1315 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1316 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1317 ** </ul>
1318 **
1319 ** The file I/O implementation can use the object type flags to
1320 ** change the way it deals with files.  For example, an application
1321 ** that does not care about crash recovery or rollback might make
1322 ** the open of a journal file a no-op.  Writes to this journal would
1323 ** also be no-ops, and any attempt to read the journal would return
1324 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1325 ** file will be doing page-aligned sector reads and writes in a random
1326 ** order and set up its I/O subsystem accordingly.
1327 **
1328 ** SQLite might also add one of the following flags to the xOpen method:
1329 **
1330 ** <ul>
1331 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1332 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1333 ** </ul>
1334 **
1335 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1336 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1337 ** will be set for TEMP  databases, journals and for subjournals.
1338 **
1339 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1340 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1341 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1342 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1343 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1344 ** be created, and that it is an error if it already exists.
1345 ** It is <i>not</i> used to indicate the file should be opened 
1346 ** for exclusive access.
1347 **
1348 ** At least szOsFile bytes of memory are allocated by SQLite
1349 ** to hold the  [sqlite3_file] structure passed as the third
1350 ** argument to xOpen.  The xOpen method does not have to
1351 ** allocate the structure; it should just fill it in.  Note that
1352 ** the xOpen method must set the sqlite3_file.pMethods to either
1353 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1354 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1355 ** element will be valid after xOpen returns regardless of the success
1356 ** or failure of the xOpen call.
1357 **
1358 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1359 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1360 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1361 ** to test whether a file is at least readable.   The file can be a
1362 ** directory.
1363 **
1364 ** SQLite will always allocate at least mxPathname+1 bytes for the
1365 ** output buffer xFullPathname.  The exact size of the output buffer
1366 ** is also passed as a parameter to both  methods. If the output buffer
1367 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1368 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1369 ** to prevent this by setting mxPathname to a sufficiently large value.
1370 **
1371 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1372 ** interfaces are not strictly a part of the filesystem, but they are
1373 ** included in the VFS structure for completeness.
1374 ** The xRandomness() function attempts to return nBytes bytes
1375 ** of good-quality randomness into zOut.  The return value is
1376 ** the actual number of bytes of randomness obtained.
1377 ** The xSleep() method causes the calling thread to sleep for at
1378 ** least the number of microseconds given.  The xCurrentTime()
1379 ** method returns a Julian Day Number for the current date and time as
1380 ** a floating point value.
1381 ** The xCurrentTimeInt64() method returns, as an integer, the Julian
1382 ** Day Number multipled by 86400000 (the number of milliseconds in 
1383 ** a 24-hour day).  
1384 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1385 ** date and time if that method is available (if iVersion is 2 or 
1386 ** greater and the function pointer is not NULL) and will fall back
1387 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1388 */
1389 typedef struct sqlite3_vfs sqlite3_vfs;
1390 struct sqlite3_vfs {
1391   int iVersion;            /* Structure version number (currently 2) */
1392   int szOsFile;            /* Size of subclassed sqlite3_file */
1393   int mxPathname;          /* Maximum file pathname length */
1394   sqlite3_vfs *pNext;      /* Next registered VFS */
1395   const char *zName;       /* Name of this virtual file system */
1396   void *pAppData;          /* Pointer to application-specific data */
1397   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1398                int flags, int *pOutFlags);
1399   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1400   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1401   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1402   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1403   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1404   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1405   void (*xDlClose)(sqlite3_vfs*, void*);
1406   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1407   int (*xSleep)(sqlite3_vfs*, int microseconds);
1408   int (*xCurrentTime)(sqlite3_vfs*, double*);
1409   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1410   /*
1411   ** The methods above are in version 1 of the sqlite_vfs object
1412   ** definition.  Those that follow are added in version 2 or later
1413   */
1414   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1415   /*
1416   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1417   ** New fields may be appended in figure versions.  The iVersion
1418   ** value will increment whenever this happens. 
1419   */
1420 };
1421
1422 /*
1423 ** CAPI3REF: Flags for the xAccess VFS method
1424 **
1425 ** These integer constants can be used as the third parameter to
1426 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1427 ** what kind of permissions the xAccess method is looking for.
1428 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1429 ** simply checks whether the file exists.
1430 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1431 ** checks whether the named directory is both readable and writable
1432 ** (in other words, if files can be added, removed, and renamed within
1433 ** the directory).
1434 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1435 ** [temp_store_directory pragma], though this could change in a future
1436 ** release of SQLite.
1437 ** With SQLITE_ACCESS_READ, the xAccess method
1438 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1439 ** currently unused, though it might be used in a future release of
1440 ** SQLite.
1441 */
1442 #define SQLITE_ACCESS_EXISTS    0
1443 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1444 #define SQLITE_ACCESS_READ      2   /* Unused */
1445
1446 /*
1447 ** CAPI3REF: Flags for the xShmLock VFS method
1448 **
1449 ** These integer constants define the various locking operations
1450 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1451 ** following are the only legal combinations of flags to the
1452 ** xShmLock method:
1453 **
1454 ** <ul>
1455 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1456 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1457 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1458 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1459 ** </ul>
1460 **
1461 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1462 ** was given no the corresponding lock.  
1463 **
1464 ** The xShmLock method can transition between unlocked and SHARED or
1465 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1466 ** and EXCLUSIVE.
1467 */
1468 #define SQLITE_SHM_UNLOCK       1
1469 #define SQLITE_SHM_LOCK         2
1470 #define SQLITE_SHM_SHARED       4
1471 #define SQLITE_SHM_EXCLUSIVE    8
1472
1473 /*
1474 ** CAPI3REF: Maximum xShmLock index
1475 **
1476 ** The xShmLock method on [sqlite3_io_methods] may use values
1477 ** between 0 and this upper bound as its "offset" argument.
1478 ** The SQLite core will never attempt to acquire or release a
1479 ** lock outside of this range
1480 */
1481 #define SQLITE_SHM_NLOCK        8
1482
1483
1484 /*
1485 ** CAPI3REF: Initialize The SQLite Library
1486 **
1487 ** ^The sqlite3_initialize() routine initializes the
1488 ** SQLite library.  ^The sqlite3_shutdown() routine
1489 ** deallocates any resources that were allocated by sqlite3_initialize().
1490 ** These routines are designed to aid in process initialization and
1491 ** shutdown on embedded systems.  Workstation applications using
1492 ** SQLite normally do not need to invoke either of these routines.
1493 **
1494 ** A call to sqlite3_initialize() is an "effective" call if it is
1495 ** the first time sqlite3_initialize() is invoked during the lifetime of
1496 ** the process, or if it is the first time sqlite3_initialize() is invoked
1497 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1498 ** of sqlite3_initialize() does any initialization.  All other calls
1499 ** are harmless no-ops.)^
1500 **
1501 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1502 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1503 ** an effective call to sqlite3_shutdown() does any deinitialization.
1504 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1505 **
1506 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1507 ** is not.  The sqlite3_shutdown() interface must only be called from a
1508 ** single thread.  All open [database connections] must be closed and all
1509 ** other SQLite resources must be deallocated prior to invoking
1510 ** sqlite3_shutdown().
1511 **
1512 ** Among other things, ^sqlite3_initialize() will invoke
1513 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1514 ** will invoke sqlite3_os_end().
1515 **
1516 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1517 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1518 ** the library (perhaps it is unable to allocate a needed resource such
1519 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1520 **
1521 ** ^The sqlite3_initialize() routine is called internally by many other
1522 ** SQLite interfaces so that an application usually does not need to
1523 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1524 ** calls sqlite3_initialize() so the SQLite library will be automatically
1525 ** initialized when [sqlite3_open()] is called if it has not be initialized
1526 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1527 ** compile-time option, then the automatic calls to sqlite3_initialize()
1528 ** are omitted and the application must call sqlite3_initialize() directly
1529 ** prior to using any other SQLite interface.  For maximum portability,
1530 ** it is recommended that applications always invoke sqlite3_initialize()
1531 ** directly prior to using any other SQLite interface.  Future releases
1532 ** of SQLite may require this.  In other words, the behavior exhibited
1533 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1534 ** default behavior in some future release of SQLite.
1535 **
1536 ** The sqlite3_os_init() routine does operating-system specific
1537 ** initialization of the SQLite library.  The sqlite3_os_end()
1538 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1539 ** performed by these routines include allocation or deallocation
1540 ** of static resources, initialization of global variables,
1541 ** setting up a default [sqlite3_vfs] module, or setting up
1542 ** a default configuration using [sqlite3_config()].
1543 **
1544 ** The application should never invoke either sqlite3_os_init()
1545 ** or sqlite3_os_end() directly.  The application should only invoke
1546 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1547 ** interface is called automatically by sqlite3_initialize() and
1548 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1549 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1550 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1551 ** When [custom builds | built for other platforms]
1552 ** (using the [SQLITE_OS_OTHER=1] compile-time
1553 ** option) the application must supply a suitable implementation for
1554 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1555 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1556 ** must return [SQLITE_OK] on success and some other [error code] upon
1557 ** failure.
1558 */
1559 SQLITE_API int sqlite3_initialize(void);
1560 SQLITE_API int sqlite3_shutdown(void);
1561 SQLITE_API int sqlite3_os_init(void);
1562 SQLITE_API int sqlite3_os_end(void);
1563
1564 /*
1565 ** CAPI3REF: Configuring The SQLite Library
1566 **
1567 ** The sqlite3_config() interface is used to make global configuration
1568 ** changes to SQLite in order to tune SQLite to the specific needs of
1569 ** the application.  The default configuration is recommended for most
1570 ** applications and so this routine is usually not necessary.  It is
1571 ** provided to support rare applications with unusual needs.
1572 **
1573 ** The sqlite3_config() interface is not threadsafe.  The application
1574 ** must insure that no other SQLite interfaces are invoked by other
1575 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1576 ** may only be invoked prior to library initialization using
1577 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1578 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1579 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1580 ** Note, however, that ^sqlite3_config() can be called as part of the
1581 ** implementation of an application-defined [sqlite3_os_init()].
1582 **
1583 ** The first argument to sqlite3_config() is an integer
1584 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1585 ** what property of SQLite is to be configured.  Subsequent arguments
1586 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1587 ** in the first argument.
1588 **
1589 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1590 ** ^If the option is unknown or SQLite is unable to set the option
1591 ** then this routine returns a non-zero [error code].
1592 */
1593 SQLITE_API int sqlite3_config(int, ...);
1594
1595 /*
1596 ** CAPI3REF: Configure database connections
1597 **
1598 ** The sqlite3_db_config() interface is used to make configuration
1599 ** changes to a [database connection].  The interface is similar to
1600 ** [sqlite3_config()] except that the changes apply to a single
1601 ** [database connection] (specified in the first argument).  The
1602 ** sqlite3_db_config() interface should only be used immediately after
1603 ** the database connection is created using [sqlite3_open()],
1604 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1605 **
1606 ** The second argument to sqlite3_db_config(D,V,...)  is the
1607 ** configuration verb - an integer code that indicates what
1608 ** aspect of the [database connection] is being configured.
1609 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1610 ** New verbs are likely to be added in future releases of SQLite.
1611 ** Additional arguments depend on the verb.
1612 **
1613 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1614 ** the call is considered successful.
1615 */
1616 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1617
1618 /*
1619 ** CAPI3REF: Memory Allocation Routines
1620 **
1621 ** An instance of this object defines the interface between SQLite
1622 ** and low-level memory allocation routines.
1623 **
1624 ** This object is used in only one place in the SQLite interface.
1625 ** A pointer to an instance of this object is the argument to
1626 ** [sqlite3_config()] when the configuration option is
1627 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1628 ** By creating an instance of this object
1629 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1630 ** during configuration, an application can specify an alternative
1631 ** memory allocation subsystem for SQLite to use for all of its
1632 ** dynamic memory needs.
1633 **
1634 ** Note that SQLite comes with several [built-in memory allocators]
1635 ** that are perfectly adequate for the overwhelming majority of applications
1636 ** and that this object is only useful to a tiny minority of applications
1637 ** with specialized memory allocation requirements.  This object is
1638 ** also used during testing of SQLite in order to specify an alternative
1639 ** memory allocator that simulates memory out-of-memory conditions in
1640 ** order to verify that SQLite recovers gracefully from such
1641 ** conditions.
1642 **
1643 ** The xMalloc and xFree methods must work like the
1644 ** malloc() and free() functions from the standard C library.
1645 ** The xRealloc method must work like realloc() from the standard C library
1646 ** with the exception that if the second argument to xRealloc is zero,
1647 ** xRealloc must be a no-op - it must not perform any allocation or
1648 ** deallocation.  ^SQLite guarantees that the second argument to
1649 ** xRealloc is always a value returned by a prior call to xRoundup.
1650 ** And so in cases where xRoundup always returns a positive number,
1651 ** xRealloc can perform exactly as the standard library realloc() and
1652 ** still be in compliance with this specification.
1653 **
1654 ** xSize should return the allocated size of a memory allocation
1655 ** previously obtained from xMalloc or xRealloc.  The allocated size
1656 ** is always at least as big as the requested size but may be larger.
1657 **
1658 ** The xRoundup method returns what would be the allocated size of
1659 ** a memory allocation given a particular requested size.  Most memory
1660 ** allocators round up memory allocations at least to the next multiple
1661 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1662 ** Every memory allocation request coming in through [sqlite3_malloc()]
1663 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1664 ** that causes the corresponding memory allocation to fail.
1665 **
1666 ** The xInit method initializes the memory allocator.  (For example,
1667 ** it might allocate any require mutexes or initialize internal data
1668 ** structures.  The xShutdown method is invoked (indirectly) by
1669 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1670 ** by xInit.  The pAppData pointer is used as the only parameter to
1671 ** xInit and xShutdown.
1672 **
1673 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1674 ** the xInit method, so the xInit method need not be threadsafe.  The
1675 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1676 ** not need to be threadsafe either.  For all other methods, SQLite
1677 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1678 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1679 ** it is by default) and so the methods are automatically serialized.
1680 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1681 ** methods must be threadsafe or else make their own arrangements for
1682 ** serialization.
1683 **
1684 ** SQLite will never invoke xInit() more than once without an intervening
1685 ** call to xShutdown().
1686 */
1687 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1688 struct sqlite3_mem_methods {
1689   void *(*xMalloc)(int);         /* Memory allocation function */
1690   void (*xFree)(void*);          /* Free a prior allocation */
1691   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1692   int (*xSize)(void*);           /* Return the size of an allocation */
1693   int (*xRoundup)(int);          /* Round up request size to allocation size */
1694   int (*xInit)(void*);           /* Initialize the memory allocator */
1695   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1696   void *pAppData;                /* Argument to xInit() and xShutdown() */
1697 };
1698
1699 /*
1700 ** CAPI3REF: Configuration Options
1701 **
1702 ** These constants are the available integer configuration options that
1703 ** can be passed as the first argument to the [sqlite3_config()] interface.
1704 **
1705 ** New configuration options may be added in future releases of SQLite.
1706 ** Existing configuration options might be discontinued.  Applications
1707 ** should check the return code from [sqlite3_config()] to make sure that
1708 ** the call worked.  The [sqlite3_config()] interface will return a
1709 ** non-zero [error code] if a discontinued or unsupported configuration option
1710 ** is invoked.
1711 **
1712 ** <dl>
1713 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1714 ** <dd>There are no arguments to this option.  ^This option sets the
1715 ** [threading mode] to Single-thread.  In other words, it disables
1716 ** all mutexing and puts SQLite into a mode where it can only be used
1717 ** by a single thread.   ^If SQLite is compiled with
1718 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1719 ** it is not possible to change the [threading mode] from its default
1720 ** value of Single-thread and so [sqlite3_config()] will return 
1721 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1722 ** configuration option.</dd>
1723 **
1724 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1725 ** <dd>There are no arguments to this option.  ^This option sets the
1726 ** [threading mode] to Multi-thread.  In other words, it disables
1727 ** mutexing on [database connection] and [prepared statement] objects.
1728 ** The application is responsible for serializing access to
1729 ** [database connections] and [prepared statements].  But other mutexes
1730 ** are enabled so that SQLite will be safe to use in a multi-threaded
1731 ** environment as long as no two threads attempt to use the same
1732 ** [database connection] at the same time.  ^If SQLite is compiled with
1733 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1734 ** it is not possible to set the Multi-thread [threading mode] and
1735 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1736 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1737 **
1738 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1739 ** <dd>There are no arguments to this option.  ^This option sets the
1740 ** [threading mode] to Serialized. In other words, this option enables
1741 ** all mutexes including the recursive
1742 ** mutexes on [database connection] and [prepared statement] objects.
1743 ** In this mode (which is the default when SQLite is compiled with
1744 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1745 ** to [database connections] and [prepared statements] so that the
1746 ** application is free to use the same [database connection] or the
1747 ** same [prepared statement] in different threads at the same time.
1748 ** ^If SQLite is compiled with
1749 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1750 ** it is not possible to set the Serialized [threading mode] and
1751 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1752 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1753 **
1754 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1755 ** <dd> ^(This option takes a single argument which is a pointer to an
1756 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1757 ** alternative low-level memory allocation routines to be used in place of
1758 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1759 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1760 ** before the [sqlite3_config()] call returns.</dd>
1761 **
1762 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1763 ** <dd> ^(This option takes a single argument which is a pointer to an
1764 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1765 ** structure is filled with the currently defined memory allocation routines.)^
1766 ** This option can be used to overload the default memory allocation
1767 ** routines with a wrapper that simulations memory allocation failure or
1768 ** tracks memory usage, for example. </dd>
1769 **
1770 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1771 ** <dd> ^This option takes single argument of type int, interpreted as a 
1772 ** boolean, which enables or disables the collection of memory allocation 
1773 ** statistics. ^(When memory allocation statistics are disabled, the 
1774 ** following SQLite interfaces become non-operational:
1775 **   <ul>
1776 **   <li> [sqlite3_memory_used()]
1777 **   <li> [sqlite3_memory_highwater()]
1778 **   <li> [sqlite3_soft_heap_limit()]
1779 **   <li> [sqlite3_status()]
1780 **   </ul>)^
1781 ** ^Memory allocation statistics are enabled by default unless SQLite is
1782 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1783 ** allocation statistics are disabled by default.
1784 ** </dd>
1785 **
1786 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1787 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1788 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1789 ** aligned memory buffer from which the scrach allocations will be
1790 ** drawn, the size of each scratch allocation (sz),
1791 ** and the maximum number of scratch allocations (N).  The sz
1792 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1793 ** larger than the actual scratch space required due to internal overhead.
1794 ** The first argument must be a pointer to an 8-byte aligned buffer
1795 ** of at least sz*N bytes of memory.
1796 ** ^SQLite will use no more than one scratch buffer per thread.  So
1797 ** N should be set to the expected maximum number of threads.  ^SQLite will
1798 ** never require a scratch buffer that is more than 6 times the database
1799 ** page size. ^If SQLite needs needs additional scratch memory beyond 
1800 ** what is provided by this configuration option, then 
1801 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1802 **
1803 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1804 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1805 ** the database page cache with the default page cache implemenation.  
1806 ** This configuration should not be used if an application-define page
1807 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1808 ** There are three arguments to this option: A pointer to 8-byte aligned
1809 ** memory, the size of each page buffer (sz), and the number of pages (N).
1810 ** The sz argument should be the size of the largest database page
1811 ** (a power of two between 512 and 32768) plus a little extra for each
1812 ** page header.  ^The page header size is 20 to 40 bytes depending on
1813 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1814 ** to make sz a little too large.  The first
1815 ** argument should point to an allocation of at least sz*N bytes of memory.
1816 ** ^SQLite will use the memory provided by the first argument to satisfy its
1817 ** memory needs for the first N pages that it adds to cache.  ^If additional
1818 ** page cache memory is needed beyond what is provided by this option, then
1819 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1820 ** ^The implementation might use one or more of the N buffers to hold 
1821 ** memory accounting information. The pointer in the first argument must
1822 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1823 ** will be undefined.</dd>
1824 **
1825 ** <dt>SQLITE_CONFIG_HEAP</dt>
1826 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1827 ** for all of its dynamic memory allocation needs beyond those provided
1828 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1829 ** There are three arguments: An 8-byte aligned pointer to the memory,
1830 ** the number of bytes in the memory buffer, and the minimum allocation size.
1831 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1832 ** to using its default memory allocator (the system malloc() implementation),
1833 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1834 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1835 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1836 ** allocator is engaged to handle all of SQLites memory allocation needs.
1837 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1838 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1839 **
1840 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1841 ** <dd> ^(This option takes a single argument which is a pointer to an
1842 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1843 ** alternative low-level mutex routines to be used in place
1844 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1845 ** content of the [sqlite3_mutex_methods] structure before the call to
1846 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1847 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1848 ** the entire mutexing subsystem is omitted from the build and hence calls to
1849 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1850 ** return [SQLITE_ERROR].</dd>
1851 **
1852 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1853 ** <dd> ^(This option takes a single argument which is a pointer to an
1854 ** instance of the [sqlite3_mutex_methods] structure.  The
1855 ** [sqlite3_mutex_methods]
1856 ** structure is filled with the currently defined mutex routines.)^
1857 ** This option can be used to overload the default mutex allocation
1858 ** routines with a wrapper used to track mutex usage for performance
1859 ** profiling or testing, for example.   ^If SQLite is compiled with
1860 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1861 ** the entire mutexing subsystem is omitted from the build and hence calls to
1862 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1863 ** return [SQLITE_ERROR].</dd>
1864 **
1865 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1866 ** <dd> ^(This option takes two arguments that determine the default
1867 ** memory allocation for the lookaside memory allocator on each
1868 ** [database connection].  The first argument is the
1869 ** size of each lookaside buffer slot and the second is the number of
1870 ** slots allocated to each database connection.)^  ^(This option sets the
1871 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1872 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1873 ** configuration on individual connections.)^ </dd>
1874 **
1875 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1876 ** <dd> ^(This option takes a single argument which is a pointer to
1877 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1878 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1879 ** object and uses it for page cache memory allocations.</dd>
1880 **
1881 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1882 ** <dd> ^(This option takes a single argument which is a pointer to an
1883 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1884 ** page cache implementation into that object.)^ </dd>
1885 **
1886 ** <dt>SQLITE_CONFIG_LOG</dt>
1887 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1888 ** function with a call signature of void(*)(void*,int,const char*), 
1889 ** and a pointer to void. ^If the function pointer is not NULL, it is
1890 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1891 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1892 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1893 ** passed through as the first parameter to the application-defined logger
1894 ** function whenever that function is invoked.  ^The second parameter to
1895 ** the logger function is a copy of the first parameter to the corresponding
1896 ** [sqlite3_log()] call and is intended to be a [result code] or an
1897 ** [extended result code].  ^The third parameter passed to the logger is
1898 ** log message after formatting via [sqlite3_snprintf()].
1899 ** The SQLite logging interface is not reentrant; the logger function
1900 ** supplied by the application must not invoke any SQLite interface.
1901 ** In a multi-threaded application, the application-defined logger
1902 ** function must be threadsafe. </dd>
1903 **
1904 ** </dl>
1905 */
1906 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1907 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1908 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1909 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1910 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1911 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1912 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1913 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1914 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1915 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1916 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1917 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1918 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1919 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1920 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1921 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1922
1923 /*
1924 ** CAPI3REF: Database Connection Configuration Options
1925 **
1926 ** These constants are the available integer configuration options that
1927 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1928 **
1929 ** New configuration options may be added in future releases of SQLite.
1930 ** Existing configuration options might be discontinued.  Applications
1931 ** should check the return code from [sqlite3_db_config()] to make sure that
1932 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1933 ** non-zero [error code] if a discontinued or unsupported configuration option
1934 ** is invoked.
1935 **
1936 ** <dl>
1937 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1938 ** <dd> ^This option takes three additional arguments that determine the 
1939 ** [lookaside memory allocator] configuration for the [database connection].
1940 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1941 ** pointer to an memory buffer to use for lookaside memory.
1942 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1943 ** may be NULL in which case SQLite will allocate the
1944 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1945 ** size of each lookaside buffer slot.  ^The third argument is the number of
1946 ** slots.  The size of the buffer in the first argument must be greater than
1947 ** or equal to the product of the second and third arguments.  The buffer
1948 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1949 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1950 ** rounded down to the next smaller
1951 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1952 **
1953 ** </dl>
1954 */
1955 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1956
1957
1958 /*
1959 ** CAPI3REF: Enable Or Disable Extended Result Codes
1960 **
1961 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1962 ** [extended result codes] feature of SQLite. ^The extended result
1963 ** codes are disabled by default for historical compatibility.
1964 */
1965 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1966
1967 /*
1968 ** CAPI3REF: Last Insert Rowid
1969 **
1970 ** ^Each entry in an SQLite table has a unique 64-bit signed
1971 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1972 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1973 ** names are not also used by explicitly declared columns. ^If
1974 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1975 ** is another alias for the rowid.
1976 **
1977 ** ^This routine returns the [rowid] of the most recent
1978 ** successful [INSERT] into the database from the [database connection]
1979 ** in the first argument.  ^If no successful [INSERT]s
1980 ** have ever occurred on that database connection, zero is returned.
1981 **
1982 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1983 ** row is returned by this routine as long as the trigger is running.
1984 ** But once the trigger terminates, the value returned by this routine
1985 ** reverts to the last value inserted before the trigger fired.)^
1986 **
1987 ** ^An [INSERT] that fails due to a constraint violation is not a
1988 ** successful [INSERT] and does not change the value returned by this
1989 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1990 ** and INSERT OR ABORT make no changes to the return value of this
1991 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
1992 ** encounters a constraint violation, it does not fail.  The
1993 ** INSERT continues to completion after deleting rows that caused
1994 ** the constraint problem so INSERT OR REPLACE will always change
1995 ** the return value of this interface.)^
1996 **
1997 ** ^For the purposes of this routine, an [INSERT] is considered to
1998 ** be successful even if it is subsequently rolled back.
1999 **
2000 ** This function is accessible to SQL statements via the
2001 ** [last_insert_rowid() SQL function].
2002 **
2003 ** If a separate thread performs a new [INSERT] on the same
2004 ** database connection while the [sqlite3_last_insert_rowid()]
2005 ** function is running and thus changes the last insert [rowid],
2006 ** then the value returned by [sqlite3_last_insert_rowid()] is
2007 ** unpredictable and might not equal either the old or the new
2008 ** last insert [rowid].
2009 */
2010 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2011
2012 /*
2013 ** CAPI3REF: Count The Number Of Rows Modified
2014 **
2015 ** ^This function returns the number of database rows that were changed
2016 ** or inserted or deleted by the most recently completed SQL statement
2017 ** on the [database connection] specified by the first parameter.
2018 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2019 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2020 ** triggers or [foreign key actions] are not counted.)^ Use the
2021 ** [sqlite3_total_changes()] function to find the total number of changes
2022 ** including changes caused by triggers and foreign key actions.
2023 **
2024 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2025 ** are not counted.  Only real table changes are counted.
2026 **
2027 ** ^(A "row change" is a change to a single row of a single table
2028 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2029 ** are changed as side effects of [REPLACE] constraint resolution,
2030 ** rollback, ABORT processing, [DROP TABLE], or by any other
2031 ** mechanisms do not count as direct row changes.)^
2032 **
2033 ** A "trigger context" is a scope of execution that begins and
2034 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2035 ** Most SQL statements are
2036 ** evaluated outside of any trigger.  This is the "top level"
2037 ** trigger context.  If a trigger fires from the top level, a
2038 ** new trigger context is entered for the duration of that one
2039 ** trigger.  Subtriggers create subcontexts for their duration.
2040 **
2041 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2042 ** not create a new trigger context.
2043 **
2044 ** ^This function returns the number of direct row changes in the
2045 ** most recent INSERT, UPDATE, or DELETE statement within the same
2046 ** trigger context.
2047 **
2048 ** ^Thus, when called from the top level, this function returns the
2049 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2050 ** that also occurred at the top level.  ^(Within the body of a trigger,
2051 ** the sqlite3_changes() interface can be called to find the number of
2052 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2053 ** statement within the body of the same trigger.
2054 ** However, the number returned does not include changes
2055 ** caused by subtriggers since those have their own context.)^
2056 **
2057 ** See also the [sqlite3_total_changes()] interface, the
2058 ** [count_changes pragma], and the [changes() SQL function].
2059 **
2060 ** If a separate thread makes changes on the same database connection
2061 ** while [sqlite3_changes()] is running then the value returned
2062 ** is unpredictable and not meaningful.
2063 */
2064 SQLITE_API int sqlite3_changes(sqlite3*);
2065
2066 /*
2067 ** CAPI3REF: Total Number Of Rows Modified
2068 **
2069 ** ^This function returns the number of row changes caused by [INSERT],
2070 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2071 ** ^(The count returned by sqlite3_total_changes() includes all changes
2072 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2073 ** [foreign key actions]. However,
2074 ** the count does not include changes used to implement [REPLACE] constraints,
2075 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2076 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2077 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2078 ** are counted.)^
2079 ** ^The sqlite3_total_changes() function counts the changes as soon as
2080 ** the statement that makes them is completed (when the statement handle
2081 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2082 **
2083 ** See also the [sqlite3_changes()] interface, the
2084 ** [count_changes pragma], and the [total_changes() SQL function].
2085 **
2086 ** If a separate thread makes changes on the same database connection
2087 ** while [sqlite3_total_changes()] is running then the value
2088 ** returned is unpredictable and not meaningful.
2089 */
2090 SQLITE_API int sqlite3_total_changes(sqlite3*);
2091
2092 /*
2093 ** CAPI3REF: Interrupt A Long-Running Query
2094 **
2095 ** ^This function causes any pending database operation to abort and
2096 ** return at its earliest opportunity. This routine is typically
2097 ** called in response to a user action such as pressing "Cancel"
2098 ** or Ctrl-C where the user wants a long query operation to halt
2099 ** immediately.
2100 **
2101 ** ^It is safe to call this routine from a thread different from the
2102 ** thread that is currently running the database operation.  But it
2103 ** is not safe to call this routine with a [database connection] that
2104 ** is closed or might close before sqlite3_interrupt() returns.
2105 **
2106 ** ^If an SQL operation is very nearly finished at the time when
2107 ** sqlite3_interrupt() is called, then it might not have an opportunity
2108 ** to be interrupted and might continue to completion.
2109 **
2110 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2111 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2112 ** that is inside an explicit transaction, then the entire transaction
2113 ** will be rolled back automatically.
2114 **
2115 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2116 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2117 ** that are started after the sqlite3_interrupt() call and before the 
2118 ** running statements reaches zero are interrupted as if they had been
2119 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2120 ** that are started after the running statement count reaches zero are
2121 ** not effected by the sqlite3_interrupt().
2122 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2123 ** SQL statements is a no-op and has no effect on SQL statements
2124 ** that are started after the sqlite3_interrupt() call returns.
2125 **
2126 ** If the database connection closes while [sqlite3_interrupt()]
2127 ** is running then bad things will likely happen.
2128 */
2129 SQLITE_API void sqlite3_interrupt(sqlite3*);
2130
2131 /*
2132 ** CAPI3REF: Determine If An SQL Statement Is Complete
2133 **
2134 ** These routines are useful during command-line input to determine if the
2135 ** currently entered text seems to form a complete SQL statement or
2136 ** if additional input is needed before sending the text into
2137 ** SQLite for parsing.  ^These routines return 1 if the input string
2138 ** appears to be a complete SQL statement.  ^A statement is judged to be
2139 ** complete if it ends with a semicolon token and is not a prefix of a
2140 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2141 ** string literals or quoted identifier names or comments are not
2142 ** independent tokens (they are part of the token in which they are
2143 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2144 ** and comments that follow the final semicolon are ignored.
2145 **
2146 ** ^These routines return 0 if the statement is incomplete.  ^If a
2147 ** memory allocation fails, then SQLITE_NOMEM is returned.
2148 **
2149 ** ^These routines do not parse the SQL statements thus
2150 ** will not detect syntactically incorrect SQL.
2151 **
2152 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2153 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2154 ** automatically by sqlite3_complete16().  If that initialization fails,
2155 ** then the return value from sqlite3_complete16() will be non-zero
2156 ** regardless of whether or not the input SQL is complete.)^
2157 **
2158 ** The input to [sqlite3_complete()] must be a zero-terminated
2159 ** UTF-8 string.
2160 **
2161 ** The input to [sqlite3_complete16()] must be a zero-terminated
2162 ** UTF-16 string in native byte order.
2163 */
2164 SQLITE_API int sqlite3_complete(const char *sql);
2165 SQLITE_API int sqlite3_complete16(const void *sql);
2166
2167 /*
2168 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2169 **
2170 ** ^This routine sets a callback function that might be invoked whenever
2171 ** an attempt is made to open a database table that another thread
2172 ** or process has locked.
2173 **
2174 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2175 ** is returned immediately upon encountering the lock.  ^If the busy callback
2176 ** is not NULL, then the callback might be invoked with two arguments.
2177 **
2178 ** ^The first argument to the busy handler is a copy of the void* pointer which
2179 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2180 ** the busy handler callback is the number of times that the busy handler has
2181 ** been invoked for this locking event.  ^If the
2182 ** busy callback returns 0, then no additional attempts are made to
2183 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2184 ** ^If the callback returns non-zero, then another attempt
2185 ** is made to open the database for reading and the cycle repeats.
2186 **
2187 ** The presence of a busy handler does not guarantee that it will be invoked
2188 ** when there is lock contention. ^If SQLite determines that invoking the busy
2189 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2190 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2191 ** Consider a scenario where one process is holding a read lock that
2192 ** it is trying to promote to a reserved lock and
2193 ** a second process is holding a reserved lock that it is trying
2194 ** to promote to an exclusive lock.  The first process cannot proceed
2195 ** because it is blocked by the second and the second process cannot
2196 ** proceed because it is blocked by the first.  If both processes
2197 ** invoke the busy handlers, neither will make any progress.  Therefore,
2198 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2199 ** will induce the first process to release its read lock and allow
2200 ** the second process to proceed.
2201 **
2202 ** ^The default busy callback is NULL.
2203 **
2204 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2205 ** when SQLite is in the middle of a large transaction where all the
2206 ** changes will not fit into the in-memory cache.  SQLite will
2207 ** already hold a RESERVED lock on the database file, but it needs
2208 ** to promote this lock to EXCLUSIVE so that it can spill cache
2209 ** pages into the database file without harm to concurrent
2210 ** readers.  ^If it is unable to promote the lock, then the in-memory
2211 ** cache will be left in an inconsistent state and so the error
2212 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2213 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2214 ** forces an automatic rollback of the changes.  See the
2215 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2216 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2217 ** this is important.
2218 **
2219 ** ^(There can only be a single busy handler defined for each
2220 ** [database connection].  Setting a new busy handler clears any
2221 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2222 ** will also set or clear the busy handler.
2223 **
2224 ** The busy callback should not take any actions which modify the
2225 ** database connection that invoked the busy handler.  Any such actions
2226 ** result in undefined behavior.
2227 ** 
2228 ** A busy handler must not close the database connection
2229 ** or [prepared statement] that invoked the busy handler.
2230 */
2231 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2232
2233 /*
2234 ** CAPI3REF: Set A Busy Timeout
2235 **
2236 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2237 ** for a specified amount of time when a table is locked.  ^The handler
2238 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2239 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2240 ** the handler returns 0 which causes [sqlite3_step()] to return
2241 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2242 **
2243 ** ^Calling this routine with an argument less than or equal to zero
2244 ** turns off all busy handlers.
2245 **
2246 ** ^(There can only be a single busy handler for a particular
2247 ** [database connection] any any given moment.  If another busy handler
2248 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2249 ** this routine, that other busy handler is cleared.)^
2250 */
2251 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2252
2253 /*
2254 ** CAPI3REF: Convenience Routines For Running Queries
2255 **
2256 ** Definition: A <b>result table</b> is memory data structure created by the
2257 ** [sqlite3_get_table()] interface.  A result table records the
2258 ** complete query results from one or more queries.
2259 **
2260 ** The table conceptually has a number of rows and columns.  But
2261 ** these numbers are not part of the result table itself.  These
2262 ** numbers are obtained separately.  Let N be the number of rows
2263 ** and M be the number of columns.
2264 **
2265 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2266 ** There are (N+1)*M elements in the array.  The first M pointers point
2267 ** to zero-terminated strings that  contain the names of the columns.
2268 ** The remaining entries all point to query results.  NULL values result
2269 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2270 ** string representation as returned by [sqlite3_column_text()].
2271 **
2272 ** A result table might consist of one or more memory allocations.
2273 ** It is not safe to pass a result table directly to [sqlite3_free()].
2274 ** A result table should be deallocated using [sqlite3_free_table()].
2275 **
2276 ** As an example of the result table format, suppose a query result
2277 ** is as follows:
2278 **
2279 ** <blockquote><pre>
2280 **        Name        | Age
2281 **        -----------------------
2282 **        Alice       | 43
2283 **        Bob         | 28
2284 **        Cindy       | 21
2285 ** </pre></blockquote>
2286 **
2287 ** There are two column (M==2) and three rows (N==3).  Thus the
2288 ** result table has 8 entries.  Suppose the result table is stored
2289 ** in an array names azResult.  Then azResult holds this content:
2290 **
2291 ** <blockquote><pre>
2292 **        azResult&#91;0] = "Name";
2293 **        azResult&#91;1] = "Age";
2294 **        azResult&#91;2] = "Alice";
2295 **        azResult&#91;3] = "43";
2296 **        azResult&#91;4] = "Bob";
2297 **        azResult&#91;5] = "28";
2298 **        azResult&#91;6] = "Cindy";
2299 **        azResult&#91;7] = "21";
2300 ** </pre></blockquote>
2301 **
2302 ** ^The sqlite3_get_table() function evaluates one or more
2303 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2304 ** string of its 2nd parameter and returns a result table to the
2305 ** pointer given in its 3rd parameter.
2306 **
2307 ** After the application has finished with the result from sqlite3_get_table(),
2308 ** it should pass the result table pointer to sqlite3_free_table() in order to
2309 ** release the memory that was malloced.  Because of the way the
2310 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2311 ** function must not try to call [sqlite3_free()] directly.  Only
2312 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2313 **
2314 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2315 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2316 ** to any internal data structures of SQLite.  It uses only the public
2317 ** interface defined here.  As a consequence, errors that occur in the
2318 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2319 ** reflected in subsequent calls to [sqlite3_errcode()] or
2320 ** [sqlite3_errmsg()].)^
2321 */
2322 SQLITE_API int sqlite3_get_table(
2323   sqlite3 *db,          /* An open database */
2324   const char *zSql,     /* SQL to be evaluated */
2325   char ***pazResult,    /* Results of the query */
2326   int *pnRow,           /* Number of result rows written here */
2327   int *pnColumn,        /* Number of result columns written here */
2328   char **pzErrmsg       /* Error msg written here */
2329 );
2330 SQLITE_API void sqlite3_free_table(char **result);
2331
2332 /*
2333 ** CAPI3REF: Formatted String Printing Functions
2334 **
2335 ** These routines are work-alikes of the "printf()" family of functions
2336 ** from the standard C library.
2337 **
2338 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2339 ** results into memory obtained from [sqlite3_malloc()].
2340 ** The strings returned by these two routines should be
2341 ** released by [sqlite3_free()].  ^Both routines return a
2342 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2343 ** memory to hold the resulting string.
2344 **
2345 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2346 ** the standard C library.  The result is written into the
2347 ** buffer supplied as the second parameter whose size is given by
2348 ** the first parameter. Note that the order of the
2349 ** first two parameters is reversed from snprintf().)^  This is an
2350 ** historical accident that cannot be fixed without breaking
2351 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2352 ** returns a pointer to its buffer instead of the number of
2353 ** characters actually written into the buffer.)^  We admit that
2354 ** the number of characters written would be a more useful return
2355 ** value but we cannot change the implementation of sqlite3_snprintf()
2356 ** now without breaking compatibility.
2357 **
2358 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2359 ** guarantees that the buffer is always zero-terminated.  ^The first
2360 ** parameter "n" is the total size of the buffer, including space for
2361 ** the zero terminator.  So the longest string that can be completely
2362 ** written will be n-1 characters.
2363 **
2364 ** These routines all implement some additional formatting
2365 ** options that are useful for constructing SQL statements.
2366 ** All of the usual printf() formatting options apply.  In addition, there
2367 ** is are "%q", "%Q", and "%z" options.
2368 **
2369 ** ^(The %q option works like %s in that it substitutes a null-terminated
2370 ** string from the argument list.  But %q also doubles every '\'' character.
2371 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2372 ** character it escapes that character and allows it to be inserted into
2373 ** the string.
2374 **
2375 ** For example, assume the string variable zText contains text as follows:
2376 **
2377 ** <blockquote><pre>
2378 **  char *zText = "It's a happy day!";
2379 ** </pre></blockquote>
2380 **
2381 ** One can use this text in an SQL statement as follows:
2382 **
2383 ** <blockquote><pre>
2384 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2385 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2386 **  sqlite3_free(zSQL);
2387 ** </pre></blockquote>
2388 **
2389 ** Because the %q format string is used, the '\'' character in zText
2390 ** is escaped and the SQL generated is as follows:
2391 **
2392 ** <blockquote><pre>
2393 **  INSERT INTO table1 VALUES('It''s a happy day!')
2394 ** </pre></blockquote>
2395 **
2396 ** This is correct.  Had we used %s instead of %q, the generated SQL
2397 ** would have looked like this:
2398 **
2399 ** <blockquote><pre>
2400 **  INSERT INTO table1 VALUES('It's a happy day!');
2401 ** </pre></blockquote>
2402 **
2403 ** This second example is an SQL syntax error.  As a general rule you should
2404 ** always use %q instead of %s when inserting text into a string literal.
2405 **
2406 ** ^(The %Q option works like %q except it also adds single quotes around
2407 ** the outside of the total string.  Additionally, if the parameter in the
2408 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2409 ** single quotes).)^  So, for example, one could say:
2410 **
2411 ** <blockquote><pre>
2412 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2413 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2414 **  sqlite3_free(zSQL);
2415 ** </pre></blockquote>
2416 **
2417 ** The code above will render a correct SQL statement in the zSQL
2418 ** variable even if the zText variable is a NULL pointer.
2419 **
2420 ** ^(The "%z" formatting option works like "%s" but with the
2421 ** addition that after the string has been read and copied into
2422 ** the result, [sqlite3_free()] is called on the input string.)^
2423 */
2424 SQLITE_API char *sqlite3_mprintf(const char*,...);
2425 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2426 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2427
2428 /*
2429 ** CAPI3REF: Memory Allocation Subsystem
2430 **
2431 ** The SQLite core uses these three routines for all of its own
2432 ** internal memory allocation needs. "Core" in the previous sentence
2433 ** does not include operating-system specific VFS implementation.  The
2434 ** Windows VFS uses native malloc() and free() for some operations.
2435 **
2436 ** ^The sqlite3_malloc() routine returns a pointer to a block
2437 ** of memory at least N bytes in length, where N is the parameter.
2438 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2439 ** memory, it returns a NULL pointer.  ^If the parameter N to
2440 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2441 ** a NULL pointer.
2442 **
2443 ** ^Calling sqlite3_free() with a pointer previously returned
2444 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2445 ** that it might be reused.  ^The sqlite3_free() routine is
2446 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2447 ** to sqlite3_free() is harmless.  After being freed, memory
2448 ** should neither be read nor written.  Even reading previously freed
2449 ** memory might result in a segmentation fault or other severe error.
2450 ** Memory corruption, a segmentation fault, or other severe error
2451 ** might result if sqlite3_free() is called with a non-NULL pointer that
2452 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2453 **
2454 ** ^(The sqlite3_realloc() interface attempts to resize a
2455 ** prior memory allocation to be at least N bytes, where N is the
2456 ** second parameter.  The memory allocation to be resized is the first
2457 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2458 ** is a NULL pointer then its behavior is identical to calling
2459 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2460 ** ^If the second parameter to sqlite3_realloc() is zero or
2461 ** negative then the behavior is exactly the same as calling
2462 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2463 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2464 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2465 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2466 ** of the prior allocation are copied into the beginning of buffer returned
2467 ** by sqlite3_realloc() and the prior allocation is freed.
2468 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2469 ** is not freed.
2470 **
2471 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2472 ** is always aligned to at least an 8 byte boundary.
2473 **
2474 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2475 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2476 ** implementation of these routines to be omitted.  That capability
2477 ** is no longer provided.  Only built-in memory allocators can be used.
2478 **
2479 ** The Windows OS interface layer calls
2480 ** the system malloc() and free() directly when converting
2481 ** filenames between the UTF-8 encoding used by SQLite
2482 ** and whatever filename encoding is used by the particular Windows
2483 ** installation.  Memory allocation errors are detected, but
2484 ** they are reported back as [SQLITE_CANTOPEN] or
2485 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2486 **
2487 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2488 ** must be either NULL or else pointers obtained from a prior
2489 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2490 ** not yet been released.
2491 **
2492 ** The application must not read or write any part of
2493 ** a block of memory after it has been released using
2494 ** [sqlite3_free()] or [sqlite3_realloc()].
2495 */
2496 SQLITE_API void *sqlite3_malloc(int);
2497 SQLITE_API void *sqlite3_realloc(void*, int);
2498 SQLITE_API void sqlite3_free(void*);
2499
2500 /*
2501 ** CAPI3REF: Memory Allocator Statistics
2502 **
2503 ** SQLite provides these two interfaces for reporting on the status
2504 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2505 ** routines, which form the built-in memory allocation subsystem.
2506 **
2507 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2508 ** of memory currently outstanding (malloced but not freed).
2509 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2510 ** value of [sqlite3_memory_used()] since the high-water mark
2511 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2512 ** [sqlite3_memory_highwater()] include any overhead
2513 ** added by SQLite in its implementation of [sqlite3_malloc()],
2514 ** but not overhead added by the any underlying system library
2515 ** routines that [sqlite3_malloc()] may call.
2516 **
2517 ** ^The memory high-water mark is reset to the current value of
2518 ** [sqlite3_memory_used()] if and only if the parameter to
2519 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2520 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2521 ** prior to the reset.
2522 */
2523 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2524 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2525
2526 /*
2527 ** CAPI3REF: Pseudo-Random Number Generator
2528 **
2529 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2530 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2531 ** already uses the largest possible [ROWID].  The PRNG is also used for
2532 ** the build-in random() and randomblob() SQL functions.  This interface allows
2533 ** applications to access the same PRNG for other purposes.
2534 **
2535 ** ^A call to this routine stores N bytes of randomness into buffer P.
2536 **
2537 ** ^The first time this routine is invoked (either internally or by
2538 ** the application) the PRNG is seeded using randomness obtained
2539 ** from the xRandomness method of the default [sqlite3_vfs] object.
2540 ** ^On all subsequent invocations, the pseudo-randomness is generated
2541 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2542 ** method.
2543 */
2544 SQLITE_API void sqlite3_randomness(int N, void *P);
2545
2546 /*
2547 ** CAPI3REF: Compile-Time Authorization Callbacks
2548 **
2549 ** ^This routine registers a authorizer callback with a particular
2550 ** [database connection], supplied in the first argument.
2551 ** ^The authorizer callback is invoked as SQL statements are being compiled
2552 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2553 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2554 ** points during the compilation process, as logic is being created
2555 ** to perform various actions, the authorizer callback is invoked to
2556 ** see if those actions are allowed.  ^The authorizer callback should
2557 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2558 ** specific action but allow the SQL statement to continue to be
2559 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2560 ** rejected with an error.  ^If the authorizer callback returns
2561 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2562 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2563 ** the authorizer will fail with an error message.
2564 **
2565 ** When the callback returns [SQLITE_OK], that means the operation
2566 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2567 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2568 ** authorizer will fail with an error message explaining that
2569 ** access is denied. 
2570 **
2571 ** ^The first parameter to the authorizer callback is a copy of the third
2572 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2573 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2574 ** the particular action to be authorized. ^The third through sixth parameters
2575 ** to the callback are zero-terminated strings that contain additional
2576 ** details about the action to be authorized.
2577 **
2578 ** ^If the action code is [SQLITE_READ]
2579 ** and the callback returns [SQLITE_IGNORE] then the
2580 ** [prepared statement] statement is constructed to substitute
2581 ** a NULL value in place of the table column that would have
2582 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2583 ** return can be used to deny an untrusted user access to individual
2584 ** columns of a table.
2585 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2586 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2587 ** [truncate optimization] is disabled and all rows are deleted individually.
2588 **
2589 ** An authorizer is used when [sqlite3_prepare | preparing]
2590 ** SQL statements from an untrusted source, to ensure that the SQL statements
2591 ** do not try to access data they are not allowed to see, or that they do not
2592 ** try to execute malicious statements that damage the database.  For
2593 ** example, an application may allow a user to enter arbitrary
2594 ** SQL queries for evaluation by a database.  But the application does
2595 ** not want the user to be able to make arbitrary changes to the
2596 ** database.  An authorizer could then be put in place while the
2597 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2598 ** disallows everything except [SELECT] statements.
2599 **
2600 ** Applications that need to process SQL from untrusted sources
2601 ** might also consider lowering resource limits using [sqlite3_limit()]
2602 ** and limiting database size using the [max_page_count] [PRAGMA]
2603 ** in addition to using an authorizer.
2604 **
2605 ** ^(Only a single authorizer can be in place on a database connection
2606 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2607 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2608 ** The authorizer is disabled by default.
2609 **
2610 ** The authorizer callback must not do anything that will modify
2611 ** the database connection that invoked the authorizer callback.
2612 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2613 ** database connections for the meaning of "modify" in this paragraph.
2614 **
2615 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2616 ** statement might be re-prepared during [sqlite3_step()] due to a 
2617 ** schema change.  Hence, the application should ensure that the
2618 ** correct authorizer callback remains in place during the [sqlite3_step()].
2619 **
2620 ** ^Note that the authorizer callback is invoked only during
2621 ** [sqlite3_prepare()] or its variants.  Authorization is not
2622 ** performed during statement evaluation in [sqlite3_step()], unless
2623 ** as stated in the previous paragraph, sqlite3_step() invokes
2624 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2625 */
2626 SQLITE_API int sqlite3_set_authorizer(
2627   sqlite3*,
2628   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2629   void *pUserData
2630 );
2631
2632 /*
2633 ** CAPI3REF: Authorizer Return Codes
2634 **
2635 ** The [sqlite3_set_authorizer | authorizer callback function] must
2636 ** return either [SQLITE_OK] or one of these two constants in order
2637 ** to signal SQLite whether or not the action is permitted.  See the
2638 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2639 ** information.
2640 */
2641 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2642 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2643
2644 /*
2645 ** CAPI3REF: Authorizer Action Codes
2646 **
2647 ** The [sqlite3_set_authorizer()] interface registers a callback function
2648 ** that is invoked to authorize certain SQL statement actions.  The
2649 ** second parameter to the callback is an integer code that specifies
2650 ** what action is being authorized.  These are the integer action codes that
2651 ** the authorizer callback may be passed.
2652 **
2653 ** These action code values signify what kind of operation is to be
2654 ** authorized.  The 3rd and 4th parameters to the authorization
2655 ** callback function will be parameters or NULL depending on which of these
2656 ** codes is used as the second parameter.  ^(The 5th parameter to the
2657 ** authorizer callback is the name of the database ("main", "temp",
2658 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2659 ** is the name of the inner-most trigger or view that is responsible for
2660 ** the access attempt or NULL if this access attempt is directly from
2661 ** top-level SQL code.
2662 */
2663 /******************************************* 3rd ************ 4th ***********/
2664 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2665 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2666 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2667 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2668 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2669 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2670 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2671 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2672 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2673 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2674 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2675 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2676 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2677 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2678 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2679 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2680 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2681 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2682 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2683 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2684 #define SQLITE_SELECT               21   /* NULL            NULL            */
2685 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2686 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2687 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2688 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2689 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2690 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2691 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2692 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2693 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2694 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2695 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2696 #define SQLITE_COPY                  0   /* No longer used */
2697
2698 /*
2699 ** CAPI3REF: Tracing And Profiling Functions
2700 **
2701 ** These routines register callback functions that can be used for
2702 ** tracing and profiling the execution of SQL statements.
2703 **
2704 ** ^The callback function registered by sqlite3_trace() is invoked at
2705 ** various times when an SQL statement is being run by [sqlite3_step()].
2706 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2707 ** SQL statement text as the statement first begins executing.
2708 ** ^(Additional sqlite3_trace() callbacks might occur
2709 ** as each triggered subprogram is entered.  The callbacks for triggers
2710 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2711 **
2712 ** ^The callback function registered by sqlite3_profile() is invoked
2713 ** as each SQL statement finishes.  ^The profile callback contains
2714 ** the original statement text and an estimate of wall-clock time
2715 ** of how long that statement took to run.
2716 */
2717 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2718 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2719    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2720
2721 /*
2722 ** CAPI3REF: Query Progress Callbacks
2723 **
2724 ** ^This routine configures a callback function - the
2725 ** progress callback - that is invoked periodically during long
2726 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2727 ** [sqlite3_get_table()].  An example use for this
2728 ** interface is to keep a GUI updated during a large query.
2729 **
2730 ** ^If the progress callback returns non-zero, the operation is
2731 ** interrupted.  This feature can be used to implement a
2732 ** "Cancel" button on a GUI progress dialog box.
2733 **
2734 ** The progress handler must not do anything that will modify
2735 ** the database connection that invoked the progress handler.
2736 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2737 ** database connections for the meaning of "modify" in this paragraph.
2738 **
2739 */
2740 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2741
2742 /*
2743 ** CAPI3REF: Opening A New Database Connection
2744 **
2745 ** ^These routines open an SQLite database file whose name is given by the
2746 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2747 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2748 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2749 ** returned in *ppDb, even if an error occurs.  The only exception is that
2750 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2751 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2752 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2753 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2754 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2755 ** an English language description of the error following a failure of any
2756 ** of the sqlite3_open() routines.
2757 **
2758 ** ^The default encoding for the database will be UTF-8 if
2759 ** sqlite3_open() or sqlite3_open_v2() is called and
2760 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2761 **
2762 ** Whether or not an error occurs when it is opened, resources
2763 ** associated with the [database connection] handle should be released by
2764 ** passing it to [sqlite3_close()] when it is no longer required.
2765 **
2766 ** The sqlite3_open_v2() interface works like sqlite3_open()
2767 ** except that it accepts two additional parameters for additional control
2768 ** over the new database connection.  ^(The flags parameter to
2769 ** sqlite3_open_v2() can take one of
2770 ** the following three values, optionally combined with the 
2771 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2772 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2773 **
2774 ** <dl>
2775 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2776 ** <dd>The database is opened in read-only mode.  If the database does not
2777 ** already exist, an error is returned.</dd>)^
2778 **
2779 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2780 ** <dd>The database is opened for reading and writing if possible, or reading
2781 ** only if the file is write protected by the operating system.  In either
2782 ** case the database must already exist, otherwise an error is returned.</dd>)^
2783 **
2784 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2785 ** <dd>The database is opened for reading and writing, and is creates it if
2786 ** it does not already exist. This is the behavior that is always used for
2787 ** sqlite3_open() and sqlite3_open16().</dd>)^
2788 ** </dl>
2789 **
2790 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2791 ** combinations shown above or one of the combinations shown above combined
2792 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2793 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2794 ** then the behavior is undefined.
2795 **
2796 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2797 ** opens in the multi-thread [threading mode] as long as the single-thread
2798 ** mode has not been set at compile-time or start-time.  ^If the
2799 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2800 ** in the serialized [threading mode] unless single-thread was
2801 ** previously selected at compile-time or start-time.
2802 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2803 ** eligible to use [shared cache mode], regardless of whether or not shared
2804 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2805 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2806 ** participate in [shared cache mode] even if it is enabled.
2807 **
2808 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2809 ** is created for the connection.  ^This in-memory database will vanish when
2810 ** the database connection is closed.  Future versions of SQLite might
2811 ** make use of additional special filenames that begin with the ":" character.
2812 ** It is recommended that when a database filename actually does begin with
2813 ** a ":" character you should prefix the filename with a pathname such as
2814 ** "./" to avoid ambiguity.
2815 **
2816 ** ^If the filename is an empty string, then a private, temporary
2817 ** on-disk database will be created.  ^This private database will be
2818 ** automatically deleted as soon as the database connection is closed.
2819 **
2820 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2821 ** [sqlite3_vfs] object that defines the operating system interface that
2822 ** the new database connection should use.  ^If the fourth parameter is
2823 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2824 **
2825 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2826 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2827 ** codepage is currently defined.  Filenames containing international
2828 ** characters must be converted to UTF-8 prior to passing them into
2829 ** sqlite3_open() or sqlite3_open_v2().
2830 */
2831 SQLITE_API int sqlite3_open(
2832   const char *filename,   /* Database filename (UTF-8) */
2833   sqlite3 **ppDb          /* OUT: SQLite db handle */
2834 );
2835 SQLITE_API int sqlite3_open16(
2836   const void *filename,   /* Database filename (UTF-16) */
2837   sqlite3 **ppDb          /* OUT: SQLite db handle */
2838 );
2839 SQLITE_API int sqlite3_open_v2(
2840   const char *filename,   /* Database filename (UTF-8) */
2841   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2842   int flags,              /* Flags */
2843   const char *zVfs        /* Name of VFS module to use */
2844 );
2845
2846 /*
2847 ** CAPI3REF: Error Codes And Messages
2848 **
2849 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2850 ** [extended result code] for the most recent failed sqlite3_* API call
2851 ** associated with a [database connection]. If a prior API call failed
2852 ** but the most recent API call succeeded, the return value from
2853 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2854 ** interface is the same except that it always returns the 
2855 ** [extended result code] even when extended result codes are
2856 ** disabled.
2857 **
2858 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2859 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2860 ** ^(Memory to hold the error message string is managed internally.
2861 ** The application does not need to worry about freeing the result.
2862 ** However, the error string might be overwritten or deallocated by
2863 ** subsequent calls to other SQLite interface functions.)^
2864 **
2865 ** When the serialized [threading mode] is in use, it might be the
2866 ** case that a second error occurs on a separate thread in between
2867 ** the time of the first error and the call to these interfaces.
2868 ** When that happens, the second error will be reported since these
2869 ** interfaces always report the most recent result.  To avoid
2870 ** this, each thread can obtain exclusive use of the [database connection] D
2871 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2872 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2873 ** all calls to the interfaces listed here are completed.
2874 **
2875 ** If an interface fails with SQLITE_MISUSE, that means the interface
2876 ** was invoked incorrectly by the application.  In that case, the
2877 ** error code and message may or may not be set.
2878 */
2879 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2880 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2881 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2882 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2883
2884 /*
2885 ** CAPI3REF: SQL Statement Object
2886 ** KEYWORDS: {prepared statement} {prepared statements}
2887 **
2888 ** An instance of this object represents a single SQL statement.
2889 ** This object is variously known as a "prepared statement" or a
2890 ** "compiled SQL statement" or simply as a "statement".
2891 **
2892 ** The life of a statement object goes something like this:
2893 **
2894 ** <ol>
2895 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2896 **      function.
2897 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2898 **      interfaces.
2899 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2900 ** <li> Reset the statement using [sqlite3_reset()] then go back
2901 **      to step 2.  Do this zero or more times.
2902 ** <li> Destroy the object using [sqlite3_finalize()].
2903 ** </ol>
2904 **
2905 ** Refer to documentation on individual methods above for additional
2906 ** information.
2907 */
2908 typedef struct sqlite3_stmt sqlite3_stmt;
2909
2910 /*
2911 ** CAPI3REF: Run-time Limits
2912 **
2913 ** ^(This interface allows the size of various constructs to be limited
2914 ** on a connection by connection basis.  The first parameter is the
2915 ** [database connection] whose limit is to be set or queried.  The
2916 ** second parameter is one of the [limit categories] that define a
2917 ** class of constructs to be size limited.  The third parameter is the
2918 ** new limit for that construct.  The function returns the old limit.)^
2919 **
2920 ** ^If the new limit is a negative number, the limit is unchanged.
2921 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a 
2922 ** [limits | hard upper bound]
2923 ** set by a compile-time C preprocessor macro named 
2924 ** [limits | SQLITE_MAX_XYZ].
2925 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2926 ** ^Attempts to increase a limit above its hard upper bound are
2927 ** silently truncated to the hard upper bound.
2928 **
2929 ** Run-time limits are intended for use in applications that manage
2930 ** both their own internal database and also databases that are controlled
2931 ** by untrusted external sources.  An example application might be a
2932 ** web browser that has its own databases for storing history and
2933 ** separate databases controlled by JavaScript applications downloaded
2934 ** off the Internet.  The internal databases can be given the
2935 ** large, default limits.  Databases managed by external sources can
2936 ** be given much smaller limits designed to prevent a denial of service
2937 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2938 ** interface to further control untrusted SQL.  The size of the database
2939 ** created by an untrusted script can be contained using the
2940 ** [max_page_count] [PRAGMA].
2941 **
2942 ** New run-time limit categories may be added in future releases.
2943 */
2944 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2945
2946 /*
2947 ** CAPI3REF: Run-Time Limit Categories
2948 ** KEYWORDS: {limit category} {*limit categories}
2949 **
2950 ** These constants define various performance limits
2951 ** that can be lowered at run-time using [sqlite3_limit()].
2952 ** The synopsis of the meanings of the various limits is shown below.
2953 ** Additional information is available at [limits | Limits in SQLite].
2954 **
2955 ** <dl>
2956 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2957 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2958 **
2959 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2960 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2961 **
2962 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2963 ** <dd>The maximum number of columns in a table definition or in the
2964 ** result set of a [SELECT] or the maximum number of columns in an index
2965 ** or in an ORDER BY or GROUP BY clause.</dd>)^
2966 **
2967 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2968 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2969 **
2970 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2971 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2972 **
2973 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2974 ** <dd>The maximum number of instructions in a virtual machine program
2975 ** used to implement an SQL statement.</dd>)^
2976 **
2977 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2978 ** <dd>The maximum number of arguments on a function.</dd>)^
2979 **
2980 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2981 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2982 **
2983 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2984 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2985 ** [GLOB] operators.</dd>)^
2986 **
2987 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2988 ** <dd>The maximum number of variables in an SQL statement that can
2989 ** be bound.</dd>)^
2990 **
2991 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2992 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2993 ** </dl>
2994 */
2995 #define SQLITE_LIMIT_LENGTH                    0
2996 #define SQLITE_LIMIT_SQL_LENGTH                1
2997 #define SQLITE_LIMIT_COLUMN                    2
2998 #define SQLITE_LIMIT_EXPR_DEPTH                3
2999 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3000 #define SQLITE_LIMIT_VDBE_OP                   5
3001 #define SQLITE_LIMIT_FUNCTION_ARG              6
3002 #define SQLITE_LIMIT_ATTACHED                  7
3003 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3004 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3005 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3006
3007 /*
3008 ** CAPI3REF: Compiling An SQL Statement
3009 ** KEYWORDS: {SQL statement compiler}
3010 **
3011 ** To execute an SQL query, it must first be compiled into a byte-code
3012 ** program using one of these routines.
3013 **
3014 ** The first argument, "db", is a [database connection] obtained from a
3015 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3016 ** [sqlite3_open16()].  The database connection must not have been closed.
3017 **
3018 ** The second argument, "zSql", is the statement to be compiled, encoded
3019 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3020 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3021 ** use UTF-16.
3022 **
3023 ** ^If the nByte argument is less than zero, then zSql is read up to the
3024 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3025 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3026 ** zSql string ends at either the first '\000' or '\u0000' character or
3027 ** the nByte-th byte, whichever comes first. If the caller knows
3028 ** that the supplied string is nul-terminated, then there is a small
3029 ** performance advantage to be gained by passing an nByte parameter that
3030 ** is equal to the number of bytes in the input string <i>including</i>
3031 ** the nul-terminator bytes.
3032 **
3033 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3034 ** past the end of the first SQL statement in zSql.  These routines only
3035 ** compile the first statement in zSql, so *pzTail is left pointing to
3036 ** what remains uncompiled.
3037 **
3038 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3039 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3040 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3041 ** string or a comment) then *ppStmt is set to NULL.
3042 ** The calling procedure is responsible for deleting the compiled
3043 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3044 ** ppStmt may not be NULL.
3045 **
3046 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3047 ** otherwise an [error code] is returned.
3048 **
3049 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3050 ** recommended for all new programs. The two older interfaces are retained
3051 ** for backwards compatibility, but their use is discouraged.
3052 ** ^In the "v2" interfaces, the prepared statement
3053 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3054 ** original SQL text. This causes the [sqlite3_step()] interface to
3055 ** behave differently in three ways:
3056 **
3057 ** <ol>
3058 ** <li>
3059 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3060 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3061 ** statement and try to run it again.  ^If the schema has changed in
3062 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3063 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3064 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3065 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3066 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3067 ** </li>
3068 **
3069 ** <li>
3070 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3071 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3072 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3073 ** and the application would have to make a second call to [sqlite3_reset()]
3074 ** in order to find the underlying cause of the problem. With the "v2" prepare
3075 ** interfaces, the underlying reason for the error is returned immediately.
3076 ** </li>
3077 **
3078 ** <li>
3079 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
3080 ** change the query plan for a statement, then the statement may be
3081 ** automatically recompiled (as if there had been a schema change) on the first 
3082 ** [sqlite3_step()] call following any change to the 
3083 ** [sqlite3_bind_text | bindings] of the [parameter]. 
3084 ** </li>
3085 ** </ol>
3086 */
3087 SQLITE_API int sqlite3_prepare(
3088   sqlite3 *db,            /* Database handle */
3089   const char *zSql,       /* SQL statement, UTF-8 encoded */
3090   int nByte,              /* Maximum length of zSql in bytes. */
3091   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3092   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3093 );
3094 SQLITE_API int sqlite3_prepare_v2(
3095   sqlite3 *db,            /* Database handle */
3096   const char *zSql,       /* SQL statement, UTF-8 encoded */
3097   int nByte,              /* Maximum length of zSql in bytes. */
3098   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3099   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3100 );
3101 SQLITE_API int sqlite3_prepare16(
3102   sqlite3 *db,            /* Database handle */
3103   const void *zSql,       /* SQL statement, UTF-16 encoded */
3104   int nByte,              /* Maximum length of zSql in bytes. */
3105   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3106   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3107 );
3108 SQLITE_API int sqlite3_prepare16_v2(
3109   sqlite3 *db,            /* Database handle */
3110   const void *zSql,       /* SQL statement, UTF-16 encoded */
3111   int nByte,              /* Maximum length of zSql in bytes. */
3112   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3113   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3114 );
3115
3116 /*
3117 ** CAPI3REF: Retrieving Statement SQL
3118 **
3119 ** ^This interface can be used to retrieve a saved copy of the original
3120 ** SQL text used to create a [prepared statement] if that statement was
3121 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3122 */
3123 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3124
3125 /*
3126 ** CAPI3REF: Dynamically Typed Value Object
3127 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3128 **
3129 ** SQLite uses the sqlite3_value object to represent all values
3130 ** that can be stored in a database table. SQLite uses dynamic typing
3131 ** for the values it stores.  ^Values stored in sqlite3_value objects
3132 ** can be integers, floating point values, strings, BLOBs, or NULL.
3133 **
3134 ** An sqlite3_value object may be either "protected" or "unprotected".
3135 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3136 ** will accept either a protected or an unprotected sqlite3_value.
3137 ** Every interface that accepts sqlite3_value arguments specifies
3138 ** whether or not it requires a protected sqlite3_value.
3139 **
3140 ** The terms "protected" and "unprotected" refer to whether or not
3141 ** a mutex is held.  A internal mutex is held for a protected
3142 ** sqlite3_value object but no mutex is held for an unprotected
3143 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3144 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3145 ** or if SQLite is run in one of reduced mutex modes 
3146 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3147 ** then there is no distinction between protected and unprotected
3148 ** sqlite3_value objects and they can be used interchangeably.  However,
3149 ** for maximum code portability it is recommended that applications
3150 ** still make the distinction between between protected and unprotected
3151 ** sqlite3_value objects even when not strictly required.
3152 **
3153 ** ^The sqlite3_value objects that are passed as parameters into the
3154 ** implementation of [application-defined SQL functions] are protected.
3155 ** ^The sqlite3_value object returned by
3156 ** [sqlite3_column_value()] is unprotected.
3157 ** Unprotected sqlite3_value objects may only be used with
3158 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3159 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3160 ** interfaces require protected sqlite3_value objects.
3161 */
3162 typedef struct Mem sqlite3_value;
3163
3164 /*
3165 ** CAPI3REF: SQL Function Context Object
3166 **
3167 ** The context in which an SQL function executes is stored in an
3168 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3169 ** is always first parameter to [application-defined SQL functions].
3170 ** The application-defined SQL function implementation will pass this
3171 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3172 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3173 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3174 ** and/or [sqlite3_set_auxdata()].
3175 */
3176 typedef struct sqlite3_context sqlite3_context;
3177
3178 /*
3179 ** CAPI3REF: Binding Values To Prepared Statements
3180 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3181 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3182 **
3183 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3184 ** literals may be replaced by a [parameter] that matches one of following
3185 ** templates:
3186 **
3187 ** <ul>
3188 ** <li>  ?
3189 ** <li>  ?NNN
3190 ** <li>  :VVV
3191 ** <li>  @VVV
3192 ** <li>  $VVV
3193 ** </ul>
3194 **
3195 ** In the templates above, NNN represents an integer literal,
3196 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
3197 ** parameters (also called "host parameter names" or "SQL parameters")
3198 ** can be set using the sqlite3_bind_*() routines defined here.
3199 **
3200 ** ^The first argument to the sqlite3_bind_*() routines is always
3201 ** a pointer to the [sqlite3_stmt] object returned from
3202 ** [sqlite3_prepare_v2()] or its variants.
3203 **
3204 ** ^The second argument is the index of the SQL parameter to be set.
3205 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3206 ** SQL parameter is used more than once, second and subsequent
3207 ** occurrences have the same index as the first occurrence.
3208 ** ^The index for named parameters can be looked up using the
3209 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3210 ** for "?NNN" parameters is the value of NNN.
3211 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3212 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3213 **
3214 ** ^The third argument is the value to bind to the parameter.
3215 **
3216 ** ^(In those routines that have a fourth argument, its value is the
3217 ** number of bytes in the parameter.  To be clear: the value is the
3218 ** number of <u>bytes</u> in the value, not the number of characters.)^
3219 ** ^If the fourth parameter is negative, the length of the string is
3220 ** the number of bytes up to the first zero terminator.
3221 **
3222 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3223 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3224 ** string after SQLite has finished with it. ^If the fifth argument is
3225 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3226 ** information is in static, unmanaged space and does not need to be freed.
3227 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3228 ** SQLite makes its own private copy of the data immediately, before
3229 ** the sqlite3_bind_*() routine returns.
3230 **
3231 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3232 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3233 ** (just an integer to hold its size) while it is being processed.
3234 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3235 ** content is later written using
3236 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3237 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3238 **
3239 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3240 ** for the [prepared statement] or with a prepared statement for which
3241 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3242 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3243 ** routine is passed a [prepared statement] that has been finalized, the
3244 ** result is undefined and probably harmful.
3245 **
3246 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3247 ** ^Unbound parameters are interpreted as NULL.
3248 **
3249 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3250 ** [error code] if anything goes wrong.
3251 ** ^[SQLITE_RANGE] is returned if the parameter
3252 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3253 **
3254 ** See also: [sqlite3_bind_parameter_count()],
3255 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3256 */
3257 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3258 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3259 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3260 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3261 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3262 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3263 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3264 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3265 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3266
3267 /*
3268 ** CAPI3REF: Number Of SQL Parameters
3269 **
3270 ** ^This routine can be used to find the number of [SQL parameters]
3271 ** in a [prepared statement].  SQL parameters are tokens of the
3272 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3273 ** placeholders for values that are [sqlite3_bind_blob | bound]
3274 ** to the parameters at a later time.
3275 **
3276 ** ^(This routine actually returns the index of the largest (rightmost)
3277 ** parameter. For all forms except ?NNN, this will correspond to the
3278 ** number of unique parameters.  If parameters of the ?NNN form are used,
3279 ** there may be gaps in the list.)^
3280 **
3281 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3282 ** [sqlite3_bind_parameter_name()], and
3283 ** [sqlite3_bind_parameter_index()].
3284 */
3285 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3286
3287 /*
3288 ** CAPI3REF: Name Of A Host Parameter
3289 **
3290 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3291 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3292 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3293 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3294 ** respectively.
3295 ** In other words, the initial ":" or "$" or "@" or "?"
3296 ** is included as part of the name.)^
3297 ** ^Parameters of the form "?" without a following integer have no name
3298 ** and are referred to as "nameless" or "anonymous parameters".
3299 **
3300 ** ^The first host parameter has an index of 1, not 0.
3301 **
3302 ** ^If the value N is out of range or if the N-th parameter is
3303 ** nameless, then NULL is returned.  ^The returned string is
3304 ** always in UTF-8 encoding even if the named parameter was
3305 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3306 ** [sqlite3_prepare16_v2()].
3307 **
3308 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3309 ** [sqlite3_bind_parameter_count()], and
3310 ** [sqlite3_bind_parameter_index()].
3311 */
3312 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3313
3314 /*
3315 ** CAPI3REF: Index Of A Parameter With A Given Name
3316 **
3317 ** ^Return the index of an SQL parameter given its name.  ^The
3318 ** index value returned is suitable for use as the second
3319 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3320 ** is returned if no matching parameter is found.  ^The parameter
3321 ** name must be given in UTF-8 even if the original statement
3322 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3323 **
3324 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3325 ** [sqlite3_bind_parameter_count()], and
3326 ** [sqlite3_bind_parameter_index()].
3327 */
3328 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3329
3330 /*
3331 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3332 **
3333 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3334 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3335 ** ^Use this routine to reset all host parameters to NULL.
3336 */
3337 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3338
3339 /*
3340 ** CAPI3REF: Number Of Columns In A Result Set
3341 **
3342 ** ^Return the number of columns in the result set returned by the
3343 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3344 ** statement that does not return data (for example an [UPDATE]).
3345 */
3346 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3347
3348 /*
3349 ** CAPI3REF: Column Names In A Result Set
3350 **
3351 ** ^These routines return the name assigned to a particular column
3352 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3353 ** interface returns a pointer to a zero-terminated UTF-8 string
3354 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3355 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3356 ** that implements the [SELECT] statement. ^The second parameter is the
3357 ** column number.  ^The leftmost column is number 0.
3358 **
3359 ** ^The returned string pointer is valid until either the [prepared statement]
3360 ** is destroyed by [sqlite3_finalize()] or until the next call to
3361 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3362 **
3363 ** ^If sqlite3_malloc() fails during the processing of either routine
3364 ** (for example during a conversion from UTF-8 to UTF-16) then a
3365 ** NULL pointer is returned.
3366 **
3367 ** ^The name of a result column is the value of the "AS" clause for
3368 ** that column, if there is an AS clause.  If there is no AS clause
3369 ** then the name of the column is unspecified and may change from
3370 ** one release of SQLite to the next.
3371 */
3372 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3373 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3374
3375 /*
3376 ** CAPI3REF: Source Of Data In A Query Result
3377 **
3378 ** ^These routines provide a means to determine the database, table, and
3379 ** table column that is the origin of a particular result column in
3380 ** [SELECT] statement.
3381 ** ^The name of the database or table or column can be returned as
3382 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3383 ** the database name, the _table_ routines return the table name, and
3384 ** the origin_ routines return the column name.
3385 ** ^The returned string is valid until the [prepared statement] is destroyed
3386 ** using [sqlite3_finalize()] or until the same information is requested
3387 ** again in a different encoding.
3388 **
3389 ** ^The names returned are the original un-aliased names of the
3390 ** database, table, and column.
3391 **
3392 ** ^The first argument to these interfaces is a [prepared statement].
3393 ** ^These functions return information about the Nth result column returned by
3394 ** the statement, where N is the second function argument.
3395 ** ^The left-most column is column 0 for these routines.
3396 **
3397 ** ^If the Nth column returned by the statement is an expression or
3398 ** subquery and is not a column value, then all of these functions return
3399 ** NULL.  ^These routine might also return NULL if a memory allocation error
3400 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3401 ** or column that query result column was extracted from.
3402 **
3403 ** ^As with all other SQLite APIs, those whose names end with "16" return
3404 ** UTF-16 encoded strings and the other functions return UTF-8.
3405 **
3406 ** ^These APIs are only available if the library was compiled with the
3407 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3408 **
3409 ** If two or more threads call one or more of these routines against the same
3410 ** prepared statement and column at the same time then the results are
3411 ** undefined.
3412 **
3413 ** If two or more threads call one or more
3414 ** [sqlite3_column_database_name | column metadata interfaces]
3415 ** for the same [prepared statement] and result column
3416 ** at the same time then the results are undefined.
3417 */
3418 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3419 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3420 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3421 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3422 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3423 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3424
3425 /*
3426 ** CAPI3REF: Declared Datatype Of A Query Result
3427 **
3428 ** ^(The first parameter is a [prepared statement].
3429 ** If this statement is a [SELECT] statement and the Nth column of the
3430 ** returned result set of that [SELECT] is a table column (not an
3431 ** expression or subquery) then the declared type of the table
3432 ** column is returned.)^  ^If the Nth column of the result set is an
3433 ** expression or subquery, then a NULL pointer is returned.
3434 ** ^The returned string is always UTF-8 encoded.
3435 **
3436 ** ^(For example, given the database schema:
3437 **
3438 ** CREATE TABLE t1(c1 VARIANT);
3439 **
3440 ** and the following statement to be compiled:
3441 **
3442 ** SELECT c1 + 1, c1 FROM t1;
3443 **
3444 ** this routine would return the string "VARIANT" for the second result
3445 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3446 **
3447 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3448 ** is declared to contain a particular type does not mean that the
3449 ** data stored in that column is of the declared type.  SQLite is
3450 ** strongly typed, but the typing is dynamic not static.  ^Type
3451 ** is associated with individual values, not with the containers
3452 ** used to hold those values.
3453 */
3454 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3455 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3456
3457 /*
3458 ** CAPI3REF: Evaluate An SQL Statement
3459 **
3460 ** After a [prepared statement] has been prepared using either
3461 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3462 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3463 ** must be called one or more times to evaluate the statement.
3464 **
3465 ** The details of the behavior of the sqlite3_step() interface depend
3466 ** on whether the statement was prepared using the newer "v2" interface
3467 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3468 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3469 ** new "v2" interface is recommended for new applications but the legacy
3470 ** interface will continue to be supported.
3471 **
3472 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3473 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3474 ** ^With the "v2" interface, any of the other [result codes] or
3475 ** [extended result codes] might be returned as well.
3476 **
3477 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3478 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3479 ** or occurs outside of an explicit transaction, then you can retry the
3480 ** statement.  If the statement is not a [COMMIT] and occurs within a
3481 ** explicit transaction then you should rollback the transaction before
3482 ** continuing.
3483 **
3484 ** ^[SQLITE_DONE] means that the statement has finished executing
3485 ** successfully.  sqlite3_step() should not be called again on this virtual
3486 ** machine without first calling [sqlite3_reset()] to reset the virtual
3487 ** machine back to its initial state.
3488 **
3489 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3490 ** is returned each time a new row of data is ready for processing by the
3491 ** caller. The values may be accessed using the [column access functions].
3492 ** sqlite3_step() is called again to retrieve the next row of data.
3493 **
3494 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3495 ** violation) has occurred.  sqlite3_step() should not be called again on
3496 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3497 ** ^With the legacy interface, a more specific error code (for example,
3498 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3499 ** can be obtained by calling [sqlite3_reset()] on the
3500 ** [prepared statement].  ^In the "v2" interface,
3501 ** the more specific error code is returned directly by sqlite3_step().
3502 **
3503 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3504 ** Perhaps it was called on a [prepared statement] that has
3505 ** already been [sqlite3_finalize | finalized] or on one that had
3506 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3507 ** be the case that the same database connection is being used by two or
3508 ** more threads at the same moment in time.
3509 **
3510 ** For all versions of SQLite up to and including 3.6.23.1, it was required
3511 ** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3512 ** [sqlite3_reset()] be called before any subsequent invocation of
3513 ** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3514 ** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3515 ** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
3516 ** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
3517 **
3518 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3519 ** API always returns a generic error code, [SQLITE_ERROR], following any
3520 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3521 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3522 ** specific [error codes] that better describes the error.
3523 ** We admit that this is a goofy design.  The problem has been fixed
3524 ** with the "v2" interface.  If you prepare all of your SQL statements
3525 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3526 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3527 ** then the more specific [error codes] are returned directly
3528 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3529 */
3530 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3531
3532 /*
3533 ** CAPI3REF: Number of columns in a result set
3534 **
3535 ** ^The sqlite3_data_count(P) the number of columns in the
3536 ** of the result set of [prepared statement] P.
3537 */
3538 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3539
3540 /*
3541 ** CAPI3REF: Fundamental Datatypes
3542 ** KEYWORDS: SQLITE_TEXT
3543 **
3544 ** ^(Every value in SQLite has one of five fundamental datatypes:
3545 **
3546 ** <ul>
3547 ** <li> 64-bit signed integer
3548 ** <li> 64-bit IEEE floating point number
3549 ** <li> string
3550 ** <li> BLOB
3551 ** <li> NULL
3552 ** </ul>)^
3553 **
3554 ** These constants are codes for each of those types.
3555 **
3556 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3557 ** for a completely different meaning.  Software that links against both
3558 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3559 ** SQLITE_TEXT.
3560 */
3561 #define SQLITE_INTEGER  1
3562 #define SQLITE_FLOAT    2
3563 #define SQLITE_BLOB     4
3564 #define SQLITE_NULL     5
3565 #ifdef SQLITE_TEXT
3566 # undef SQLITE_TEXT
3567 #else
3568 # define SQLITE_TEXT     3
3569 #endif
3570 #define SQLITE3_TEXT     3
3571
3572 /*
3573 ** CAPI3REF: Result Values From A Query
3574 ** KEYWORDS: {column access functions}
3575 **
3576 ** These routines form the "result set" interface.
3577 **
3578 ** ^These routines return information about a single column of the current
3579 ** result row of a query.  ^In every case the first argument is a pointer
3580 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3581 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3582 ** and the second argument is the index of the column for which information
3583 ** should be returned. ^The leftmost column of the result set has the index 0.
3584 ** ^The number of columns in the result can be determined using
3585 ** [sqlite3_column_count()].
3586 **
3587 ** If the SQL statement does not currently point to a valid row, or if the
3588 ** column index is out of range, the result is undefined.
3589 ** These routines may only be called when the most recent call to
3590 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3591 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3592 ** If any of these routines are called after [sqlite3_reset()] or
3593 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3594 ** something other than [SQLITE_ROW], the results are undefined.
3595 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3596 ** are called from a different thread while any of these routines
3597 ** are pending, then the results are undefined.
3598 **
3599 ** ^The sqlite3_column_type() routine returns the
3600 ** [SQLITE_INTEGER | datatype code] for the initial data type
3601 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3602 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3603 ** returned by sqlite3_column_type() is only meaningful if no type
3604 ** conversions have occurred as described below.  After a type conversion,
3605 ** the value returned by sqlite3_column_type() is undefined.  Future
3606 ** versions of SQLite may change the behavior of sqlite3_column_type()
3607 ** following a type conversion.
3608 **
3609 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3610 ** routine returns the number of bytes in that BLOB or string.
3611 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3612 ** the string to UTF-8 and then returns the number of bytes.
3613 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3614 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3615 ** the number of bytes in that string.
3616 ** ^The value returned does not include the zero terminator at the end
3617 ** of the string.  ^For clarity: the value returned is the number of
3618 ** bytes in the string, not the number of characters.
3619 **
3620 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3621 ** even empty strings, are always zero terminated.  ^The return
3622 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3623 ** pointer, possibly even a NULL pointer.
3624 **
3625 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3626 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3627 ** ^The zero terminator is not included in this count.
3628 **
3629 ** ^The object returned by [sqlite3_column_value()] is an
3630 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3631 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3632 ** If the [unprotected sqlite3_value] object returned by
3633 ** [sqlite3_column_value()] is used in any other way, including calls
3634 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3635 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3636 **
3637 ** These routines attempt to convert the value where appropriate.  ^For
3638 ** example, if the internal representation is FLOAT and a text result
3639 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3640 ** conversion automatically.  ^(The following table details the conversions
3641 ** that are applied:
3642 **
3643 ** <blockquote>
3644 ** <table border="1">
3645 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3646 **
3647 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3648 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3649 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3650 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3651 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3652 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3653 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3654 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3655 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3656 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3657 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3658 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3659 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3660 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3661 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3662 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3663 ** </table>
3664 ** </blockquote>)^
3665 **
3666 ** The table above makes reference to standard C library functions atoi()
3667 ** and atof().  SQLite does not really use these functions.  It has its
3668 ** own equivalent internal routines.  The atoi() and atof() names are
3669 ** used in the table for brevity and because they are familiar to most
3670 ** C programmers.
3671 **
3672 ** ^Note that when type conversions occur, pointers returned by prior
3673 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3674 ** sqlite3_column_text16() may be invalidated.
3675 ** ^(Type conversions and pointer invalidations might occur
3676 ** in the following cases:
3677 **
3678 ** <ul>
3679 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3680 **      sqlite3_column_text16() is called.  A zero-terminator might
3681 **      need to be added to the string.</li>
3682 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3683 **      sqlite3_column_text16() is called.  The content must be converted
3684 **      to UTF-16.</li>
3685 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3686 **      sqlite3_column_text() is called.  The content must be converted
3687 **      to UTF-8.</li>
3688 ** </ul>)^
3689 **
3690 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3691 ** not invalidate a prior pointer, though of course the content of the buffer
3692 ** that the prior pointer points to will have been modified.  Other kinds
3693 ** of conversion are done in place when it is possible, but sometimes they
3694 ** are not possible and in those cases prior pointers are invalidated.
3695 **
3696 ** ^(The safest and easiest to remember policy is to invoke these routines
3697 ** in one of the following ways:
3698 **
3699 ** <ul>
3700 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3701 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3702 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3703 ** </ul>)^
3704 **
3705 ** In other words, you should call sqlite3_column_text(),
3706 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3707 ** into the desired format, then invoke sqlite3_column_bytes() or
3708 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3709 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3710 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3711 ** with calls to sqlite3_column_bytes().
3712 **
3713 ** ^The pointers returned are valid until a type conversion occurs as
3714 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3715 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3716 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3717 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3718 ** [sqlite3_free()].
3719 **
3720 ** ^(If a memory allocation error occurs during the evaluation of any
3721 ** of these routines, a default value is returned.  The default value
3722 ** is either the integer 0, the floating point number 0.0, or a NULL
3723 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3724 ** [SQLITE_NOMEM].)^
3725 */
3726 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3727 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3728 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3729 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3730 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3731 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3732 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3733 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3734 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3735 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3736
3737 /*
3738 ** CAPI3REF: Destroy A Prepared Statement Object
3739 **
3740 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3741 ** ^If the statement was executed successfully or not executed at all, then
3742 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3743 ** [error code] or [extended error code] is returned.
3744 **
3745 ** ^This routine can be called at any point during the execution of the
3746 ** [prepared statement].  ^If the virtual machine has not
3747 ** completed execution when this routine is called, that is like
3748 ** encountering an error or an [sqlite3_interrupt | interrupt].
3749 ** ^Incomplete updates may be rolled back and transactions canceled,
3750 ** depending on the circumstances, and the
3751 ** [error code] returned will be [SQLITE_ABORT].
3752 */
3753 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3754
3755 /*
3756 ** CAPI3REF: Reset A Prepared Statement Object
3757 **
3758 ** The sqlite3_reset() function is called to reset a [prepared statement]
3759 ** object back to its initial state, ready to be re-executed.
3760 ** ^Any SQL statement variables that had values bound to them using
3761 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3762 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3763 **
3764 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3765 ** back to the beginning of its program.
3766 **
3767 ** ^If the most recent call to [sqlite3_step(S)] for the
3768 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3769 ** or if [sqlite3_step(S)] has never before been called on S,
3770 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3771 **
3772 ** ^If the most recent call to [sqlite3_step(S)] for the
3773 ** [prepared statement] S indicated an error, then
3774 ** [sqlite3_reset(S)] returns an appropriate [error code].
3775 **
3776 ** ^The [sqlite3_reset(S)] interface does not change the values
3777 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3778 */
3779 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3780
3781 /*
3782 ** CAPI3REF: Create Or Redefine SQL Functions
3783 ** KEYWORDS: {function creation routines}
3784 ** KEYWORDS: {application-defined SQL function}
3785 ** KEYWORDS: {application-defined SQL functions}
3786 **
3787 ** ^These two functions (collectively known as "function creation routines")
3788 ** are used to add SQL functions or aggregates or to redefine the behavior
3789 ** of existing SQL functions or aggregates.  The only difference between the
3790 ** two is that the second parameter, the name of the (scalar) function or
3791 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3792 ** for sqlite3_create_function16().
3793 **
3794 ** ^The first parameter is the [database connection] to which the SQL
3795 ** function is to be added.  ^If an application uses more than one database
3796 ** connection then application-defined SQL functions must be added
3797 ** to each database connection separately.
3798 **
3799 ** The second parameter is the name of the SQL function to be created or
3800 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3801 ** the zero-terminator.  Note that the name length limit is in bytes, not
3802 ** characters.  ^Any attempt to create a function with a longer name
3803 ** will result in [SQLITE_ERROR] being returned.
3804 **
3805 ** ^The third parameter (nArg)
3806 ** is the number of arguments that the SQL function or
3807 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3808 ** aggregate may take any number of arguments between 0 and the limit
3809 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3810 ** parameter is less than -1 or greater than 127 then the behavior is
3811 ** undefined.
3812 **
3813 ** The fourth parameter, eTextRep, specifies what
3814 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3815 ** its parameters.  Any SQL function implementation should be able to work
3816 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3817 ** more efficient with one encoding than another.  ^An application may
3818 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3819 ** times with the same function but with different values of eTextRep.
3820 ** ^When multiple implementations of the same function are available, SQLite
3821 ** will pick the one that involves the least amount of data conversion.
3822 ** If there is only a single implementation which does not care what text
3823 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3824 **
3825 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3826 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3827 **
3828 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3829 ** pointers to C-language functions that implement the SQL function or
3830 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3831 ** callback only; NULL pointers should be passed as the xStep and xFinal
3832 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3833 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3834 ** SQL function or aggregate, pass NULL for all three function callbacks.
3835 **
3836 ** ^It is permitted to register multiple implementations of the same
3837 ** functions with the same name but with either differing numbers of
3838 ** arguments or differing preferred text encodings.  ^SQLite will use
3839 ** the implementation that most closely matches the way in which the
3840 ** SQL function is used.  ^A function implementation with a non-negative
3841 ** nArg parameter is a better match than a function implementation with
3842 ** a negative nArg.  ^A function where the preferred text encoding
3843 ** matches the database encoding is a better
3844 ** match than a function where the encoding is different.  
3845 ** ^A function where the encoding difference is between UTF16le and UTF16be
3846 ** is a closer match than a function where the encoding difference is
3847 ** between UTF8 and UTF16.
3848 **
3849 ** ^Built-in functions may be overloaded by new application-defined functions.
3850 ** ^The first application-defined function with a given name overrides all
3851 ** built-in functions in the same [database connection] with the same name.
3852 ** ^Subsequent application-defined functions of the same name only override 
3853 ** prior application-defined functions that are an exact match for the
3854 ** number of parameters and preferred encoding.
3855 **
3856 ** ^An application-defined function is permitted to call other
3857 ** SQLite interfaces.  However, such calls must not
3858 ** close the database connection nor finalize or reset the prepared
3859 ** statement in which the function is running.
3860 */
3861 SQLITE_API int sqlite3_create_function(
3862   sqlite3 *db,
3863   const char *zFunctionName,
3864   int nArg,
3865   int eTextRep,
3866   void *pApp,
3867   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3868   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3869   void (*xFinal)(sqlite3_context*)
3870 );
3871 SQLITE_API int sqlite3_create_function16(
3872   sqlite3 *db,
3873   const void *zFunctionName,
3874   int nArg,
3875   int eTextRep,
3876   void *pApp,
3877   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3878   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3879   void (*xFinal)(sqlite3_context*)
3880 );
3881
3882 /*
3883 ** CAPI3REF: Text Encodings
3884 **
3885 ** These constant define integer codes that represent the various
3886 ** text encodings supported by SQLite.
3887 */
3888 #define SQLITE_UTF8           1
3889 #define SQLITE_UTF16LE        2
3890 #define SQLITE_UTF16BE        3
3891 #define SQLITE_UTF16          4    /* Use native byte order */
3892 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3893 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3894
3895 /*
3896 ** CAPI3REF: Deprecated Functions
3897 ** DEPRECATED
3898 **
3899 ** These functions are [deprecated].  In order to maintain
3900 ** backwards compatibility with older code, these functions continue 
3901 ** to be supported.  However, new applications should avoid
3902 ** the use of these functions.  To help encourage people to avoid
3903 ** using these functions, we are not going to tell you what they do.
3904 */
3905 #ifndef SQLITE_OMIT_DEPRECATED
3906 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3907 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3908 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3909 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3910 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3911 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3912 #endif
3913
3914 /*
3915 ** CAPI3REF: Obtaining SQL Function Parameter Values
3916 **
3917 ** The C-language implementation of SQL functions and aggregates uses
3918 ** this set of interface routines to access the parameter values on
3919 ** the function or aggregate.
3920 **
3921 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3922 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3923 ** define callbacks that implement the SQL functions and aggregates.
3924 ** The 4th parameter to these callbacks is an array of pointers to
3925 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3926 ** each parameter to the SQL function.  These routines are used to
3927 ** extract values from the [sqlite3_value] objects.
3928 **
3929 ** These routines work only with [protected sqlite3_value] objects.
3930 ** Any attempt to use these routines on an [unprotected sqlite3_value]
3931 ** object results in undefined behavior.
3932 **
3933 ** ^These routines work just like the corresponding [column access functions]
3934 ** except that  these routines take a single [protected sqlite3_value] object
3935 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3936 **
3937 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3938 ** in the native byte-order of the host machine.  ^The
3939 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3940 ** extract UTF-16 strings as big-endian and little-endian respectively.
3941 **
3942 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
3943 ** numeric affinity to the value.  This means that an attempt is
3944 ** made to convert the value to an integer or floating point.  If
3945 ** such a conversion is possible without loss of information (in other
3946 ** words, if the value is a string that looks like a number)
3947 ** then the conversion is performed.  Otherwise no conversion occurs.
3948 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3949 **
3950 ** Please pay particular attention to the fact that the pointer returned
3951 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3952 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3953 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3954 ** or [sqlite3_value_text16()].
3955 **
3956 ** These routines must be called from the same thread as
3957 ** the SQL function that supplied the [sqlite3_value*] parameters.
3958 */
3959 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3960 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3961 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3962 SQLITE_API double sqlite3_value_double(sqlite3_value*);
3963 SQLITE_API int sqlite3_value_int(sqlite3_value*);
3964 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3965 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3966 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3967 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3968 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3969 SQLITE_API int sqlite3_value_type(sqlite3_value*);
3970 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3971
3972 /*
3973 ** CAPI3REF: Obtain Aggregate Function Context
3974 **
3975 ** Implementions of aggregate SQL functions use this
3976 ** routine to allocate memory for storing their state.
3977 **
3978 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3979 ** for a particular aggregate function, SQLite
3980 ** allocates N of memory, zeroes out that memory, and returns a pointer
3981 ** to the new memory. ^On second and subsequent calls to
3982 ** sqlite3_aggregate_context() for the same aggregate function instance,
3983 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3984 ** called once for each invocation of the xStep callback and then one
3985 ** last time when the xFinal callback is invoked.  ^(When no rows match
3986 ** an aggregate query, the xStep() callback of the aggregate function
3987 ** implementation is never called and xFinal() is called exactly once.
3988 ** In those cases, sqlite3_aggregate_context() might be called for the
3989 ** first time from within xFinal().)^
3990 **
3991 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3992 ** less than or equal to zero or if a memory allocate error occurs.
3993 **
3994 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3995 ** determined by the N parameter on first successful call.  Changing the
3996 ** value of N in subsequent call to sqlite3_aggregate_context() within
3997 ** the same aggregate function instance will not resize the memory
3998 ** allocation.)^
3999 **
4000 ** ^SQLite automatically frees the memory allocated by 
4001 ** sqlite3_aggregate_context() when the aggregate query concludes.
4002 **
4003 ** The first parameter must be a copy of the
4004 ** [sqlite3_context | SQL function context] that is the first parameter
4005 ** to the xStep or xFinal callback routine that implements the aggregate
4006 ** function.
4007 **
4008 ** This routine must be called from the same thread in which
4009 ** the aggregate SQL function is running.
4010 */
4011 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4012
4013 /*
4014 ** CAPI3REF: User Data For Functions
4015 **
4016 ** ^The sqlite3_user_data() interface returns a copy of
4017 ** the pointer that was the pUserData parameter (the 5th parameter)
4018 ** of the [sqlite3_create_function()]
4019 ** and [sqlite3_create_function16()] routines that originally
4020 ** registered the application defined function.
4021 **
4022 ** This routine must be called from the same thread in which
4023 ** the application-defined function is running.
4024 */
4025 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4026
4027 /*
4028 ** CAPI3REF: Database Connection For Functions
4029 **
4030 ** ^The sqlite3_context_db_handle() interface returns a copy of
4031 ** the pointer to the [database connection] (the 1st parameter)
4032 ** of the [sqlite3_create_function()]
4033 ** and [sqlite3_create_function16()] routines that originally
4034 ** registered the application defined function.
4035 */
4036 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4037
4038 /*
4039 ** CAPI3REF: Function Auxiliary Data
4040 **
4041 ** The following two functions may be used by scalar SQL functions to
4042 ** associate metadata with argument values. If the same value is passed to
4043 ** multiple invocations of the same SQL function during query execution, under
4044 ** some circumstances the associated metadata may be preserved. This may
4045 ** be used, for example, to add a regular-expression matching scalar
4046 ** function. The compiled version of the regular expression is stored as
4047 ** metadata associated with the SQL value passed as the regular expression
4048 ** pattern.  The compiled regular expression can be reused on multiple
4049 ** invocations of the same function so that the original pattern string
4050 ** does not need to be recompiled on each invocation.
4051 **
4052 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4053 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4054 ** value to the application-defined function. ^If no metadata has been ever
4055 ** been set for the Nth argument of the function, or if the corresponding
4056 ** function parameter has changed since the meta-data was set,
4057 ** then sqlite3_get_auxdata() returns a NULL pointer.
4058 **
4059 ** ^The sqlite3_set_auxdata() interface saves the metadata
4060 ** pointed to by its 3rd parameter as the metadata for the N-th
4061 ** argument of the application-defined function.  Subsequent
4062 ** calls to sqlite3_get_auxdata() might return this data, if it has
4063 ** not been destroyed.
4064 ** ^If it is not NULL, SQLite will invoke the destructor
4065 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4066 ** the metadata when the corresponding function parameter changes
4067 ** or when the SQL statement completes, whichever comes first.
4068 **
4069 ** SQLite is free to call the destructor and drop metadata on any
4070 ** parameter of any function at any time.  ^The only guarantee is that
4071 ** the destructor will be called before the metadata is dropped.
4072 **
4073 ** ^(In practice, metadata is preserved between function calls for
4074 ** expressions that are constant at compile time. This includes literal
4075 ** values and [parameters].)^
4076 **
4077 ** These routines must be called from the same thread in which
4078 ** the SQL function is running.
4079 */
4080 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4081 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4082
4083
4084 /*
4085 ** CAPI3REF: Constants Defining Special Destructor Behavior
4086 **
4087 ** These are special values for the destructor that is passed in as the
4088 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4089 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4090 ** and will never change.  It does not need to be destroyed.  ^The
4091 ** SQLITE_TRANSIENT value means that the content will likely change in
4092 ** the near future and that SQLite should make its own private copy of
4093 ** the content before returning.
4094 **
4095 ** The typedef is necessary to work around problems in certain
4096 ** C++ compilers.  See ticket #2191.
4097 */
4098 typedef void (*sqlite3_destructor_type)(void*);
4099 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4100 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4101
4102 /*
4103 ** CAPI3REF: Setting The Result Of An SQL Function
4104 **
4105 ** These routines are used by the xFunc or xFinal callbacks that
4106 ** implement SQL functions and aggregates.  See
4107 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4108 ** for additional information.
4109 **
4110 ** These functions work very much like the [parameter binding] family of
4111 ** functions used to bind values to host parameters in prepared statements.
4112 ** Refer to the [SQL parameter] documentation for additional information.
4113 **
4114 ** ^The sqlite3_result_blob() interface sets the result from
4115 ** an application-defined function to be the BLOB whose content is pointed
4116 ** to by the second parameter and which is N bytes long where N is the
4117 ** third parameter.
4118 **
4119 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4120 ** the application-defined function to be a BLOB containing all zero
4121 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4122 **
4123 ** ^The sqlite3_result_double() interface sets the result from
4124 ** an application-defined function to be a floating point value specified
4125 ** by its 2nd argument.
4126 **
4127 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4128 ** cause the implemented SQL function to throw an exception.
4129 ** ^SQLite uses the string pointed to by the
4130 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4131 ** as the text of an error message.  ^SQLite interprets the error
4132 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4133 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4134 ** byte order.  ^If the third parameter to sqlite3_result_error()
4135 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4136 ** message all text up through the first zero character.
4137 ** ^If the third parameter to sqlite3_result_error() or
4138 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4139 ** bytes (not characters) from the 2nd parameter as the error message.
4140 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4141 ** routines make a private copy of the error message text before
4142 ** they return.  Hence, the calling function can deallocate or
4143 ** modify the text after they return without harm.
4144 ** ^The sqlite3_result_error_code() function changes the error code
4145 ** returned by SQLite as a result of an error in a function.  ^By default,
4146 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4147 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4148 **
4149 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4150 ** indicating that a string or BLOB is too long to represent.
4151 **
4152 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4153 ** indicating that a memory allocation failed.
4154 **
4155 ** ^The sqlite3_result_int() interface sets the return value
4156 ** of the application-defined function to be the 32-bit signed integer
4157 ** value given in the 2nd argument.
4158 ** ^The sqlite3_result_int64() interface sets the return value
4159 ** of the application-defined function to be the 64-bit signed integer
4160 ** value given in the 2nd argument.
4161 **
4162 ** ^The sqlite3_result_null() interface sets the return value
4163 ** of the application-defined function to be NULL.
4164 **
4165 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4166 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4167 ** set the return value of the application-defined function to be
4168 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4169 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4170 ** ^SQLite takes the text result from the application from
4171 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4172 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4173 ** is negative, then SQLite takes result text from the 2nd parameter
4174 ** through the first zero character.
4175 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4176 ** is non-negative, then as many bytes (not characters) of the text
4177 ** pointed to by the 2nd parameter are taken as the application-defined
4178 ** function result.
4179 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4180 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4181 ** function as the destructor on the text or BLOB result when it has
4182 ** finished using that result.
4183 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4184 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4185 ** assumes that the text or BLOB result is in constant space and does not
4186 ** copy the content of the parameter nor call a destructor on the content
4187 ** when it has finished using that result.
4188 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4189 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4190 ** then SQLite makes a copy of the result into space obtained from
4191 ** from [sqlite3_malloc()] before it returns.
4192 **
4193 ** ^The sqlite3_result_value() interface sets the result of
4194 ** the application-defined function to be a copy the
4195 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4196 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4197 ** so that the [sqlite3_value] specified in the parameter may change or
4198 ** be deallocated after sqlite3_result_value() returns without harm.
4199 ** ^A [protected sqlite3_value] object may always be used where an
4200 ** [unprotected sqlite3_value] object is required, so either
4201 ** kind of [sqlite3_value] object can be used with this interface.
4202 **
4203 ** If these routines are called from within the different thread
4204 ** than the one containing the application-defined function that received
4205 ** the [sqlite3_context] pointer, the results are undefined.
4206 */
4207 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4208 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4209 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4210 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4211 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4212 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4213 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4214 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4215 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4216 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4217 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4218 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4219 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4220 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4221 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4222 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4223
4224 /*
4225 ** CAPI3REF: Define New Collating Sequences
4226 **
4227 ** These functions are used to add new collation sequences to the
4228 ** [database connection] specified as the first argument.
4229 **
4230 ** ^The name of the new collation sequence is specified as a UTF-8 string
4231 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4232 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4233 ** the name is passed as the second function argument.
4234 **
4235 ** ^The third argument may be one of the constants [SQLITE_UTF8],
4236 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4237 ** routine expects to be passed pointers to strings encoded using UTF-8,
4238 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4239 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4240 ** expects pointers to be UTF-16 strings in the native byte order, or the
4241 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4242 ** the routine expects pointers to 16-bit word aligned strings
4243 ** of UTF-16 in the native byte order.
4244 **
4245 ** A pointer to the user supplied routine must be passed as the fifth
4246 ** argument.  ^If it is NULL, this is the same as deleting the collation
4247 ** sequence (so that SQLite cannot call it anymore).
4248 ** ^Each time the application supplied function is invoked, it is passed
4249 ** as its first parameter a copy of the void* passed as the fourth argument
4250 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4251 **
4252 ** ^The remaining arguments to the application-supplied routine are two strings,
4253 ** each represented by a (length, data) pair and encoded in the encoding
4254 ** that was passed as the third argument when the collation sequence was
4255 ** registered.  The application defined collation routine should
4256 ** return negative, zero or positive if the first string is less than,
4257 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4258 **
4259 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4260 ** except that it takes an extra argument which is a destructor for
4261 ** the collation.  ^The destructor is called when the collation is
4262 ** destroyed and is passed a copy of the fourth parameter void* pointer
4263 ** of the sqlite3_create_collation_v2().
4264 ** ^Collations are destroyed when they are overridden by later calls to the
4265 ** collation creation functions or when the [database connection] is closed
4266 ** using [sqlite3_close()].
4267 **
4268 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4269 */
4270 SQLITE_API int sqlite3_create_collation(
4271   sqlite3*, 
4272   const char *zName, 
4273   int eTextRep, 
4274   void*,
4275   int(*xCompare)(void*,int,const void*,int,const void*)
4276 );
4277 SQLITE_API int sqlite3_create_collation_v2(
4278   sqlite3*, 
4279   const char *zName, 
4280   int eTextRep, 
4281   void*,
4282   int(*xCompare)(void*,int,const void*,int,const void*),
4283   void(*xDestroy)(void*)
4284 );
4285 SQLITE_API int sqlite3_create_collation16(
4286   sqlite3*, 
4287   const void *zName,
4288   int eTextRep, 
4289   void*,
4290   int(*xCompare)(void*,int,const void*,int,const void*)
4291 );
4292
4293 /*
4294 ** CAPI3REF: Collation Needed Callbacks
4295 **
4296 ** ^To avoid having to register all collation sequences before a database
4297 ** can be used, a single callback function may be registered with the
4298 ** [database connection] to be invoked whenever an undefined collation
4299 ** sequence is required.
4300 **
4301 ** ^If the function is registered using the sqlite3_collation_needed() API,
4302 ** then it is passed the names of undefined collation sequences as strings
4303 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4304 ** the names are passed as UTF-16 in machine native byte order.
4305 ** ^A call to either function replaces the existing collation-needed callback.
4306 **
4307 ** ^(When the callback is invoked, the first argument passed is a copy
4308 ** of the second argument to sqlite3_collation_needed() or
4309 ** sqlite3_collation_needed16().  The second argument is the database
4310 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4311 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4312 ** sequence function required.  The fourth parameter is the name of the
4313 ** required collation sequence.)^
4314 **
4315 ** The callback function should register the desired collation using
4316 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4317 ** [sqlite3_create_collation_v2()].
4318 */
4319 SQLITE_API int sqlite3_collation_needed(
4320   sqlite3*, 
4321   void*, 
4322   void(*)(void*,sqlite3*,int eTextRep,const char*)
4323 );
4324 SQLITE_API int sqlite3_collation_needed16(
4325   sqlite3*, 
4326   void*,
4327   void(*)(void*,sqlite3*,int eTextRep,const void*)
4328 );
4329
4330 #ifdef SQLITE_HAS_CODEC
4331 /*
4332 ** Specify the key for an encrypted database.  This routine should be
4333 ** called right after sqlite3_open().
4334 **
4335 ** The code to implement this API is not available in the public release
4336 ** of SQLite.
4337 */
4338 SQLITE_API int sqlite3_key(
4339   sqlite3 *db,                   /* Database to be rekeyed */
4340   const void *pKey, int nKey     /* The key */
4341 );
4342
4343 /*
4344 ** Change the key on an open database.  If the current database is not
4345 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4346 ** database is decrypted.
4347 **
4348 ** The code to implement this API is not available in the public release
4349 ** of SQLite.
4350 */
4351 SQLITE_API int sqlite3_rekey(
4352   sqlite3 *db,                   /* Database to be rekeyed */
4353   const void *pKey, int nKey     /* The new key */
4354 );
4355
4356 /*
4357 ** Specify the activation key for a SEE database.  Unless 
4358 ** activated, none of the SEE routines will work.
4359 */
4360 SQLITE_API void sqlite3_activate_see(
4361   const char *zPassPhrase        /* Activation phrase */
4362 );
4363 #endif
4364
4365 #ifdef SQLITE_ENABLE_CEROD
4366 /*
4367 ** Specify the activation key for a CEROD database.  Unless 
4368 ** activated, none of the CEROD routines will work.
4369 */
4370 SQLITE_API void sqlite3_activate_cerod(
4371   const char *zPassPhrase        /* Activation phrase */
4372 );
4373 #endif
4374
4375 /*
4376 ** CAPI3REF: Suspend Execution For A Short Time
4377 **
4378 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
4379 ** for at least a number of milliseconds specified in its parameter.
4380 **
4381 ** ^If the operating system does not support sleep requests with
4382 ** millisecond time resolution, then the time will be rounded up to
4383 ** the nearest second. ^The number of milliseconds of sleep actually
4384 ** requested from the operating system is returned.
4385 **
4386 ** ^SQLite implements this interface by calling the xSleep()
4387 ** method of the default [sqlite3_vfs] object.
4388 */
4389 SQLITE_API int sqlite3_sleep(int);
4390
4391 /*
4392 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4393 **
4394 ** ^(If this global variable is made to point to a string which is
4395 ** the name of a folder (a.k.a. directory), then all temporary files
4396 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4397 ** will be placed in that directory.)^  ^If this variable
4398 ** is a NULL pointer, then SQLite performs a search for an appropriate
4399 ** temporary file directory.
4400 **
4401 ** It is not safe to read or modify this variable in more than one
4402 ** thread at a time.  It is not safe to read or modify this variable
4403 ** if a [database connection] is being used at the same time in a separate
4404 ** thread.
4405 ** It is intended that this variable be set once
4406 ** as part of process initialization and before any SQLite interface
4407 ** routines have been called and that this variable remain unchanged
4408 ** thereafter.
4409 **
4410 ** ^The [temp_store_directory pragma] may modify this variable and cause
4411 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4412 ** the [temp_store_directory pragma] always assumes that any string
4413 ** that this variable points to is held in memory obtained from 
4414 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4415 ** using [sqlite3_free].
4416 ** Hence, if this variable is modified directly, either it should be
4417 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4418 ** or else the use of the [temp_store_directory pragma] should be avoided.
4419 */
4420 SQLITE_API char *sqlite3_temp_directory;
4421
4422 /*
4423 ** CAPI3REF: Test For Auto-Commit Mode
4424 ** KEYWORDS: {autocommit mode}
4425 **
4426 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4427 ** zero if the given database connection is or is not in autocommit mode,
4428 ** respectively.  ^Autocommit mode is on by default.
4429 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4430 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4431 **
4432 ** If certain kinds of errors occur on a statement within a multi-statement
4433 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4434 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4435 ** transaction might be rolled back automatically.  The only way to
4436 ** find out whether SQLite automatically rolled back the transaction after
4437 ** an error is to use this function.
4438 **
4439 ** If another thread changes the autocommit status of the database
4440 ** connection while this routine is running, then the return value
4441 ** is undefined.
4442 */
4443 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4444
4445 /*
4446 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4447 **
4448 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4449 ** to which a [prepared statement] belongs.  ^The [database connection]
4450 ** returned by sqlite3_db_handle is the same [database connection]
4451 ** that was the first argument
4452 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4453 ** create the statement in the first place.
4454 */
4455 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4456
4457 /*
4458 ** CAPI3REF: Find the next prepared statement
4459 **
4460 ** ^This interface returns a pointer to the next [prepared statement] after
4461 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4462 ** then this interface returns a pointer to the first prepared statement
4463 ** associated with the database connection pDb.  ^If no prepared statement
4464 ** satisfies the conditions of this routine, it returns NULL.
4465 **
4466 ** The [database connection] pointer D in a call to
4467 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4468 ** connection and in particular must not be a NULL pointer.
4469 */
4470 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4471
4472 /*
4473 ** CAPI3REF: Commit And Rollback Notification Callbacks
4474 **
4475 ** ^The sqlite3_commit_hook() interface registers a callback
4476 ** function to be invoked whenever a transaction is [COMMIT | committed].
4477 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4478 ** for the same database connection is overridden.
4479 ** ^The sqlite3_rollback_hook() interface registers a callback
4480 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4481 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4482 ** for the same database connection is overridden.
4483 ** ^The pArg argument is passed through to the callback.
4484 ** ^If the callback on a commit hook function returns non-zero,
4485 ** then the commit is converted into a rollback.
4486 **
4487 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4488 ** return the P argument from the previous call of the same function
4489 ** on the same [database connection] D, or NULL for
4490 ** the first call for each function on D.
4491 **
4492 ** The callback implementation must not do anything that will modify
4493 ** the database connection that invoked the callback.  Any actions
4494 ** to modify the database connection must be deferred until after the
4495 ** completion of the [sqlite3_step()] call that triggered the commit
4496 ** or rollback hook in the first place.
4497 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4498 ** database connections for the meaning of "modify" in this paragraph.
4499 **
4500 ** ^Registering a NULL function disables the callback.
4501 **
4502 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4503 ** operation is allowed to continue normally.  ^If the commit hook
4504 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4505 ** ^The rollback hook is invoked on a rollback that results from a commit
4506 ** hook returning non-zero, just as it would be with any other rollback.
4507 **
4508 ** ^For the purposes of this API, a transaction is said to have been
4509 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4510 ** an error or constraint causes an implicit rollback to occur.
4511 ** ^The rollback callback is not invoked if a transaction is
4512 ** automatically rolled back because the database connection is closed.
4513 **
4514 ** See also the [sqlite3_update_hook()] interface.
4515 */
4516 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4517 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4518
4519 /*
4520 ** CAPI3REF: Data Change Notification Callbacks
4521 **
4522 ** ^The sqlite3_update_hook() interface registers a callback function
4523 ** with the [database connection] identified by the first argument
4524 ** to be invoked whenever a row is updated, inserted or deleted.
4525 ** ^Any callback set by a previous call to this function
4526 ** for the same database connection is overridden.
4527 **
4528 ** ^The second argument is a pointer to the function to invoke when a
4529 ** row is updated, inserted or deleted.
4530 ** ^The first argument to the callback is a copy of the third argument
4531 ** to sqlite3_update_hook().
4532 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4533 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4534 ** to be invoked.
4535 ** ^The third and fourth arguments to the callback contain pointers to the
4536 ** database and table name containing the affected row.
4537 ** ^The final callback parameter is the [rowid] of the row.
4538 ** ^In the case of an update, this is the [rowid] after the update takes place.
4539 **
4540 ** ^(The update hook is not invoked when internal system tables are
4541 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4542 **
4543 ** ^In the current implementation, the update hook
4544 ** is not invoked when duplication rows are deleted because of an
4545 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4546 ** invoked when rows are deleted using the [truncate optimization].
4547 ** The exceptions defined in this paragraph might change in a future
4548 ** release of SQLite.
4549 **
4550 ** The update hook implementation must not do anything that will modify
4551 ** the database connection that invoked the update hook.  Any actions
4552 ** to modify the database connection must be deferred until after the
4553 ** completion of the [sqlite3_step()] call that triggered the update hook.
4554 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4555 ** database connections for the meaning of "modify" in this paragraph.
4556 **
4557 ** ^The sqlite3_update_hook(D,C,P) function
4558 ** returns the P argument from the previous call
4559 ** on the same [database connection] D, or NULL for
4560 ** the first call on D.
4561 **
4562 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4563 ** interfaces.
4564 */
4565 SQLITE_API void *sqlite3_update_hook(
4566   sqlite3*, 
4567   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4568   void*
4569 );
4570
4571 /*
4572 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4573 ** KEYWORDS: {shared cache}
4574 **
4575 ** ^(This routine enables or disables the sharing of the database cache
4576 ** and schema data structures between [database connection | connections]
4577 ** to the same database. Sharing is enabled if the argument is true
4578 ** and disabled if the argument is false.)^
4579 **
4580 ** ^Cache sharing is enabled and disabled for an entire process.
4581 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4582 ** sharing was enabled or disabled for each thread separately.
4583 **
4584 ** ^(The cache sharing mode set by this interface effects all subsequent
4585 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4586 ** Existing database connections continue use the sharing mode
4587 ** that was in effect at the time they were opened.)^
4588 **
4589 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4590 ** successfully.  An [error code] is returned otherwise.)^
4591 **
4592 ** ^Shared cache is disabled by default. But this might change in
4593 ** future releases of SQLite.  Applications that care about shared
4594 ** cache setting should set it explicitly.
4595 **
4596 ** See Also:  [SQLite Shared-Cache Mode]
4597 */
4598 SQLITE_API int sqlite3_enable_shared_cache(int);
4599
4600 /*
4601 ** CAPI3REF: Attempt To Free Heap Memory
4602 **
4603 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4604 ** of heap memory by deallocating non-essential memory allocations
4605 ** held by the database library.   Memory used to cache database
4606 ** pages to improve performance is an example of non-essential memory.
4607 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4608 ** which might be more or less than the amount requested.
4609 */
4610 SQLITE_API int sqlite3_release_memory(int);
4611
4612 /*
4613 ** CAPI3REF: Impose A Limit On Heap Size
4614 **
4615 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4616 ** on the amount of heap memory that may be allocated by SQLite.
4617 ** ^If an internal allocation is requested that would exceed the
4618 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4619 ** more times to free up some space before the allocation is performed.
4620 **
4621 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4622 ** cannot free sufficient memory to prevent the limit from being exceeded,
4623 ** the memory is allocated anyway and the current operation proceeds.
4624 **
4625 ** ^A negative or zero value for N means that there is no soft heap limit and
4626 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4627 ** ^The default value for the soft heap limit is zero.
4628 **
4629 ** ^(SQLite makes a best effort to honor the soft heap limit.
4630 ** But if the soft heap limit cannot be honored, execution will
4631 ** continue without error or notification.)^  This is why the limit is
4632 ** called a "soft" limit.  It is advisory only.
4633 **
4634 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4635 ** allocated by a single thread - the same thread in which this routine
4636 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4637 ** applied to all threads. The value specified for the soft heap limit
4638 ** is an upper bound on the total memory allocation for all threads. In
4639 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4640 ** individual threads.
4641 */
4642 SQLITE_API void sqlite3_soft_heap_limit(int);
4643
4644 /*
4645 ** CAPI3REF: Extract Metadata About A Column Of A Table
4646 **
4647 ** ^This routine returns metadata about a specific column of a specific
4648 ** database table accessible using the [database connection] handle
4649 ** passed as the first function argument.
4650 **
4651 ** ^The column is identified by the second, third and fourth parameters to
4652 ** this function. ^The second parameter is either the name of the database
4653 ** (i.e. "main", "temp", or an attached database) containing the specified
4654 ** table or NULL. ^If it is NULL, then all attached databases are searched
4655 ** for the table using the same algorithm used by the database engine to
4656 ** resolve unqualified table references.
4657 **
4658 ** ^The third and fourth parameters to this function are the table and column
4659 ** name of the desired column, respectively. Neither of these parameters
4660 ** may be NULL.
4661 **
4662 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4663 ** and subsequent parameters to this function. ^Any of these arguments may be
4664 ** NULL, in which case the corresponding element of metadata is omitted.
4665 **
4666 ** ^(<blockquote>
4667 ** <table border="1">
4668 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4669 **
4670 ** <tr><td> 5th <td> const char* <td> Data type
4671 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4672 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4673 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4674 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4675 ** </table>
4676 ** </blockquote>)^
4677 **
4678 ** ^The memory pointed to by the character pointers returned for the
4679 ** declaration type and collation sequence is valid only until the next
4680 ** call to any SQLite API function.
4681 **
4682 ** ^If the specified table is actually a view, an [error code] is returned.
4683 **
4684 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4685 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4686 ** parameters are set for the explicitly declared column. ^(If there is no
4687 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4688 ** parameters are set as follows:
4689 **
4690 ** <pre>
4691 **     data type: "INTEGER"
4692 **     collation sequence: "BINARY"
4693 **     not null: 0
4694 **     primary key: 1
4695 **     auto increment: 0
4696 ** </pre>)^
4697 **
4698 ** ^(This function may load one or more schemas from database files. If an
4699 ** error occurs during this process, or if the requested table or column
4700 ** cannot be found, an [error code] is returned and an error message left
4701 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4702 **
4703 ** ^This API is only available if the library was compiled with the
4704 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4705 */
4706 SQLITE_API int sqlite3_table_column_metadata(
4707   sqlite3 *db,                /* Connection handle */
4708   const char *zDbName,        /* Database name or NULL */
4709   const char *zTableName,     /* Table name */
4710   const char *zColumnName,    /* Column name */
4711   char const **pzDataType,    /* OUTPUT: Declared data type */
4712   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4713   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4714   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4715   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4716 );
4717
4718 /*
4719 ** CAPI3REF: Load An Extension
4720 **
4721 ** ^This interface loads an SQLite extension library from the named file.
4722 **
4723 ** ^The sqlite3_load_extension() interface attempts to load an
4724 ** SQLite extension library contained in the file zFile.
4725 **
4726 ** ^The entry point is zProc.
4727 ** ^zProc may be 0, in which case the name of the entry point
4728 ** defaults to "sqlite3_extension_init".
4729 ** ^The sqlite3_load_extension() interface returns
4730 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4731 ** ^If an error occurs and pzErrMsg is not 0, then the
4732 ** [sqlite3_load_extension()] interface shall attempt to
4733 ** fill *pzErrMsg with error message text stored in memory
4734 ** obtained from [sqlite3_malloc()]. The calling function
4735 ** should free this memory by calling [sqlite3_free()].
4736 **
4737 ** ^Extension loading must be enabled using
4738 ** [sqlite3_enable_load_extension()] prior to calling this API,
4739 ** otherwise an error will be returned.
4740 **
4741 ** See also the [load_extension() SQL function].
4742 */
4743 SQLITE_API int sqlite3_load_extension(
4744   sqlite3 *db,          /* Load the extension into this database connection */
4745   const char *zFile,    /* Name of the shared library containing extension */
4746   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4747   char **pzErrMsg       /* Put error message here if not 0 */
4748 );
4749
4750 /*
4751 ** CAPI3REF: Enable Or Disable Extension Loading
4752 **
4753 ** ^So as not to open security holes in older applications that are
4754 ** unprepared to deal with extension loading, and as a means of disabling
4755 ** extension loading while evaluating user-entered SQL, the following API
4756 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4757 **
4758 ** ^Extension loading is off by default. See ticket #1863.
4759 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4760 ** to turn extension loading on and call it with onoff==0 to turn
4761 ** it back off again.
4762 */
4763 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4764
4765 /*
4766 ** CAPI3REF: Automatically Load An Extensions
4767 **
4768 ** ^This API can be invoked at program startup in order to register
4769 ** one or more statically linked extensions that will be available
4770 ** to all new [database connections].
4771 **
4772 ** ^(This routine stores a pointer to the extension entry point
4773 ** in an array that is obtained from [sqlite3_malloc()].  That memory
4774 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4775 **
4776 ** ^This function registers an extension entry point that is
4777 ** automatically invoked whenever a new [database connection]
4778 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4779 ** or [sqlite3_open_v2()].
4780 ** ^Duplicate extensions are detected so calling this routine
4781 ** multiple times with the same extension is harmless.
4782 ** ^Automatic extensions apply across all threads.
4783 */
4784 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4785
4786 /*
4787 ** CAPI3REF: Reset Automatic Extension Loading
4788 **
4789 ** ^(This function disables all previously registered automatic
4790 ** extensions. It undoes the effect of all prior
4791 ** [sqlite3_auto_extension()] calls.)^
4792 **
4793 ** ^This function disables automatic extensions in all threads.
4794 */
4795 SQLITE_API void sqlite3_reset_auto_extension(void);
4796
4797 /*
4798 ** The interface to the virtual-table mechanism is currently considered
4799 ** to be experimental.  The interface might change in incompatible ways.
4800 ** If this is a problem for you, do not use the interface at this time.
4801 **
4802 ** When the virtual-table mechanism stabilizes, we will declare the
4803 ** interface fixed, support it indefinitely, and remove this comment.
4804 */
4805
4806 /*
4807 ** Structures used by the virtual table interface
4808 */
4809 typedef struct sqlite3_vtab sqlite3_vtab;
4810 typedef struct sqlite3_index_info sqlite3_index_info;
4811 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4812 typedef struct sqlite3_module sqlite3_module;
4813
4814 /*
4815 ** CAPI3REF: Virtual Table Object
4816 ** KEYWORDS: sqlite3_module {virtual table module}
4817 **
4818 ** This structure, sometimes called a a "virtual table module", 
4819 ** defines the implementation of a [virtual tables].  
4820 ** This structure consists mostly of methods for the module.
4821 **
4822 ** ^A virtual table module is created by filling in a persistent
4823 ** instance of this structure and passing a pointer to that instance
4824 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4825 ** ^The registration remains valid until it is replaced by a different
4826 ** module or until the [database connection] closes.  The content
4827 ** of this structure must not change while it is registered with
4828 ** any database connection.
4829 */
4830 struct sqlite3_module {
4831   int iVersion;
4832   int (*xCreate)(sqlite3*, void *pAux,
4833                int argc, const char *const*argv,
4834                sqlite3_vtab **ppVTab, char**);
4835   int (*xConnect)(sqlite3*, void *pAux,
4836                int argc, const char *const*argv,
4837                sqlite3_vtab **ppVTab, char**);
4838   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4839   int (*xDisconnect)(sqlite3_vtab *pVTab);
4840   int (*xDestroy)(sqlite3_vtab *pVTab);
4841   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4842   int (*xClose)(sqlite3_vtab_cursor*);
4843   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4844                 int argc, sqlite3_value **argv);
4845   int (*xNext)(sqlite3_vtab_cursor*);
4846   int (*xEof)(sqlite3_vtab_cursor*);
4847   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4848   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4849   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4850   int (*xBegin)(sqlite3_vtab *pVTab);
4851   int (*xSync)(sqlite3_vtab *pVTab);
4852   int (*xCommit)(sqlite3_vtab *pVTab);
4853   int (*xRollback)(sqlite3_vtab *pVTab);
4854   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4855                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4856                        void **ppArg);
4857   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4858 };
4859
4860 /*
4861 ** CAPI3REF: Virtual Table Indexing Information
4862 ** KEYWORDS: sqlite3_index_info
4863 **
4864 ** The sqlite3_index_info structure and its substructures is used to
4865 ** pass information into and receive the reply from the [xBestIndex]
4866 ** method of a [virtual table module].  The fields under **Inputs** are the
4867 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4868 ** results into the **Outputs** fields.
4869 **
4870 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
4871 **
4872 ** <pre>column OP expr</pre>
4873 **
4874 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4875 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4876 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4877 ** expr on the right-hand side can be evaluated (and thus the constraint
4878 ** is usable) and false if it cannot.)^
4879 **
4880 ** ^The optimizer automatically inverts terms of the form "expr OP column"
4881 ** and makes other simplifications to the WHERE clause in an attempt to
4882 ** get as many WHERE clause terms into the form shown above as possible.
4883 ** ^The aConstraint[] array only reports WHERE clause terms that are
4884 ** relevant to the particular virtual table being queried.
4885 **
4886 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
4887 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
4888 **
4889 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4890 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4891 ** the right-hand side of the corresponding aConstraint[] is evaluated
4892 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4893 ** is true, then the constraint is assumed to be fully handled by the
4894 ** virtual table and is not checked again by SQLite.)^
4895 **
4896 ** ^The idxNum and idxPtr values are recorded and passed into the
4897 ** [xFilter] method.
4898 ** ^[sqlite3_free()] is used to free idxPtr if and only if
4899 ** needToFreeIdxPtr is true.
4900 **
4901 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4902 ** the correct order to satisfy the ORDER BY clause so that no separate
4903 ** sorting step is required.
4904 **
4905 ** ^The estimatedCost value is an estimate of the cost of doing the
4906 ** particular lookup.  A full scan of a table with N entries should have
4907 ** a cost of N.  A binary search of a table of N entries should have a
4908 ** cost of approximately log(N).
4909 */
4910 struct sqlite3_index_info {
4911   /* Inputs */
4912   int nConstraint;           /* Number of entries in aConstraint */
4913   struct sqlite3_index_constraint {
4914      int iColumn;              /* Column on left-hand side of constraint */
4915      unsigned char op;         /* Constraint operator */
4916      unsigned char usable;     /* True if this constraint is usable */
4917      int iTermOffset;          /* Used internally - xBestIndex should ignore */
4918   } *aConstraint;            /* Table of WHERE clause constraints */
4919   int nOrderBy;              /* Number of terms in the ORDER BY clause */
4920   struct sqlite3_index_orderby {
4921      int iColumn;              /* Column number */
4922      unsigned char desc;       /* True for DESC.  False for ASC. */
4923   } *aOrderBy;               /* The ORDER BY clause */
4924   /* Outputs */
4925   struct sqlite3_index_constraint_usage {
4926     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4927     unsigned char omit;      /* Do not code a test for this constraint */
4928   } *aConstraintUsage;
4929   int idxNum;                /* Number used to identify the index */
4930   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4931   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4932   int orderByConsumed;       /* True if output is already ordered */
4933   double estimatedCost;      /* Estimated cost of using this index */
4934 };
4935 #define SQLITE_INDEX_CONSTRAINT_EQ    2
4936 #define SQLITE_INDEX_CONSTRAINT_GT    4
4937 #define SQLITE_INDEX_CONSTRAINT_LE    8
4938 #define SQLITE_INDEX_CONSTRAINT_LT    16
4939 #define SQLITE_INDEX_CONSTRAINT_GE    32
4940 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
4941
4942 /*
4943 ** CAPI3REF: Register A Virtual Table Implementation
4944 **
4945 ** ^These routines are used to register a new [virtual table module] name.
4946 ** ^Module names must be registered before
4947 ** creating a new [virtual table] using the module and before using a
4948 ** preexisting [virtual table] for the module.
4949 **
4950 ** ^The module name is registered on the [database connection] specified
4951 ** by the first parameter.  ^The name of the module is given by the 
4952 ** second parameter.  ^The third parameter is a pointer to
4953 ** the implementation of the [virtual table module].   ^The fourth
4954 ** parameter is an arbitrary client data pointer that is passed through
4955 ** into the [xCreate] and [xConnect] methods of the virtual table module
4956 ** when a new virtual table is be being created or reinitialized.
4957 **
4958 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4959 ** is a pointer to a destructor for the pClientData.  ^SQLite will
4960 ** invoke the destructor function (if it is not NULL) when SQLite
4961 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4962 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
4963 ** destructor.
4964 */
4965 SQLITE_API int sqlite3_create_module(
4966   sqlite3 *db,               /* SQLite connection to register module with */
4967   const char *zName,         /* Name of the module */
4968   const sqlite3_module *p,   /* Methods for the module */
4969   void *pClientData          /* Client data for xCreate/xConnect */
4970 );
4971 SQLITE_API int sqlite3_create_module_v2(
4972   sqlite3 *db,               /* SQLite connection to register module with */
4973   const char *zName,         /* Name of the module */
4974   const sqlite3_module *p,   /* Methods for the module */
4975   void *pClientData,         /* Client data for xCreate/xConnect */
4976   void(*xDestroy)(void*)     /* Module destructor function */
4977 );
4978
4979 /*
4980 ** CAPI3REF: Virtual Table Instance Object
4981 ** KEYWORDS: sqlite3_vtab
4982 **
4983 ** Every [virtual table module] implementation uses a subclass
4984 ** of this object to describe a particular instance
4985 ** of the [virtual table].  Each subclass will
4986 ** be tailored to the specific needs of the module implementation.
4987 ** The purpose of this superclass is to define certain fields that are
4988 ** common to all module implementations.
4989 **
4990 ** ^Virtual tables methods can set an error message by assigning a
4991 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4992 ** take care that any prior string is freed by a call to [sqlite3_free()]
4993 ** prior to assigning a new string to zErrMsg.  ^After the error message
4994 ** is delivered up to the client application, the string will be automatically
4995 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4996 */
4997 struct sqlite3_vtab {
4998   const sqlite3_module *pModule;  /* The module for this virtual table */
4999   int nRef;                       /* NO LONGER USED */
5000   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5001   /* Virtual table implementations will typically add additional fields */
5002 };
5003
5004 /*
5005 ** CAPI3REF: Virtual Table Cursor Object
5006 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5007 **
5008 ** Every [virtual table module] implementation uses a subclass of the
5009 ** following structure to describe cursors that point into the
5010 ** [virtual table] and are used
5011 ** to loop through the virtual table.  Cursors are created using the
5012 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5013 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5014 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5015 ** of the module.  Each module implementation will define
5016 ** the content of a cursor structure to suit its own needs.
5017 **
5018 ** This superclass exists in order to define fields of the cursor that
5019 ** are common to all implementations.
5020 */
5021 struct sqlite3_vtab_cursor {
5022   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5023   /* Virtual table implementations will typically add additional fields */
5024 };
5025
5026 /*
5027 ** CAPI3REF: Declare The Schema Of A Virtual Table
5028 **
5029 ** ^The [xCreate] and [xConnect] methods of a
5030 ** [virtual table module] call this interface
5031 ** to declare the format (the names and datatypes of the columns) of
5032 ** the virtual tables they implement.
5033 */
5034 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5035
5036 /*
5037 ** CAPI3REF: Overload A Function For A Virtual Table
5038 **
5039 ** ^(Virtual tables can provide alternative implementations of functions
5040 ** using the [xFindFunction] method of the [virtual table module].  
5041 ** But global versions of those functions
5042 ** must exist in order to be overloaded.)^
5043 **
5044 ** ^(This API makes sure a global version of a function with a particular
5045 ** name and number of parameters exists.  If no such function exists
5046 ** before this API is called, a new function is created.)^  ^The implementation
5047 ** of the new function always causes an exception to be thrown.  So
5048 ** the new function is not good for anything by itself.  Its only
5049 ** purpose is to be a placeholder function that can be overloaded
5050 ** by a [virtual table].
5051 */
5052 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5053
5054 /*
5055 ** The interface to the virtual-table mechanism defined above (back up
5056 ** to a comment remarkably similar to this one) is currently considered
5057 ** to be experimental.  The interface might change in incompatible ways.
5058 ** If this is a problem for you, do not use the interface at this time.
5059 **
5060 ** When the virtual-table mechanism stabilizes, we will declare the
5061 ** interface fixed, support it indefinitely, and remove this comment.
5062 */
5063
5064 /*
5065 ** CAPI3REF: A Handle To An Open BLOB
5066 ** KEYWORDS: {BLOB handle} {BLOB handles}
5067 **
5068 ** An instance of this object represents an open BLOB on which
5069 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5070 ** ^Objects of this type are created by [sqlite3_blob_open()]
5071 ** and destroyed by [sqlite3_blob_close()].
5072 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5073 ** can be used to read or write small subsections of the BLOB.
5074 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5075 */
5076 typedef struct sqlite3_blob sqlite3_blob;
5077
5078 /*
5079 ** CAPI3REF: Open A BLOB For Incremental I/O
5080 **
5081 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5082 ** in row iRow, column zColumn, table zTable in database zDb;
5083 ** in other words, the same BLOB that would be selected by:
5084 **
5085 ** <pre>
5086 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5087 ** </pre>)^
5088 **
5089 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5090 ** and write access. ^If it is zero, the BLOB is opened for read access.
5091 ** ^It is not possible to open a column that is part of an index or primary 
5092 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5093 ** not possible to open a column that is part of a [child key] for writing.
5094 **
5095 ** ^Note that the database name is not the filename that contains
5096 ** the database but rather the symbolic name of the database that
5097 ** appears after the AS keyword when the database is connected using [ATTACH].
5098 ** ^For the main database file, the database name is "main".
5099 ** ^For TEMP tables, the database name is "temp".
5100 **
5101 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5102 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5103 ** to be a null pointer.)^
5104 ** ^This function sets the [database connection] error code and message
5105 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5106 ** functions. ^Note that the *ppBlob variable is always initialized in a
5107 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5108 ** regardless of the success or failure of this routine.
5109 **
5110 ** ^(If the row that a BLOB handle points to is modified by an
5111 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5112 ** then the BLOB handle is marked as "expired".
5113 ** This is true if any column of the row is changed, even a column
5114 ** other than the one the BLOB handle is open on.)^
5115 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5116 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5117 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5118 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5119 ** commit if the transaction continues to completion.)^
5120 **
5121 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5122 ** the opened blob.  ^The size of a blob may not be changed by this
5123 ** interface.  Use the [UPDATE] SQL command to change the size of a
5124 ** blob.
5125 **
5126 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5127 ** and the built-in [zeroblob] SQL function can be used, if desired,
5128 ** to create an empty, zero-filled blob in which to read or write using
5129 ** this interface.
5130 **
5131 ** To avoid a resource leak, every open [BLOB handle] should eventually
5132 ** be released by a call to [sqlite3_blob_close()].
5133 */
5134 SQLITE_API int sqlite3_blob_open(
5135   sqlite3*,
5136   const char *zDb,
5137   const char *zTable,
5138   const char *zColumn,
5139   sqlite3_int64 iRow,
5140   int flags,
5141   sqlite3_blob **ppBlob
5142 );
5143
5144 /*
5145 ** CAPI3REF: Close A BLOB Handle
5146 **
5147 ** ^Closes an open [BLOB handle].
5148 **
5149 ** ^Closing a BLOB shall cause the current transaction to commit
5150 ** if there are no other BLOBs, no pending prepared statements, and the
5151 ** database connection is in [autocommit mode].
5152 ** ^If any writes were made to the BLOB, they might be held in cache
5153 ** until the close operation if they will fit.
5154 **
5155 ** ^(Closing the BLOB often forces the changes
5156 ** out to disk and so if any I/O errors occur, they will likely occur
5157 ** at the time when the BLOB is closed.  Any errors that occur during
5158 ** closing are reported as a non-zero return value.)^
5159 **
5160 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5161 ** an error code, the BLOB is still closed.)^
5162 **
5163 ** ^Calling this routine with a null pointer (such as would be returned
5164 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5165 */
5166 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5167
5168 /*
5169 ** CAPI3REF: Return The Size Of An Open BLOB
5170 **
5171 ** ^Returns the size in bytes of the BLOB accessible via the 
5172 ** successfully opened [BLOB handle] in its only argument.  ^The
5173 ** incremental blob I/O routines can only read or overwriting existing
5174 ** blob content; they cannot change the size of a blob.
5175 **
5176 ** This routine only works on a [BLOB handle] which has been created
5177 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5178 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5179 ** to this routine results in undefined and probably undesirable behavior.
5180 */
5181 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5182
5183 /*
5184 ** CAPI3REF: Read Data From A BLOB Incrementally
5185 **
5186 ** ^(This function is used to read data from an open [BLOB handle] into a
5187 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5188 ** from the open BLOB, starting at offset iOffset.)^
5189 **
5190 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5191 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5192 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5193 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5194 ** can be determined using the [sqlite3_blob_bytes()] interface.
5195 **
5196 ** ^An attempt to read from an expired [BLOB handle] fails with an
5197 ** error code of [SQLITE_ABORT].
5198 **
5199 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5200 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5201 **
5202 ** This routine only works on a [BLOB handle] which has been created
5203 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5204 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5205 ** to this routine results in undefined and probably undesirable behavior.
5206 **
5207 ** See also: [sqlite3_blob_write()].
5208 */
5209 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5210
5211 /*
5212 ** CAPI3REF: Write Data Into A BLOB Incrementally
5213 **
5214 ** ^This function is used to write data into an open [BLOB handle] from a
5215 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5216 ** into the open BLOB, starting at offset iOffset.
5217 **
5218 ** ^If the [BLOB handle] passed as the first argument was not opened for
5219 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5220 ** this function returns [SQLITE_READONLY].
5221 **
5222 ** ^This function may only modify the contents of the BLOB; it is
5223 ** not possible to increase the size of a BLOB using this API.
5224 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5225 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5226 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5227 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5228 ** can be determined using the [sqlite3_blob_bytes()] interface.
5229 **
5230 ** ^An attempt to write to an expired [BLOB handle] fails with an
5231 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5232 ** before the [BLOB handle] expired are not rolled back by the
5233 ** expiration of the handle, though of course those changes might
5234 ** have been overwritten by the statement that expired the BLOB handle
5235 ** or by other independent statements.
5236 **
5237 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5238 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5239 **
5240 ** This routine only works on a [BLOB handle] which has been created
5241 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5242 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5243 ** to this routine results in undefined and probably undesirable behavior.
5244 **
5245 ** See also: [sqlite3_blob_read()].
5246 */
5247 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5248
5249 /*
5250 ** CAPI3REF: Virtual File System Objects
5251 **
5252 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5253 ** that SQLite uses to interact
5254 ** with the underlying operating system.  Most SQLite builds come with a
5255 ** single default VFS that is appropriate for the host computer.
5256 ** New VFSes can be registered and existing VFSes can be unregistered.
5257 ** The following interfaces are provided.
5258 **
5259 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5260 ** ^Names are case sensitive.
5261 ** ^Names are zero-terminated UTF-8 strings.
5262 ** ^If there is no match, a NULL pointer is returned.
5263 ** ^If zVfsName is NULL then the default VFS is returned.
5264 **
5265 ** ^New VFSes are registered with sqlite3_vfs_register().
5266 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5267 ** ^The same VFS can be registered multiple times without injury.
5268 ** ^To make an existing VFS into the default VFS, register it again
5269 ** with the makeDflt flag set.  If two different VFSes with the
5270 ** same name are registered, the behavior is undefined.  If a
5271 ** VFS is registered with a name that is NULL or an empty string,
5272 ** then the behavior is undefined.
5273 **
5274 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5275 ** ^(If the default VFS is unregistered, another VFS is chosen as
5276 ** the default.  The choice for the new VFS is arbitrary.)^
5277 */
5278 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5279 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5280 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5281
5282 /*
5283 ** CAPI3REF: Mutexes
5284 **
5285 ** The SQLite core uses these routines for thread
5286 ** synchronization. Though they are intended for internal
5287 ** use by SQLite, code that links against SQLite is
5288 ** permitted to use any of these routines.
5289 **
5290 ** The SQLite source code contains multiple implementations
5291 ** of these mutex routines.  An appropriate implementation
5292 ** is selected automatically at compile-time.  ^(The following
5293 ** implementations are available in the SQLite core:
5294 **
5295 ** <ul>
5296 ** <li>   SQLITE_MUTEX_OS2
5297 ** <li>   SQLITE_MUTEX_PTHREAD
5298 ** <li>   SQLITE_MUTEX_W32
5299 ** <li>   SQLITE_MUTEX_NOOP
5300 ** </ul>)^
5301 **
5302 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5303 ** that does no real locking and is appropriate for use in
5304 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5305 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5306 ** are appropriate for use on OS/2, Unix, and Windows.
5307 **
5308 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5309 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5310 ** implementation is included with the library. In this case the
5311 ** application must supply a custom mutex implementation using the
5312 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5313 ** before calling sqlite3_initialize() or any other public sqlite3_
5314 ** function that calls sqlite3_initialize().)^
5315 **
5316 ** ^The sqlite3_mutex_alloc() routine allocates a new
5317 ** mutex and returns a pointer to it. ^If it returns NULL
5318 ** that means that a mutex could not be allocated.  ^SQLite
5319 ** will unwind its stack and return an error.  ^(The argument
5320 ** to sqlite3_mutex_alloc() is one of these integer constants:
5321 **
5322 ** <ul>
5323 ** <li>  SQLITE_MUTEX_FAST
5324 ** <li>  SQLITE_MUTEX_RECURSIVE
5325 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5326 ** <li>  SQLITE_MUTEX_STATIC_MEM
5327 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5328 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5329 ** <li>  SQLITE_MUTEX_STATIC_LRU
5330 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5331 ** </ul>)^
5332 **
5333 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5334 ** cause sqlite3_mutex_alloc() to create
5335 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5336 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5337 ** The mutex implementation does not need to make a distinction
5338 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5339 ** not want to.  ^SQLite will only request a recursive mutex in
5340 ** cases where it really needs one.  ^If a faster non-recursive mutex
5341 ** implementation is available on the host platform, the mutex subsystem
5342 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5343 **
5344 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5345 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5346 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5347 ** used by the current version of SQLite.  Future versions of SQLite
5348 ** may add additional static mutexes.  Static mutexes are for internal
5349 ** use by SQLite only.  Applications that use SQLite mutexes should
5350 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5351 ** SQLITE_MUTEX_RECURSIVE.
5352 **
5353 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5354 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5355 ** returns a different mutex on every call.  ^But for the static
5356 ** mutex types, the same mutex is returned on every call that has
5357 ** the same type number.
5358 **
5359 ** ^The sqlite3_mutex_free() routine deallocates a previously
5360 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5361 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5362 ** use when they are deallocated.  Attempting to deallocate a static
5363 ** mutex results in undefined behavior.  ^SQLite never deallocates
5364 ** a static mutex.
5365 **
5366 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5367 ** to enter a mutex.  ^If another thread is already within the mutex,
5368 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5369 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5370 ** upon successful entry.  ^(Mutexes created using
5371 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5372 ** In such cases the,
5373 ** mutex must be exited an equal number of times before another thread
5374 ** can enter.)^  ^(If the same thread tries to enter any other
5375 ** kind of mutex more than once, the behavior is undefined.
5376 ** SQLite will never exhibit
5377 ** such behavior in its own use of mutexes.)^
5378 **
5379 ** ^(Some systems (for example, Windows 95) do not support the operation
5380 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5381 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5382 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5383 **
5384 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5385 ** previously entered by the same thread.   ^(The behavior
5386 ** is undefined if the mutex is not currently entered by the
5387 ** calling thread or is not currently allocated.  SQLite will
5388 ** never do either.)^
5389 **
5390 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5391 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5392 ** behave as no-ops.
5393 **
5394 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5395 */
5396 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5397 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5398 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5399 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5400 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5401
5402 /*
5403 ** CAPI3REF: Mutex Methods Object
5404 **
5405 ** An instance of this structure defines the low-level routines
5406 ** used to allocate and use mutexes.
5407 **
5408 ** Usually, the default mutex implementations provided by SQLite are
5409 ** sufficient, however the user has the option of substituting a custom
5410 ** implementation for specialized deployments or systems for which SQLite
5411 ** does not provide a suitable implementation. In this case, the user
5412 ** creates and populates an instance of this structure to pass
5413 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5414 ** Additionally, an instance of this structure can be used as an
5415 ** output variable when querying the system for the current mutex
5416 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5417 **
5418 ** ^The xMutexInit method defined by this structure is invoked as
5419 ** part of system initialization by the sqlite3_initialize() function.
5420 ** ^The xMutexInit routine is calle by SQLite exactly once for each
5421 ** effective call to [sqlite3_initialize()].
5422 **
5423 ** ^The xMutexEnd method defined by this structure is invoked as
5424 ** part of system shutdown by the sqlite3_shutdown() function. The
5425 ** implementation of this method is expected to release all outstanding
5426 ** resources obtained by the mutex methods implementation, especially
5427 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5428 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5429 **
5430 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5431 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5432 ** xMutexNotheld) implement the following interfaces (respectively):
5433 **
5434 ** <ul>
5435 **   <li>  [sqlite3_mutex_alloc()] </li>
5436 **   <li>  [sqlite3_mutex_free()] </li>
5437 **   <li>  [sqlite3_mutex_enter()] </li>
5438 **   <li>  [sqlite3_mutex_try()] </li>
5439 **   <li>  [sqlite3_mutex_leave()] </li>
5440 **   <li>  [sqlite3_mutex_held()] </li>
5441 **   <li>  [sqlite3_mutex_notheld()] </li>
5442 ** </ul>)^
5443 **
5444 ** The only difference is that the public sqlite3_XXX functions enumerated
5445 ** above silently ignore any invocations that pass a NULL pointer instead
5446 ** of a valid mutex handle. The implementations of the methods defined
5447 ** by this structure are not required to handle this case, the results
5448 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5449 ** (i.e. it is acceptable to provide an implementation that segfaults if
5450 ** it is passed a NULL pointer).
5451 **
5452 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5453 ** invoke xMutexInit() mutiple times within the same process and without
5454 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5455 ** xMutexInit() must be no-ops.
5456 **
5457 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5458 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5459 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5460 ** memory allocation for a fast or recursive mutex.
5461 **
5462 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5463 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5464 ** If xMutexInit fails in any way, it is expected to clean up after itself
5465 ** prior to returning.
5466 */
5467 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5468 struct sqlite3_mutex_methods {
5469   int (*xMutexInit)(void);
5470   int (*xMutexEnd)(void);
5471   sqlite3_mutex *(*xMutexAlloc)(int);
5472   void (*xMutexFree)(sqlite3_mutex *);
5473   void (*xMutexEnter)(sqlite3_mutex *);
5474   int (*xMutexTry)(sqlite3_mutex *);
5475   void (*xMutexLeave)(sqlite3_mutex *);
5476   int (*xMutexHeld)(sqlite3_mutex *);
5477   int (*xMutexNotheld)(sqlite3_mutex *);
5478 };
5479
5480 /*
5481 ** CAPI3REF: Mutex Verification Routines
5482 **
5483 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5484 ** are intended for use inside assert() statements.  ^The SQLite core
5485 ** never uses these routines except inside an assert() and applications
5486 ** are advised to follow the lead of the core.  ^The SQLite core only
5487 ** provides implementations for these routines when it is compiled
5488 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5489 ** are only required to provide these routines if SQLITE_DEBUG is
5490 ** defined and if NDEBUG is not defined.
5491 **
5492 ** ^These routines should return true if the mutex in their argument
5493 ** is held or not held, respectively, by the calling thread.
5494 **
5495 ** ^The implementation is not required to provided versions of these
5496 ** routines that actually work. If the implementation does not provide working
5497 ** versions of these routines, it should at least provide stubs that always
5498 ** return true so that one does not get spurious assertion failures.
5499 **
5500 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5501 ** the routine should return 1.   This seems counter-intuitive since
5502 ** clearly the mutex cannot be held if it does not exist.  But the
5503 ** the reason the mutex does not exist is because the build is not
5504 ** using mutexes.  And we do not want the assert() containing the
5505 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5506 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5507 ** interface should also return 1 when given a NULL pointer.
5508 */
5509 #ifndef NDEBUG
5510 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5511 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5512 #endif
5513
5514 /*
5515 ** CAPI3REF: Mutex Types
5516 **
5517 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5518 ** which is one of these integer constants.
5519 **
5520 ** The set of static mutexes may change from one SQLite release to the
5521 ** next.  Applications that override the built-in mutex logic must be
5522 ** prepared to accommodate additional static mutexes.
5523 */
5524 #define SQLITE_MUTEX_FAST             0
5525 #define SQLITE_MUTEX_RECURSIVE        1
5526 #define SQLITE_MUTEX_STATIC_MASTER    2
5527 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5528 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5529 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5530 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5531 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5532 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5533
5534 /*
5535 ** CAPI3REF: Retrieve the mutex for a database connection
5536 **
5537 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5538 ** serializes access to the [database connection] given in the argument
5539 ** when the [threading mode] is Serialized.
5540 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5541 ** routine returns a NULL pointer.
5542 */
5543 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5544
5545 /*
5546 ** CAPI3REF: Low-Level Control Of Database Files
5547 **
5548 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5549 ** xFileControl method for the [sqlite3_io_methods] object associated
5550 ** with a particular database identified by the second argument. ^The
5551 ** name of the database "main" for the main database or "temp" for the
5552 ** TEMP database, or the name that appears after the AS keyword for
5553 ** databases that are added using the [ATTACH] SQL command.
5554 ** ^A NULL pointer can be used in place of "main" to refer to the
5555 ** main database file.
5556 ** ^The third and fourth parameters to this routine
5557 ** are passed directly through to the second and third parameters of
5558 ** the xFileControl method.  ^The return value of the xFileControl
5559 ** method becomes the return value of this routine.
5560 **
5561 ** ^If the second parameter (zDbName) does not match the name of any
5562 ** open database file, then SQLITE_ERROR is returned.  ^This error
5563 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5564 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5565 ** also return SQLITE_ERROR.  There is no way to distinguish between
5566 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5567 ** xFileControl method.
5568 **
5569 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5570 */
5571 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5572
5573 /*
5574 ** CAPI3REF: Testing Interface
5575 **
5576 ** ^The sqlite3_test_control() interface is used to read out internal
5577 ** state of SQLite and to inject faults into SQLite for testing
5578 ** purposes.  ^The first parameter is an operation code that determines
5579 ** the number, meaning, and operation of all subsequent parameters.
5580 **
5581 ** This interface is not for use by applications.  It exists solely
5582 ** for verifying the correct operation of the SQLite library.  Depending
5583 ** on how the SQLite library is compiled, this interface might not exist.
5584 **
5585 ** The details of the operation codes, their meanings, the parameters
5586 ** they take, and what they do are all subject to change without notice.
5587 ** Unlike most of the SQLite API, this function is not guaranteed to
5588 ** operate consistently from one release to the next.
5589 */
5590 SQLITE_API int sqlite3_test_control(int op, ...);
5591
5592 /*
5593 ** CAPI3REF: Testing Interface Operation Codes
5594 **
5595 ** These constants are the valid operation code parameters used
5596 ** as the first argument to [sqlite3_test_control()].
5597 **
5598 ** These parameters and their meanings are subject to change
5599 ** without notice.  These values are for testing purposes only.
5600 ** Applications should not use any of these parameters or the
5601 ** [sqlite3_test_control()] interface.
5602 */
5603 #define SQLITE_TESTCTRL_FIRST                    5
5604 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5605 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5606 #define SQLITE_TESTCTRL_PRNG_RESET               7
5607 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5608 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5609 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5610 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5611 #define SQLITE_TESTCTRL_ASSERT                  12
5612 #define SQLITE_TESTCTRL_ALWAYS                  13
5613 #define SQLITE_TESTCTRL_RESERVE                 14
5614 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5615 #define SQLITE_TESTCTRL_ISKEYWORD               16
5616 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5617 #define SQLITE_TESTCTRL_LAST                    17
5618
5619 /*
5620 ** CAPI3REF: SQLite Runtime Status
5621 **
5622 ** ^This interface is used to retrieve runtime status information
5623 ** about the preformance of SQLite, and optionally to reset various
5624 ** highwater marks.  ^The first argument is an integer code for
5625 ** the specific parameter to measure.  ^(Recognized integer codes
5626 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5627 ** ^The current value of the parameter is returned into *pCurrent.
5628 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5629 ** resetFlag is true, then the highest record value is reset after
5630 ** *pHighwater is written.  ^(Some parameters do not record the highest
5631 ** value.  For those parameters
5632 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5633 ** ^(Other parameters record only the highwater mark and not the current
5634 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5635 **
5636 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5637 ** non-zero [error code] on failure.
5638 **
5639 ** This routine is threadsafe but is not atomic.  This routine can be
5640 ** called while other threads are running the same or different SQLite
5641 ** interfaces.  However the values returned in *pCurrent and
5642 ** *pHighwater reflect the status of SQLite at different points in time
5643 ** and it is possible that another thread might change the parameter
5644 ** in between the times when *pCurrent and *pHighwater are written.
5645 **
5646 ** See also: [sqlite3_db_status()]
5647 */
5648 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5649
5650
5651 /*
5652 ** CAPI3REF: Status Parameters
5653 **
5654 ** These integer constants designate various run-time status parameters
5655 ** that can be returned by [sqlite3_status()].
5656 **
5657 ** <dl>
5658 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5659 ** <dd>This parameter is the current amount of memory checked out
5660 ** using [sqlite3_malloc()], either directly or indirectly.  The
5661 ** figure includes calls made to [sqlite3_malloc()] by the application
5662 ** and internal memory usage by the SQLite library.  Scratch memory
5663 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5664 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5665 ** this parameter.  The amount returned is the sum of the allocation
5666 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5667 **
5668 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5669 ** <dd>This parameter records the largest memory allocation request
5670 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5671 ** internal equivalents).  Only the value returned in the
5672 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5673 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5674 **
5675 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5676 ** <dd>This parameter returns the number of pages used out of the
5677 ** [pagecache memory allocator] that was configured using 
5678 ** [SQLITE_CONFIG_PAGECACHE].  The
5679 ** value returned is in pages, not in bytes.</dd>)^
5680 **
5681 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5682 ** <dd>This parameter returns the number of bytes of page cache
5683 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5684 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5685 ** returned value includes allocations that overflowed because they
5686 ** where too large (they were larger than the "sz" parameter to
5687 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5688 ** no space was left in the page cache.</dd>)^
5689 **
5690 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5691 ** <dd>This parameter records the largest memory allocation request
5692 ** handed to [pagecache memory allocator].  Only the value returned in the
5693 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5694 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5695 **
5696 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5697 ** <dd>This parameter returns the number of allocations used out of the
5698 ** [scratch memory allocator] configured using
5699 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5700 ** in bytes.  Since a single thread may only have one scratch allocation
5701 ** outstanding at time, this parameter also reports the number of threads
5702 ** using scratch memory at the same time.</dd>)^
5703 **
5704 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5705 ** <dd>This parameter returns the number of bytes of scratch memory
5706 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5707 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5708 ** returned include overflows because the requested allocation was too
5709 ** larger (that is, because the requested allocation was larger than the
5710 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5711 ** slots were available.
5712 ** </dd>)^
5713 **
5714 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5715 ** <dd>This parameter records the largest memory allocation request
5716 ** handed to [scratch memory allocator].  Only the value returned in the
5717 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5718 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5719 **
5720 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5721 ** <dd>This parameter records the deepest parser stack.  It is only
5722 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5723 ** </dl>
5724 **
5725 ** New status parameters may be added from time to time.
5726 */
5727 #define SQLITE_STATUS_MEMORY_USED          0
5728 #define SQLITE_STATUS_PAGECACHE_USED       1
5729 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5730 #define SQLITE_STATUS_SCRATCH_USED         3
5731 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5732 #define SQLITE_STATUS_MALLOC_SIZE          5
5733 #define SQLITE_STATUS_PARSER_STACK         6
5734 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5735 #define SQLITE_STATUS_SCRATCH_SIZE         8
5736
5737 /*
5738 ** CAPI3REF: Database Connection Status
5739 **
5740 ** ^This interface is used to retrieve runtime status information 
5741 ** about a single [database connection].  ^The first argument is the
5742 ** database connection object to be interrogated.  ^The second argument
5743 ** is an integer constant, taken from the set of
5744 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5745 ** determiness the parameter to interrogate.  The set of 
5746 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5747 ** to grow in future releases of SQLite.
5748 **
5749 ** ^The current value of the requested parameter is written into *pCur
5750 ** and the highest instantaneous value is written into *pHiwtr.  ^If
5751 ** the resetFlg is true, then the highest instantaneous value is
5752 ** reset back down to the current value.
5753 **
5754 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5755 */
5756 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5757
5758 /*
5759 ** CAPI3REF: Status Parameters for database connections
5760 **
5761 ** These constants are the available integer "verbs" that can be passed as
5762 ** the second argument to the [sqlite3_db_status()] interface.
5763 **
5764 ** New verbs may be added in future releases of SQLite. Existing verbs
5765 ** might be discontinued. Applications should check the return code from
5766 ** [sqlite3_db_status()] to make sure that the call worked.
5767 ** The [sqlite3_db_status()] interface will return a non-zero error code
5768 ** if a discontinued or unsupported verb is invoked.
5769 **
5770 ** <dl>
5771 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5772 ** <dd>This parameter returns the number of lookaside memory slots currently
5773 ** checked out.</dd>)^
5774 **
5775 ** <dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5776 ** <dd>^This parameter returns the approximate number of of bytes of heap
5777 ** memory used by all pager caches associated with the database connection.
5778 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5779 ** </dd>
5780 ** </dl>
5781 */
5782 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5783 #define SQLITE_DBSTATUS_CACHE_USED         1
5784 #define SQLITE_DBSTATUS_MAX                1   /* Largest defined DBSTATUS */
5785
5786
5787 /*
5788 ** CAPI3REF: Prepared Statement Status
5789 **
5790 ** ^(Each prepared statement maintains various
5791 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5792 ** of times it has performed specific operations.)^  These counters can
5793 ** be used to monitor the performance characteristics of the prepared
5794 ** statements.  For example, if the number of table steps greatly exceeds
5795 ** the number of table searches or result rows, that would tend to indicate
5796 ** that the prepared statement is using a full table scan rather than
5797 ** an index.  
5798 **
5799 ** ^(This interface is used to retrieve and reset counter values from
5800 ** a [prepared statement].  The first argument is the prepared statement
5801 ** object to be interrogated.  The second argument
5802 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5803 ** to be interrogated.)^
5804 ** ^The current value of the requested counter is returned.
5805 ** ^If the resetFlg is true, then the counter is reset to zero after this
5806 ** interface call returns.
5807 **
5808 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
5809 */
5810 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5811
5812 /*
5813 ** CAPI3REF: Status Parameters for prepared statements
5814 **
5815 ** These preprocessor macros define integer codes that name counter
5816 ** values associated with the [sqlite3_stmt_status()] interface.
5817 ** The meanings of the various counters are as follows:
5818 **
5819 ** <dl>
5820 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5821 ** <dd>^This is the number of times that SQLite has stepped forward in
5822 ** a table as part of a full table scan.  Large numbers for this counter
5823 ** may indicate opportunities for performance improvement through 
5824 ** careful use of indices.</dd>
5825 **
5826 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
5827 ** <dd>^This is the number of sort operations that have occurred.
5828 ** A non-zero value in this counter may indicate an opportunity to
5829 ** improvement performance through careful use of indices.</dd>
5830 **
5831 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5832 ** <dd>^This is the number of rows inserted into transient indices that
5833 ** were created automatically in order to help joins run faster.
5834 ** A non-zero value in this counter may indicate an opportunity to
5835 ** improvement performance by adding permanent indices that do not
5836 ** need to be reinitialized each time the statement is run.</dd>
5837 **
5838 ** </dl>
5839 */
5840 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5841 #define SQLITE_STMTSTATUS_SORT              2
5842 #define SQLITE_STMTSTATUS_AUTOINDEX         3
5843
5844 /*
5845 ** CAPI3REF: Custom Page Cache Object
5846 **
5847 ** The sqlite3_pcache type is opaque.  It is implemented by
5848 ** the pluggable module.  The SQLite core has no knowledge of
5849 ** its size or internal structure and never deals with the
5850 ** sqlite3_pcache object except by holding and passing pointers
5851 ** to the object.
5852 **
5853 ** See [sqlite3_pcache_methods] for additional information.
5854 */
5855 typedef struct sqlite3_pcache sqlite3_pcache;
5856
5857 /*
5858 ** CAPI3REF: Application Defined Page Cache.
5859 ** KEYWORDS: {page cache}
5860 **
5861 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5862 ** register an alternative page cache implementation by passing in an 
5863 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the 
5864 ** heap memory used by SQLite is used by the page cache to cache data read 
5865 ** from, or ready to be written to, the database file. By implementing a 
5866 ** custom page cache using this API, an application can control more 
5867 ** precisely the amount of memory consumed by SQLite, the way in which 
5868 ** that memory is allocated and released, and the policies used to 
5869 ** determine exactly which parts of a database file are cached and for 
5870 ** how long.
5871 **
5872 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5873 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5874 ** the application may discard the parameter after the call to
5875 ** [sqlite3_config()] returns.)^
5876 **
5877 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5878 ** (usually only once during the lifetime of the process). ^(The xInit()
5879 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5880 ** ^The xInit() method can set up up global structures and/or any mutexes
5881 ** required by the custom page cache implementation. 
5882 **
5883 ** ^The xShutdown() method is called from within [sqlite3_shutdown()], 
5884 ** if the application invokes this API. It can be used to clean up 
5885 ** any outstanding resources before process shutdown, if required.
5886 **
5887 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5888 ** the xInit method, so the xInit method need not be threadsafe.  ^The
5889 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5890 ** not need to be threadsafe either.  All other methods must be threadsafe
5891 ** in multithreaded applications.
5892 **
5893 ** ^SQLite will never invoke xInit() more than once without an intervening
5894 ** call to xShutdown().
5895 **
5896 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
5897 ** will typically create one cache instance for each open database file,
5898 ** though this is not guaranteed. ^The
5899 ** first parameter, szPage, is the size in bytes of the pages that must
5900 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5901 ** will the page size of the database file that is to be cached plus an
5902 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5903 ** extra R bytes on each page to store metadata about the underlying
5904 ** database page on disk.  The value of R depends
5905 ** on the SQLite version, the target platform, and how SQLite was compiled.
5906 ** ^R is constant for a particular build of SQLite.  ^The second argument to
5907 ** xCreate(), bPurgeable, is true if the cache being created will
5908 ** be used to cache database pages of a file stored on disk, or
5909 ** false if it is used for an in-memory database. ^The cache implementation
5910 ** does not have to do anything special based with the value of bPurgeable;
5911 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5912 ** never invoke xUnpin() except to deliberately delete a page.
5913 ** ^In other words, a cache created with bPurgeable set to false will
5914 ** never contain any unpinned pages.
5915 **
5916 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5917 ** suggested maximum cache-size (number of pages stored by) the cache
5918 ** instance passed as the first argument. This is the value configured using
5919 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5920 ** parameter, the implementation is not required to do anything with this
5921 ** value; it is advisory only.
5922 **
5923 ** ^The xPagecount() method should return the number of pages currently
5924 ** stored in the cache.
5925 ** 
5926 ** ^The xFetch() method is used to fetch a page and return a pointer to it. 
5927 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5928 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5929 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
5930 ** is considered to be "pinned".
5931 **
5932 ** ^If the requested page is already in the page cache, then the page cache
5933 ** implementation must return a pointer to the page buffer with its content
5934 ** intact.  ^(If the requested page is not already in the cache, then the
5935 ** behavior of the cache implementation is determined by the value of the
5936 ** createFlag parameter passed to xFetch, according to the following table:
5937 **
5938 ** <table border=1 width=85% align=center>
5939 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5940 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5941 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5942 **                 Otherwise return NULL.
5943 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5944 **                 NULL if allocating a new page is effectively impossible.
5945 ** </table>)^
5946 **
5947 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5948 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5949 ** attempt to unpin one or more cache pages by spilling the content of
5950 ** pinned pages to disk and synching the operating system disk cache. After
5951 ** attempting to unpin pages, the xFetch() method will be invoked again with
5952 ** a createFlag of 2.
5953 **
5954 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5955 ** as its second argument. ^(If the third parameter, discard, is non-zero,
5956 ** then the page should be evicted from the cache. In this case SQLite 
5957 ** assumes that the next time the page is retrieved from the cache using
5958 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5959 ** zero, then the page is considered to be unpinned. ^The cache implementation
5960 ** may choose to evict unpinned pages at any time.
5961 **
5962 ** ^(The cache is not required to perform any reference counting. A single 
5963 ** call to xUnpin() unpins the page regardless of the number of prior calls 
5964 ** to xFetch().)^
5965 **
5966 ** ^The xRekey() method is used to change the key value associated with the
5967 ** page passed as the second argument from oldKey to newKey. ^If the cache
5968 ** previously contains an entry associated with newKey, it should be
5969 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5970 ** to be pinned.
5971 **
5972 ** ^When SQLite calls the xTruncate() method, the cache must discard all
5973 ** existing cache entries with page numbers (keys) greater than or equal
5974 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
5975 ** of these pages are pinned, they are implicitly unpinned, meaning that
5976 ** they can be safely discarded.
5977 **
5978 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5979 ** All resources associated with the specified cache should be freed. ^After
5980 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5981 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
5982 ** functions.
5983 */
5984 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5985 struct sqlite3_pcache_methods {
5986   void *pArg;
5987   int (*xInit)(void*);
5988   void (*xShutdown)(void*);
5989   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5990   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5991   int (*xPagecount)(sqlite3_pcache*);
5992   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5993   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5994   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5995   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5996   void (*xDestroy)(sqlite3_pcache*);
5997 };
5998
5999 /*
6000 ** CAPI3REF: Online Backup Object
6001 **
6002 ** The sqlite3_backup object records state information about an ongoing
6003 ** online backup operation.  ^The sqlite3_backup object is created by
6004 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6005 ** [sqlite3_backup_finish()].
6006 **
6007 ** See Also: [Using the SQLite Online Backup API]
6008 */
6009 typedef struct sqlite3_backup sqlite3_backup;
6010
6011 /*
6012 ** CAPI3REF: Online Backup API.
6013 **
6014 ** The backup API copies the content of one database into another.
6015 ** It is useful either for creating backups of databases or
6016 ** for copying in-memory databases to or from persistent files. 
6017 **
6018 ** See Also: [Using the SQLite Online Backup API]
6019 **
6020 ** ^Exclusive access is required to the destination database for the 
6021 ** duration of the operation. ^However the source database is only
6022 ** read-locked while it is actually being read; it is not locked
6023 ** continuously for the entire backup operation. ^Thus, the backup may be
6024 ** performed on a live source database without preventing other users from
6025 ** reading or writing to the source database while the backup is underway.
6026 ** 
6027 ** ^(To perform a backup operation: 
6028 **   <ol>
6029 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6030 **         backup, 
6031 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6032 **         the data between the two databases, and finally
6033 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6034 **         associated with the backup operation. 
6035 **   </ol>)^
6036 ** There should be exactly one call to sqlite3_backup_finish() for each
6037 ** successful call to sqlite3_backup_init().
6038 **
6039 ** <b>sqlite3_backup_init()</b>
6040 **
6041 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6042 ** [database connection] associated with the destination database 
6043 ** and the database name, respectively.
6044 ** ^The database name is "main" for the main database, "temp" for the
6045 ** temporary database, or the name specified after the AS keyword in
6046 ** an [ATTACH] statement for an attached database.
6047 ** ^The S and M arguments passed to 
6048 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6049 ** and database name of the source database, respectively.
6050 ** ^The source and destination [database connections] (parameters S and D)
6051 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6052 ** an error.
6053 **
6054 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6055 ** returned and an error code and error message are store3d in the
6056 ** destination [database connection] D.
6057 ** ^The error code and message for the failed call to sqlite3_backup_init()
6058 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6059 ** [sqlite3_errmsg16()] functions.
6060 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6061 ** [sqlite3_backup] object.
6062 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6063 ** sqlite3_backup_finish() functions to perform the specified backup 
6064 ** operation.
6065 **
6066 ** <b>sqlite3_backup_step()</b>
6067 **
6068 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6069 ** the source and destination databases specified by [sqlite3_backup] object B.
6070 ** ^If N is negative, all remaining source pages are copied. 
6071 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6072 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
6073 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6074 ** from source to destination, then it returns [SQLITE_DONE].
6075 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6076 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6077 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6078 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6079 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6080 **
6081 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6082 ** <ol>
6083 ** <li> the destination database was opened read-only, or
6084 ** <li> the destination database is using write-ahead-log journaling
6085 ** and the destination and source page sizes differ, or
6086 ** <li> The destination database is an in-memory database and the
6087 ** destination and source page sizes differ.
6088 ** </ol>)^
6089 **
6090 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6091 ** the [sqlite3_busy_handler | busy-handler function]
6092 ** is invoked (if one is specified). ^If the 
6093 ** busy-handler returns non-zero before the lock is available, then 
6094 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6095 ** sqlite3_backup_step() can be retried later. ^If the source
6096 ** [database connection]
6097 ** is being used to write to the source database when sqlite3_backup_step()
6098 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6099 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6100 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6101 ** [SQLITE_READONLY] is returned, then 
6102 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6103 ** errors are considered fatal.)^  The application must accept 
6104 ** that the backup operation has failed and pass the backup operation handle 
6105 ** to the sqlite3_backup_finish() to release associated resources.
6106 **
6107 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6108 ** on the destination file. ^The exclusive lock is not released until either 
6109 ** sqlite3_backup_finish() is called or the backup operation is complete 
6110 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6111 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6112 ** lasts for the duration of the sqlite3_backup_step() call.
6113 ** ^Because the source database is not locked between calls to
6114 ** sqlite3_backup_step(), the source database may be modified mid-way
6115 ** through the backup process.  ^If the source database is modified by an
6116 ** external process or via a database connection other than the one being
6117 ** used by the backup operation, then the backup will be automatically
6118 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6119 ** database is modified by the using the same database connection as is used
6120 ** by the backup operation, then the backup database is automatically
6121 ** updated at the same time.
6122 **
6123 ** <b>sqlite3_backup_finish()</b>
6124 **
6125 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6126 ** application wishes to abandon the backup operation, the application
6127 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6128 ** ^The sqlite3_backup_finish() interfaces releases all
6129 ** resources associated with the [sqlite3_backup] object. 
6130 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6131 ** active write-transaction on the destination database is rolled back.
6132 ** The [sqlite3_backup] object is invalid
6133 ** and may not be used following a call to sqlite3_backup_finish().
6134 **
6135 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6136 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6137 ** sqlite3_backup_step() completed.
6138 ** ^If an out-of-memory condition or IO error occurred during any prior
6139 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6140 ** sqlite3_backup_finish() returns the corresponding [error code].
6141 **
6142 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6143 ** is not a permanent error and does not affect the return value of
6144 ** sqlite3_backup_finish().
6145 **
6146 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6147 **
6148 ** ^Each call to sqlite3_backup_step() sets two values inside
6149 ** the [sqlite3_backup] object: the number of pages still to be backed
6150 ** up and the total number of pages in the source databae file.
6151 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6152 ** retrieve these two values, respectively.
6153 **
6154 ** ^The values returned by these functions are only updated by
6155 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6156 ** operation, then the values are not updated to account for any extra
6157 ** pages that need to be updated or the size of the source database file
6158 ** changing.
6159 **
6160 ** <b>Concurrent Usage of Database Handles</b>
6161 **
6162 ** ^The source [database connection] may be used by the application for other
6163 ** purposes while a backup operation is underway or being initialized.
6164 ** ^If SQLite is compiled and configured to support threadsafe database
6165 ** connections, then the source database connection may be used concurrently
6166 ** from within other threads.
6167 **
6168 ** However, the application must guarantee that the destination 
6169 ** [database connection] is not passed to any other API (by any thread) after 
6170 ** sqlite3_backup_init() is called and before the corresponding call to
6171 ** sqlite3_backup_finish().  SQLite does not currently check to see
6172 ** if the application incorrectly accesses the destination [database connection]
6173 ** and so no error code is reported, but the operations may malfunction
6174 ** nevertheless.  Use of the destination database connection while a
6175 ** backup is in progress might also also cause a mutex deadlock.
6176 **
6177 ** If running in [shared cache mode], the application must
6178 ** guarantee that the shared cache used by the destination database
6179 ** is not accessed while the backup is running. In practice this means
6180 ** that the application must guarantee that the disk file being 
6181 ** backed up to is not accessed by any connection within the process,
6182 ** not just the specific connection that was passed to sqlite3_backup_init().
6183 **
6184 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6185 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6186 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6187 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6188 ** same time as another thread is invoking sqlite3_backup_step() it is
6189 ** possible that they return invalid values.
6190 */
6191 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6192   sqlite3 *pDest,                        /* Destination database handle */
6193   const char *zDestName,                 /* Destination database name */
6194   sqlite3 *pSource,                      /* Source database handle */
6195   const char *zSourceName                /* Source database name */
6196 );
6197 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6198 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6199 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6200 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6201
6202 /*
6203 ** CAPI3REF: Unlock Notification
6204 **
6205 ** ^When running in shared-cache mode, a database operation may fail with
6206 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6207 ** individual tables within the shared-cache cannot be obtained. See
6208 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6209 ** ^This API may be used to register a callback that SQLite will invoke 
6210 ** when the connection currently holding the required lock relinquishes it.
6211 ** ^This API is only available if the library was compiled with the
6212 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6213 **
6214 ** See Also: [Using the SQLite Unlock Notification Feature].
6215 **
6216 ** ^Shared-cache locks are released when a database connection concludes
6217 ** its current transaction, either by committing it or rolling it back. 
6218 **
6219 ** ^When a connection (known as the blocked connection) fails to obtain a
6220 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6221 ** identity of the database connection (the blocking connection) that
6222 ** has locked the required resource is stored internally. ^After an 
6223 ** application receives an SQLITE_LOCKED error, it may call the
6224 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6225 ** the first argument to register for a callback that will be invoked
6226 ** when the blocking connections current transaction is concluded. ^The
6227 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6228 ** call that concludes the blocking connections transaction.
6229 **
6230 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6231 ** there is a chance that the blocking connection will have already
6232 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6233 ** If this happens, then the specified callback is invoked immediately,
6234 ** from within the call to sqlite3_unlock_notify().)^
6235 **
6236 ** ^If the blocked connection is attempting to obtain a write-lock on a
6237 ** shared-cache table, and more than one other connection currently holds
6238 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6239 ** the other connections to use as the blocking connection.
6240 **
6241 ** ^(There may be at most one unlock-notify callback registered by a 
6242 ** blocked connection. If sqlite3_unlock_notify() is called when the
6243 ** blocked connection already has a registered unlock-notify callback,
6244 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6245 ** called with a NULL pointer as its second argument, then any existing
6246 ** unlock-notify callback is cancelled. ^The blocked connections 
6247 ** unlock-notify callback may also be canceled by closing the blocked
6248 ** connection using [sqlite3_close()].
6249 **
6250 ** The unlock-notify callback is not reentrant. If an application invokes
6251 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6252 ** crash or deadlock may be the result.
6253 **
6254 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6255 ** returns SQLITE_OK.
6256 **
6257 ** <b>Callback Invocation Details</b>
6258 **
6259 ** When an unlock-notify callback is registered, the application provides a 
6260 ** single void* pointer that is passed to the callback when it is invoked.
6261 ** However, the signature of the callback function allows SQLite to pass
6262 ** it an array of void* context pointers. The first argument passed to
6263 ** an unlock-notify callback is a pointer to an array of void* pointers,
6264 ** and the second is the number of entries in the array.
6265 **
6266 ** When a blocking connections transaction is concluded, there may be
6267 ** more than one blocked connection that has registered for an unlock-notify
6268 ** callback. ^If two or more such blocked connections have specified the
6269 ** same callback function, then instead of invoking the callback function
6270 ** multiple times, it is invoked once with the set of void* context pointers
6271 ** specified by the blocked connections bundled together into an array.
6272 ** This gives the application an opportunity to prioritize any actions 
6273 ** related to the set of unblocked database connections.
6274 **
6275 ** <b>Deadlock Detection</b>
6276 **
6277 ** Assuming that after registering for an unlock-notify callback a 
6278 ** database waits for the callback to be issued before taking any further
6279 ** action (a reasonable assumption), then using this API may cause the
6280 ** application to deadlock. For example, if connection X is waiting for
6281 ** connection Y's transaction to be concluded, and similarly connection
6282 ** Y is waiting on connection X's transaction, then neither connection
6283 ** will proceed and the system may remain deadlocked indefinitely.
6284 **
6285 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6286 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6287 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6288 ** unlock-notify callback is registered. The system is said to be in
6289 ** a deadlocked state if connection A has registered for an unlock-notify
6290 ** callback on the conclusion of connection B's transaction, and connection
6291 ** B has itself registered for an unlock-notify callback when connection
6292 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6293 ** the system is also considered to be deadlocked if connection B has
6294 ** registered for an unlock-notify callback on the conclusion of connection
6295 ** C's transaction, where connection C is waiting on connection A. ^Any
6296 ** number of levels of indirection are allowed.
6297 **
6298 ** <b>The "DROP TABLE" Exception</b>
6299 **
6300 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6301 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6302 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6303 ** SQLite checks if there are any currently executing SELECT statements
6304 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6305 ** returned. In this case there is no "blocking connection", so invoking
6306 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6307 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6308 ** or "DROP INDEX" query, an infinite loop might be the result.
6309 **
6310 ** One way around this problem is to check the extended error code returned
6311 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6312 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6313 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6314 ** SQLITE_LOCKED.)^
6315 */
6316 SQLITE_API int sqlite3_unlock_notify(
6317   sqlite3 *pBlocked,                          /* Waiting connection */
6318   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6319   void *pNotifyArg                            /* Argument to pass to xNotify */
6320 );
6321
6322
6323 /*
6324 ** CAPI3REF: String Comparison
6325 **
6326 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6327 ** compare the contents of two buffers containing UTF-8 strings in a
6328 ** case-indendent fashion, using the same definition of case independence 
6329 ** that SQLite uses internally when comparing identifiers.
6330 */
6331 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6332
6333 /*
6334 ** CAPI3REF: Error Logging Interface
6335 **
6336 ** ^The [sqlite3_log()] interface writes a message into the error log
6337 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6338 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6339 ** used with [sqlite3_snprintf()] to generate the final output string.
6340 **
6341 ** The sqlite3_log() interface is intended for use by extensions such as
6342 ** virtual tables, collating functions, and SQL functions.  While there is
6343 ** nothing to prevent an application from calling sqlite3_log(), doing so
6344 ** is considered bad form.
6345 **
6346 ** The zFormat string must not be NULL.
6347 **
6348 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6349 ** will not use dynamically allocated memory.  The log message is stored in
6350 ** a fixed-length buffer on the stack.  If the log message is longer than
6351 ** a few hundred characters, it will be truncated to the length of the
6352 ** buffer.
6353 */
6354 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6355
6356 /*
6357 ** CAPI3REF: Write-Ahead Log Commit Hook
6358 **
6359 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6360 ** will be invoked each time a database connection commits data to a
6361 ** [write-ahead log] (i.e. whenever a transaction is committed in
6362 ** [journal_mode | journal_mode=WAL mode]). 
6363 **
6364 ** ^The callback is invoked by SQLite after the commit has taken place and 
6365 ** the associated write-lock on the database released, so the implementation 
6366 ** may read, write or [checkpoint] the database as required.
6367 **
6368 ** ^The first parameter passed to the callback function when it is invoked
6369 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6370 ** registering the callback. ^The second is a copy of the database handle.
6371 ** ^The third parameter is the name of the database that was written to -
6372 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6373 ** is the number of pages currently in the write-ahead log file,
6374 ** including those that were just committed.
6375 **
6376 ** The callback function should normally return [SQLITE_OK].  ^If an error
6377 ** code is returned, that error will propagate back up through the
6378 ** SQLite code base to cause the statement that provoked the callback
6379 ** to report an error, though the commit will have still occurred. If the
6380 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6381 ** that does not correspond to any valid SQLite error code, the results
6382 ** are undefined.
6383 **
6384 ** A single database handle may have at most a single write-ahead log callback 
6385 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6386 ** previously registered write-ahead log callback. ^Note that the
6387 ** [sqlite3_wal_autocheckpoint()] interface and the
6388 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6389 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6390 */
6391 SQLITE_API void *sqlite3_wal_hook(
6392   sqlite3*, 
6393   int(*)(void *,sqlite3*,const char*,int),
6394   void*
6395 );
6396
6397 /*
6398 ** CAPI3REF: Configure an auto-checkpoint
6399 **
6400 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6401 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6402 ** to automatically [checkpoint]
6403 ** after committing a transaction if there are N or
6404 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6405 ** a negative value as the nFrame parameter disables automatic
6406 ** checkpoints entirely.
6407 **
6408 ** ^The callback registered by this function replaces any existing callback
6409 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6410 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6411 ** configured by this function.
6412 **
6413 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6414 ** from SQL.
6415 **
6416 ** ^Every new [database connection] defaults to having the auto-checkpoint
6417 ** enabled with a threshold of 1000 pages.  The use of this interface
6418 ** is only necessary if the default setting is found to be suboptimal
6419 ** for a particular application.
6420 */
6421 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6422
6423 /*
6424 ** CAPI3REF: Checkpoint a database
6425 **
6426 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6427 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6428 ** empty string, then a checkpoint is run on all databases of
6429 ** connection D.  ^If the database connection D is not in
6430 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6431 **
6432 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6433 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6434 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6435 ** run whenever the WAL reaches a certain size threshold.
6436 */
6437 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6438
6439 /*
6440 ** Undo the hack that converts floating point types to integer for
6441 ** builds on processors without floating point support.
6442 */
6443 #ifdef SQLITE_OMIT_FLOATING_POINT
6444 # undef double
6445 #endif
6446
6447 #if 0
6448 }  /* End of the 'extern "C"' block */
6449 #endif
6450 #endif
6451
6452
6453 /************** End of sqlite3.h *********************************************/
6454 /************** Continuing where we left off in sqliteInt.h ******************/
6455 /************** Include hash.h in the middle of sqliteInt.h ******************/
6456 /************** Begin file hash.h ********************************************/
6457 /*
6458 ** 2001 September 22
6459 **
6460 ** The author disclaims copyright to this source code.  In place of
6461 ** a legal notice, here is a blessing:
6462 **
6463 **    May you do good and not evil.
6464 **    May you find forgiveness for yourself and forgive others.
6465 **    May you share freely, never taking more than you give.
6466 **
6467 *************************************************************************
6468 ** This is the header file for the generic hash-table implemenation
6469 ** used in SQLite.
6470 */
6471 #ifndef _SQLITE_HASH_H_
6472 #define _SQLITE_HASH_H_
6473
6474 /* Forward declarations of structures. */
6475 typedef struct Hash Hash;
6476 typedef struct HashElem HashElem;
6477
6478 /* A complete hash table is an instance of the following structure.
6479 ** The internals of this structure are intended to be opaque -- client
6480 ** code should not attempt to access or modify the fields of this structure
6481 ** directly.  Change this structure only by using the routines below.
6482 ** However, some of the "procedures" and "functions" for modifying and
6483 ** accessing this structure are really macros, so we can't really make
6484 ** this structure opaque.
6485 **
6486 ** All elements of the hash table are on a single doubly-linked list.
6487 ** Hash.first points to the head of this list.
6488 **
6489 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6490 ** the global doubly-linked list.  The contents of the bucket are the
6491 ** element pointed to plus the next _ht.count-1 elements in the list.
6492 **
6493 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6494 ** by a linear search of the global list.  For small tables, the 
6495 ** Hash.ht table is never allocated because if there are few elements
6496 ** in the table, it is faster to do a linear search than to manage
6497 ** the hash table.
6498 */
6499 struct Hash {
6500   unsigned int htsize;      /* Number of buckets in the hash table */
6501   unsigned int count;       /* Number of entries in this table */
6502   HashElem *first;          /* The first element of the array */
6503   struct _ht {              /* the hash table */
6504     int count;                 /* Number of entries with this hash */
6505     HashElem *chain;           /* Pointer to first entry with this hash */
6506   } *ht;
6507 };
6508
6509 /* Each element in the hash table is an instance of the following 
6510 ** structure.  All elements are stored on a single doubly-linked list.
6511 **
6512 ** Again, this structure is intended to be opaque, but it can't really
6513 ** be opaque because it is used by macros.
6514 */
6515 struct HashElem {
6516   HashElem *next, *prev;       /* Next and previous elements in the table */
6517   void *data;                  /* Data associated with this element */
6518   const char *pKey; int nKey;  /* Key associated with this element */
6519 };
6520
6521 /*
6522 ** Access routines.  To delete, insert a NULL pointer.
6523 */
6524 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6525 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6526 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6527 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6528
6529 /*
6530 ** Macros for looping over all elements of a hash table.  The idiom is
6531 ** like this:
6532 **
6533 **   Hash h;
6534 **   HashElem *p;
6535 **   ...
6536 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6537 **     SomeStructure *pData = sqliteHashData(p);
6538 **     // do something with pData
6539 **   }
6540 */
6541 #define sqliteHashFirst(H)  ((H)->first)
6542 #define sqliteHashNext(E)   ((E)->next)
6543 #define sqliteHashData(E)   ((E)->data)
6544 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6545 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6546
6547 /*
6548 ** Number of entries in a hash table
6549 */
6550 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6551
6552 #endif /* _SQLITE_HASH_H_ */
6553
6554 /************** End of hash.h ************************************************/
6555 /************** Continuing where we left off in sqliteInt.h ******************/
6556 /************** Include parse.h in the middle of sqliteInt.h *****************/
6557 /************** Begin file parse.h *******************************************/
6558 #define TK_SEMI                            1
6559 #define TK_EXPLAIN                         2
6560 #define TK_QUERY                           3
6561 #define TK_PLAN                            4
6562 #define TK_BEGIN                           5
6563 #define TK_TRANSACTION                     6
6564 #define TK_DEFERRED                        7
6565 #define TK_IMMEDIATE                       8
6566 #define TK_EXCLUSIVE                       9
6567 #define TK_COMMIT                         10
6568 #define TK_END                            11
6569 #define TK_ROLLBACK                       12
6570 #define TK_SAVEPOINT                      13
6571 #define TK_RELEASE                        14
6572 #define TK_TO                             15
6573 #define TK_TABLE                          16
6574 #define TK_CREATE                         17
6575 #define TK_IF                             18
6576 #define TK_NOT                            19
6577 #define TK_EXISTS                         20
6578 #define TK_TEMP                           21
6579 #define TK_LP                             22
6580 #define TK_RP                             23
6581 #define TK_AS                             24
6582 #define TK_COMMA                          25
6583 #define TK_ID                             26
6584 #define TK_INDEXED                        27
6585 #define TK_ABORT                          28
6586 #define TK_ACTION                         29
6587 #define TK_AFTER                          30
6588 #define TK_ANALYZE                        31
6589 #define TK_ASC                            32
6590 #define TK_ATTACH                         33
6591 #define TK_BEFORE                         34
6592 #define TK_BY                             35
6593 #define TK_CASCADE                        36
6594 #define TK_CAST                           37
6595 #define TK_COLUMNKW                       38
6596 #define TK_CONFLICT                       39
6597 #define TK_DATABASE                       40
6598 #define TK_DESC                           41
6599 #define TK_DETACH                         42
6600 #define TK_EACH                           43
6601 #define TK_FAIL                           44
6602 #define TK_FOR                            45
6603 #define TK_IGNORE                         46
6604 #define TK_INITIALLY                      47
6605 #define TK_INSTEAD                        48
6606 #define TK_LIKE_KW                        49
6607 #define TK_MATCH                          50
6608 #define TK_NO                             51
6609 #define TK_KEY                            52
6610 #define TK_OF                             53
6611 #define TK_OFFSET                         54
6612 #define TK_PRAGMA                         55
6613 #define TK_RAISE                          56
6614 #define TK_REPLACE                        57
6615 #define TK_RESTRICT                       58
6616 #define TK_ROW                            59
6617 #define TK_TRIGGER                        60
6618 #define TK_VACUUM                         61
6619 #define TK_VIEW                           62
6620 #define TK_VIRTUAL                        63
6621 #define TK_REINDEX                        64
6622 #define TK_RENAME                         65
6623 #define TK_CTIME_KW                       66
6624 #define TK_ANY                            67
6625 #define TK_OR                             68
6626 #define TK_AND                            69
6627 #define TK_IS                             70
6628 #define TK_BETWEEN                        71
6629 #define TK_IN                             72
6630 #define TK_ISNULL                         73
6631 #define TK_NOTNULL                        74
6632 #define TK_NE                             75
6633 #define TK_EQ                             76
6634 #define TK_GT                             77
6635 #define TK_LE                             78
6636 #define TK_LT                             79
6637 #define TK_GE                             80
6638 #define TK_ESCAPE                         81
6639 #define TK_BITAND                         82
6640 #define TK_BITOR                          83
6641 #define TK_LSHIFT                         84
6642 #define TK_RSHIFT                         85
6643 #define TK_PLUS                           86
6644 #define TK_MINUS                          87
6645 #define TK_STAR                           88
6646 #define TK_SLASH                          89
6647 #define TK_REM                            90
6648 #define TK_CONCAT                         91
6649 #define TK_COLLATE                        92
6650 #define TK_BITNOT                         93
6651 #define TK_STRING                         94
6652 #define TK_JOIN_KW                        95
6653 #define TK_CONSTRAINT                     96
6654 #define TK_DEFAULT                        97
6655 #define TK_NULL                           98
6656 #define TK_PRIMARY                        99
6657 #define TK_UNIQUE                         100
6658 #define TK_CHECK                          101
6659 #define TK_REFERENCES                     102
6660 #define TK_AUTOINCR                       103
6661 #define TK_ON                             104
6662 #define TK_INSERT                         105
6663 #define TK_DELETE                         106
6664 #define TK_UPDATE                         107
6665 #define TK_SET                            108
6666 #define TK_DEFERRABLE                     109
6667 #define TK_FOREIGN                        110
6668 #define TK_DROP                           111
6669 #define TK_UNION                          112
6670 #define TK_ALL                            113
6671 #define TK_EXCEPT                         114
6672 #define TK_INTERSECT                      115
6673 #define TK_SELECT                         116
6674 #define TK_DISTINCT                       117
6675 #define TK_DOT                            118
6676 #define TK_FROM                           119
6677 #define TK_JOIN                           120
6678 #define TK_USING                          121
6679 #define TK_ORDER                          122
6680 #define TK_GROUP                          123
6681 #define TK_HAVING                         124
6682 #define TK_LIMIT                          125
6683 #define TK_WHERE                          126
6684 #define TK_INTO                           127
6685 #define TK_VALUES                         128
6686 #define TK_INTEGER                        129
6687 #define TK_FLOAT                          130
6688 #define TK_BLOB                           131
6689 #define TK_REGISTER                       132
6690 #define TK_VARIABLE                       133
6691 #define TK_CASE                           134
6692 #define TK_WHEN                           135
6693 #define TK_THEN                           136
6694 #define TK_ELSE                           137
6695 #define TK_INDEX                          138
6696 #define TK_ALTER                          139
6697 #define TK_ADD                            140
6698 #define TK_TO_TEXT                        141
6699 #define TK_TO_BLOB                        142
6700 #define TK_TO_NUMERIC                     143
6701 #define TK_TO_INT                         144
6702 #define TK_TO_REAL                        145
6703 #define TK_ISNOT                          146
6704 #define TK_END_OF_FILE                    147
6705 #define TK_ILLEGAL                        148
6706 #define TK_SPACE                          149
6707 #define TK_UNCLOSED_STRING                150
6708 #define TK_FUNCTION                       151
6709 #define TK_COLUMN                         152
6710 #define TK_AGG_FUNCTION                   153
6711 #define TK_AGG_COLUMN                     154
6712 #define TK_CONST_FUNC                     155
6713 #define TK_UMINUS                         156
6714 #define TK_UPLUS                          157
6715
6716 /************** End of parse.h ***********************************************/
6717 /************** Continuing where we left off in sqliteInt.h ******************/
6718 #include <stdio.h>
6719 #include <stdlib.h>
6720 #include <string.h>
6721 #include <assert.h>
6722 #include <stddef.h>
6723
6724 /*
6725 ** If compiling for a processor that lacks floating point support,
6726 ** substitute integer for floating-point
6727 */
6728 #ifdef SQLITE_OMIT_FLOATING_POINT
6729 # define double sqlite_int64
6730 # define float sqlite_int64
6731 # define LONGDOUBLE_TYPE sqlite_int64
6732 # ifndef SQLITE_BIG_DBL
6733 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6734 # endif
6735 # define SQLITE_OMIT_DATETIME_FUNCS 1
6736 # define SQLITE_OMIT_TRACE 1
6737 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6738 # undef SQLITE_HAVE_ISNAN
6739 #endif
6740 #ifndef SQLITE_BIG_DBL
6741 # define SQLITE_BIG_DBL (1e99)
6742 #endif
6743
6744 /*
6745 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6746 ** afterward. Having this macro allows us to cause the C compiler 
6747 ** to omit code used by TEMP tables without messy #ifndef statements.
6748 */
6749 #ifdef SQLITE_OMIT_TEMPDB
6750 #define OMIT_TEMPDB 1
6751 #else
6752 #define OMIT_TEMPDB 0
6753 #endif
6754
6755 /*
6756 ** The "file format" number is an integer that is incremented whenever
6757 ** the VDBE-level file format changes.  The following macros define the
6758 ** the default file format for new databases and the maximum file format
6759 ** that the library can read.
6760 */
6761 #define SQLITE_MAX_FILE_FORMAT 4
6762 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6763 # define SQLITE_DEFAULT_FILE_FORMAT 1
6764 #endif
6765
6766 /*
6767 ** Determine whether triggers are recursive by default.  This can be
6768 ** changed at run-time using a pragma.
6769 */
6770 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6771 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6772 #endif
6773
6774 /*
6775 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6776 ** on the command-line
6777 */
6778 #ifndef SQLITE_TEMP_STORE
6779 # define SQLITE_TEMP_STORE 1
6780 #endif
6781
6782 /*
6783 ** GCC does not define the offsetof() macro so we'll have to do it
6784 ** ourselves.
6785 */
6786 #ifndef offsetof
6787 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6788 #endif
6789
6790 /*
6791 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6792 ** not, there are still machines out there that use EBCDIC.)
6793 */
6794 #if 'A' == '\301'
6795 # define SQLITE_EBCDIC 1
6796 #else
6797 # define SQLITE_ASCII 1
6798 #endif
6799
6800 /*
6801 ** Integers of known sizes.  These typedefs might change for architectures
6802 ** where the sizes very.  Preprocessor macros are available so that the
6803 ** types can be conveniently redefined at compile-type.  Like this:
6804 **
6805 **         cc '-DUINTPTR_TYPE=long long int' ...
6806 */
6807 #ifndef UINT32_TYPE
6808 # ifdef HAVE_UINT32_T
6809 #  define UINT32_TYPE uint32_t
6810 # else
6811 #  define UINT32_TYPE unsigned int
6812 # endif
6813 #endif
6814 #ifndef UINT16_TYPE
6815 # ifdef HAVE_UINT16_T
6816 #  define UINT16_TYPE uint16_t
6817 # else
6818 #  define UINT16_TYPE unsigned short int
6819 # endif
6820 #endif
6821 #ifndef INT16_TYPE
6822 # ifdef HAVE_INT16_T
6823 #  define INT16_TYPE int16_t
6824 # else
6825 #  define INT16_TYPE short int
6826 # endif
6827 #endif
6828 #ifndef UINT8_TYPE
6829 # ifdef HAVE_UINT8_T
6830 #  define UINT8_TYPE uint8_t
6831 # else
6832 #  define UINT8_TYPE unsigned char
6833 # endif
6834 #endif
6835 #ifndef INT8_TYPE
6836 # ifdef HAVE_INT8_T
6837 #  define INT8_TYPE int8_t
6838 # else
6839 #  define INT8_TYPE signed char
6840 # endif
6841 #endif
6842 #ifndef LONGDOUBLE_TYPE
6843 # define LONGDOUBLE_TYPE long double
6844 #endif
6845 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6846 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6847 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6848 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6849 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6850 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6851 typedef INT8_TYPE i8;              /* 1-byte signed integer */
6852
6853 /*
6854 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6855 ** that can be stored in a u32 without loss of data.  The value
6856 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6857 ** have to specify the value in the less intuitive manner shown:
6858 */
6859 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6860
6861 /*
6862 ** Macros to determine whether the machine is big or little endian,
6863 ** evaluated at runtime.
6864 */
6865 #ifdef SQLITE_AMALGAMATION
6866 SQLITE_PRIVATE const int sqlite3one = 1;
6867 #else
6868 SQLITE_PRIVATE const int sqlite3one;
6869 #endif
6870 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6871                              || defined(__x86_64) || defined(__x86_64__)
6872 # define SQLITE_BIGENDIAN    0
6873 # define SQLITE_LITTLEENDIAN 1
6874 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6875 #else
6876 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6877 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6878 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6879 #endif
6880
6881 /*
6882 ** Constants for the largest and smallest possible 64-bit signed integers.
6883 ** These macros are designed to work correctly on both 32-bit and 64-bit
6884 ** compilers.
6885 */
6886 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6887 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6888
6889 /* 
6890 ** Round up a number to the next larger multiple of 8.  This is used
6891 ** to force 8-byte alignment on 64-bit architectures.
6892 */
6893 #define ROUND8(x)     (((x)+7)&~7)
6894
6895 /*
6896 ** Round down to the nearest multiple of 8
6897 */
6898 #define ROUNDDOWN8(x) ((x)&~7)
6899
6900 /*
6901 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
6902 ** macro is used only within assert() to verify that the code gets
6903 ** all alignment restrictions correct.
6904 **
6905 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6906 ** underlying malloc() implemention might return us 4-byte aligned
6907 ** pointers.  In that case, only verify 4-byte alignment.
6908 */
6909 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6910 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6911 #else
6912 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6913 #endif
6914
6915
6916 /*
6917 ** An instance of the following structure is used to store the busy-handler
6918 ** callback for a given sqlite handle. 
6919 **
6920 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6921 ** callback for the database handle. Each pager opened via the sqlite
6922 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6923 ** callback is currently invoked only from within pager.c.
6924 */
6925 typedef struct BusyHandler BusyHandler;
6926 struct BusyHandler {
6927   int (*xFunc)(void *,int);  /* The busy callback */
6928   void *pArg;                /* First arg to busy callback */
6929   int nBusy;                 /* Incremented with each busy call */
6930 };
6931
6932 /*
6933 ** Name of the master database table.  The master database table
6934 ** is a special table that holds the names and attributes of all
6935 ** user tables and indices.
6936 */
6937 #define MASTER_NAME       "sqlite_master"
6938 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6939
6940 /*
6941 ** The root-page of the master database table.
6942 */
6943 #define MASTER_ROOT       1
6944
6945 /*
6946 ** The name of the schema table.
6947 */
6948 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6949
6950 /*
6951 ** A convenience macro that returns the number of elements in
6952 ** an array.
6953 */
6954 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6955
6956 /*
6957 ** The following value as a destructor means to use sqlite3DbFree().
6958 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6959 */
6960 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6961
6962 /*
6963 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6964 ** not support Writable Static Data (WSD) such as global and static variables.
6965 ** All variables must either be on the stack or dynamically allocated from
6966 ** the heap.  When WSD is unsupported, the variable declarations scattered
6967 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6968 ** macro is used for this purpose.  And instead of referencing the variable
6969 ** directly, we use its constant as a key to lookup the run-time allocated
6970 ** buffer that holds real variable.  The constant is also the initializer
6971 ** for the run-time allocated buffer.
6972 **
6973 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6974 ** macros become no-ops and have zero performance impact.
6975 */
6976 #ifdef SQLITE_OMIT_WSD
6977   #define SQLITE_WSD const
6978   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6979   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6980 SQLITE_API   int sqlite3_wsd_init(int N, int J);
6981 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6982 #else
6983   #define SQLITE_WSD 
6984   #define GLOBAL(t,v) v
6985   #define sqlite3GlobalConfig sqlite3Config
6986 #endif
6987
6988 /*
6989 ** The following macros are used to suppress compiler warnings and to
6990 ** make it clear to human readers when a function parameter is deliberately 
6991 ** left unused within the body of a function. This usually happens when
6992 ** a function is called via a function pointer. For example the 
6993 ** implementation of an SQL aggregate step callback may not use the
6994 ** parameter indicating the number of arguments passed to the aggregate,
6995 ** if it knows that this is enforced elsewhere.
6996 **
6997 ** When a function parameter is not used at all within the body of a function,
6998 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6999 ** However, these macros may also be used to suppress warnings related to
7000 ** parameters that may or may not be used depending on compilation options.
7001 ** For example those parameters only used in assert() statements. In these
7002 ** cases the parameters are named as per the usual conventions.
7003 */
7004 #define UNUSED_PARAMETER(x) (void)(x)
7005 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7006
7007 /*
7008 ** Forward references to structures
7009 */
7010 typedef struct AggInfo AggInfo;
7011 typedef struct AuthContext AuthContext;
7012 typedef struct AutoincInfo AutoincInfo;
7013 typedef struct Bitvec Bitvec;
7014 typedef struct CollSeq CollSeq;
7015 typedef struct Column Column;
7016 typedef struct Db Db;
7017 typedef struct Schema Schema;
7018 typedef struct Expr Expr;
7019 typedef struct ExprList ExprList;
7020 typedef struct ExprSpan ExprSpan;
7021 typedef struct FKey FKey;
7022 typedef struct FuncDef FuncDef;
7023 typedef struct FuncDefHash FuncDefHash;
7024 typedef struct IdList IdList;
7025 typedef struct Index Index;
7026 typedef struct IndexSample IndexSample;
7027 typedef struct KeyClass KeyClass;
7028 typedef struct KeyInfo KeyInfo;
7029 typedef struct Lookaside Lookaside;
7030 typedef struct LookasideSlot LookasideSlot;
7031 typedef struct Module Module;
7032 typedef struct NameContext NameContext;
7033 typedef struct Parse Parse;
7034 typedef struct RowSet RowSet;
7035 typedef struct Savepoint Savepoint;
7036 typedef struct Select Select;
7037 typedef struct SrcList SrcList;
7038 typedef struct StrAccum StrAccum;
7039 typedef struct Table Table;
7040 typedef struct TableLock TableLock;
7041 typedef struct Token Token;
7042 typedef struct Trigger Trigger;
7043 typedef struct TriggerPrg TriggerPrg;
7044 typedef struct TriggerStep TriggerStep;
7045 typedef struct UnpackedRecord UnpackedRecord;
7046 typedef struct VTable VTable;
7047 typedef struct Walker Walker;
7048 typedef struct WherePlan WherePlan;
7049 typedef struct WhereInfo WhereInfo;
7050 typedef struct WhereLevel WhereLevel;
7051
7052 /*
7053 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7054 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7055 ** pointer types (i.e. FuncDef) defined above.
7056 */
7057 /************** Include btree.h in the middle of sqliteInt.h *****************/
7058 /************** Begin file btree.h *******************************************/
7059 /*
7060 ** 2001 September 15
7061 **
7062 ** The author disclaims copyright to this source code.  In place of
7063 ** a legal notice, here is a blessing:
7064 **
7065 **    May you do good and not evil.
7066 **    May you find forgiveness for yourself and forgive others.
7067 **    May you share freely, never taking more than you give.
7068 **
7069 *************************************************************************
7070 ** This header file defines the interface that the sqlite B-Tree file
7071 ** subsystem.  See comments in the source code for a detailed description
7072 ** of what each interface routine does.
7073 */
7074 #ifndef _BTREE_H_
7075 #define _BTREE_H_
7076
7077 /* TODO: This definition is just included so other modules compile. It
7078 ** needs to be revisited.
7079 */
7080 #define SQLITE_N_BTREE_META 10
7081
7082 /*
7083 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7084 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7085 */
7086 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7087   #define SQLITE_DEFAULT_AUTOVACUUM 0
7088 #endif
7089
7090 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7091 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7092 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7093
7094 /*
7095 ** Forward declarations of structure
7096 */
7097 typedef struct Btree Btree;
7098 typedef struct BtCursor BtCursor;
7099 typedef struct BtShared BtShared;
7100 typedef struct BtreeMutexArray BtreeMutexArray;
7101
7102 /*
7103 ** This structure records all of the Btrees that need to hold
7104 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7105 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7106 ** we can always lock and unlock them all quickly.
7107 */
7108 struct BtreeMutexArray {
7109   int nMutex;
7110   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7111 };
7112
7113
7114 SQLITE_PRIVATE int sqlite3BtreeOpen(
7115   const char *zFilename,   /* Name of database file to open */
7116   sqlite3 *db,             /* Associated database connection */
7117   Btree **ppBtree,         /* Return open Btree* here */
7118   int flags,               /* Flags */
7119   int vfsFlags             /* Flags passed through to VFS open */
7120 );
7121
7122 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7123 ** following values.
7124 **
7125 ** NOTE:  These values must match the corresponding PAGER_ values in
7126 ** pager.h.
7127 */
7128 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7129 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7130 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7131 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7132 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7133 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7134
7135 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7136 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7137 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7138 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7139 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7140 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7141 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7142 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7143 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7144 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7145 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7146 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7147 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7148 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7149 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7150 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7151 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7152 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7153 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7154 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7155 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7156 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7157 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7158 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7159 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7160 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7161
7162 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7163 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7164 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7165
7166 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7167
7168 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7169 ** of the following flags:
7170 */
7171 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7172 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7173 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7174
7175 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7176 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7177 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7178
7179 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7180 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7181
7182 /*
7183 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7184 ** should be one of the following values. The integer values are assigned 
7185 ** to constants so that the offset of the corresponding field in an
7186 ** SQLite database header may be found using the following formula:
7187 **
7188 **   offset = 36 + (idx * 4)
7189 **
7190 ** For example, the free-page-count field is located at byte offset 36 of
7191 ** the database file header. The incr-vacuum-flag field is located at
7192 ** byte offset 64 (== 36+4*7).
7193 */
7194 #define BTREE_FREE_PAGE_COUNT     0
7195 #define BTREE_SCHEMA_VERSION      1
7196 #define BTREE_FILE_FORMAT         2
7197 #define BTREE_DEFAULT_CACHE_SIZE  3
7198 #define BTREE_LARGEST_ROOT_PAGE   4
7199 #define BTREE_TEXT_ENCODING       5
7200 #define BTREE_USER_VERSION        6
7201 #define BTREE_INCR_VACUUM         7
7202
7203 SQLITE_PRIVATE int sqlite3BtreeCursor(
7204   Btree*,                              /* BTree containing table to open */
7205   int iTable,                          /* Index of root page */
7206   int wrFlag,                          /* 1 for writing.  0 for read-only */
7207   struct KeyInfo*,                     /* First argument to compare function */
7208   BtCursor *pCursor                    /* Space to write cursor structure */
7209 );
7210 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7211 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7212
7213 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7214 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7215   BtCursor*,
7216   UnpackedRecord *pUnKey,
7217   i64 intKey,
7218   int bias,
7219   int *pRes
7220 );
7221 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7222 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7223 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7224                                   const void *pData, int nData,
7225                                   int nZero, int bias, int seekResult);
7226 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7227 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7228 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7229 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7230 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7231 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7232 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7233 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7234 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7235 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7236 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7237 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7238 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7239
7240 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7241 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7242
7243 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7244 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7245 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7246
7247 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7248
7249 #ifndef NDEBUG
7250 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7251 #endif
7252
7253 #ifndef SQLITE_OMIT_BTREECOUNT
7254 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7255 #endif
7256
7257 #ifdef SQLITE_TEST
7258 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7259 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7260 #endif
7261
7262 /*
7263 ** If we are not using shared cache, then there is no need to
7264 ** use mutexes to access the BtShared structures.  So make the
7265 ** Enter and Leave procedures no-ops.
7266 */
7267 #ifndef SQLITE_OMIT_SHARED_CACHE
7268 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7269 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7270 #else
7271 # define sqlite3BtreeEnter(X) 
7272 # define sqlite3BtreeEnterAll(X)
7273 #endif
7274
7275 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7276 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7277 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7278 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7279 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7280 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7281 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7282 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7283 #ifndef NDEBUG
7284   /* These routines are used inside assert() statements only. */
7285 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7286 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7287 #endif
7288 #else
7289
7290 # define sqlite3BtreeLeave(X)
7291 # define sqlite3BtreeEnterCursor(X)
7292 # define sqlite3BtreeLeaveCursor(X)
7293 # define sqlite3BtreeLeaveAll(X)
7294 # define sqlite3BtreeMutexArrayEnter(X)
7295 # define sqlite3BtreeMutexArrayLeave(X)
7296 # define sqlite3BtreeMutexArrayInsert(X,Y)
7297
7298 # define sqlite3BtreeHoldsMutex(X) 1
7299 # define sqlite3BtreeHoldsAllMutexes(X) 1
7300 #endif
7301
7302
7303 #endif /* _BTREE_H_ */
7304
7305 /************** End of btree.h ***********************************************/
7306 /************** Continuing where we left off in sqliteInt.h ******************/
7307 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7308 /************** Begin file vdbe.h ********************************************/
7309 /*
7310 ** 2001 September 15
7311 **
7312 ** The author disclaims copyright to this source code.  In place of
7313 ** a legal notice, here is a blessing:
7314 **
7315 **    May you do good and not evil.
7316 **    May you find forgiveness for yourself and forgive others.
7317 **    May you share freely, never taking more than you give.
7318 **
7319 *************************************************************************
7320 ** Header file for the Virtual DataBase Engine (VDBE)
7321 **
7322 ** This header defines the interface to the virtual database engine
7323 ** or VDBE.  The VDBE implements an abstract machine that runs a
7324 ** simple program to access and modify the underlying database.
7325 */
7326 #ifndef _SQLITE_VDBE_H_
7327 #define _SQLITE_VDBE_H_
7328
7329 /*
7330 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7331 ** in the source file sqliteVdbe.c are allowed to see the insides
7332 ** of this structure.
7333 */
7334 typedef struct Vdbe Vdbe;
7335
7336 /*
7337 ** The names of the following types declared in vdbeInt.h are required
7338 ** for the VdbeOp definition.
7339 */
7340 typedef struct VdbeFunc VdbeFunc;
7341 typedef struct Mem Mem;
7342 typedef struct SubProgram SubProgram;
7343
7344 /*
7345 ** A single instruction of the virtual machine has an opcode
7346 ** and as many as three operands.  The instruction is recorded
7347 ** as an instance of the following structure:
7348 */
7349 struct VdbeOp {
7350   u8 opcode;          /* What operation to perform */
7351   signed char p4type; /* One of the P4_xxx constants for p4 */
7352   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7353   u8 p5;              /* Fifth parameter is an unsigned character */
7354   int p1;             /* First operand */
7355   int p2;             /* Second parameter (often the jump destination) */
7356   int p3;             /* The third parameter */
7357   union {             /* fourth parameter */
7358     int i;                 /* Integer value if p4type==P4_INT32 */
7359     void *p;               /* Generic pointer */
7360     char *z;               /* Pointer to data for string (char array) types */
7361     i64 *pI64;             /* Used when p4type is P4_INT64 */
7362     double *pReal;         /* Used when p4type is P4_REAL */
7363     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7364     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7365     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7366     Mem *pMem;             /* Used when p4type is P4_MEM */
7367     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7368     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7369     int *ai;               /* Used when p4type is P4_INTARRAY */
7370     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7371   } p4;
7372 #ifdef SQLITE_DEBUG
7373   char *zComment;          /* Comment to improve readability */
7374 #endif
7375 #ifdef VDBE_PROFILE
7376   int cnt;                 /* Number of times this instruction was executed */
7377   u64 cycles;              /* Total time spent executing this instruction */
7378 #endif
7379 };
7380 typedef struct VdbeOp VdbeOp;
7381
7382
7383 /*
7384 ** A sub-routine used to implement a trigger program.
7385 */
7386 struct SubProgram {
7387   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7388   int nOp;                      /* Elements in aOp[] */
7389   int nMem;                     /* Number of memory cells required */
7390   int nCsr;                     /* Number of cursors required */
7391   int nRef;                     /* Number of pointers to this structure */
7392   void *token;                  /* id that may be used to recursive triggers */
7393 };
7394
7395 /*
7396 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7397 ** it takes up less space.
7398 */
7399 struct VdbeOpList {
7400   u8 opcode;          /* What operation to perform */
7401   signed char p1;     /* First operand */
7402   signed char p2;     /* Second parameter (often the jump destination) */
7403   signed char p3;     /* Third parameter */
7404 };
7405 typedef struct VdbeOpList VdbeOpList;
7406
7407 /*
7408 ** Allowed values of VdbeOp.p4type
7409 */
7410 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7411 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7412 #define P4_STATIC   (-2)  /* Pointer to a static string */
7413 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7414 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7415 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7416 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7417 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7418 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7419 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7420 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7421 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7422 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7423 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7424 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7425 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7426
7427 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7428 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7429 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7430 ** gets freed when the Vdbe is finalized so it still should be obtained
7431 ** from a single sqliteMalloc().  But no copy is made and the calling
7432 ** function should *not* try to free the KeyInfo.
7433 */
7434 #define P4_KEYINFO_HANDOFF (-16)
7435 #define P4_KEYINFO_STATIC  (-17)
7436
7437 /*
7438 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7439 ** number of columns of data returned by the statement.
7440 */
7441 #define COLNAME_NAME     0
7442 #define COLNAME_DECLTYPE 1
7443 #define COLNAME_DATABASE 2
7444 #define COLNAME_TABLE    3
7445 #define COLNAME_COLUMN   4
7446 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7447 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7448 #else
7449 # ifdef SQLITE_OMIT_DECLTYPE
7450 #   define COLNAME_N      1      /* Store only the name */
7451 # else
7452 #   define COLNAME_N      2      /* Store the name and decltype */
7453 # endif
7454 #endif
7455
7456 /*
7457 ** The following macro converts a relative address in the p2 field
7458 ** of a VdbeOp structure into a negative number so that 
7459 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7460 ** the macro again restores the address.
7461 */
7462 #define ADDR(X)  (-1-(X))
7463
7464 /*
7465 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7466 ** header file that defines a number for each opcode used by the VDBE.
7467 */
7468 /************** Include opcodes.h in the middle of vdbe.h ********************/
7469 /************** Begin file opcodes.h *****************************************/
7470 /* Automatically generated.  Do not edit */
7471 /* See the mkopcodeh.awk script for details */
7472 #define OP_Goto                                 1
7473 #define OP_Gosub                                2
7474 #define OP_Return                               3
7475 #define OP_Yield                                4
7476 #define OP_HaltIfNull                           5
7477 #define OP_Halt                                 6
7478 #define OP_Integer                              7
7479 #define OP_Int64                                8
7480 #define OP_Real                               130   /* same as TK_FLOAT    */
7481 #define OP_String8                             94   /* same as TK_STRING   */
7482 #define OP_String                               9
7483 #define OP_Null                                10
7484 #define OP_Blob                                11
7485 #define OP_Variable                            12
7486 #define OP_Move                                13
7487 #define OP_Copy                                14
7488 #define OP_SCopy                               15
7489 #define OP_ResultRow                           16
7490 #define OP_Concat                              91   /* same as TK_CONCAT   */
7491 #define OP_Add                                 86   /* same as TK_PLUS     */
7492 #define OP_Subtract                            87   /* same as TK_MINUS    */
7493 #define OP_Multiply                            88   /* same as TK_STAR     */
7494 #define OP_Divide                              89   /* same as TK_SLASH    */
7495 #define OP_Remainder                           90   /* same as TK_REM      */
7496 #define OP_CollSeq                             17
7497 #define OP_Function                            18
7498 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7499 #define OP_BitOr                               83   /* same as TK_BITOR    */
7500 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7501 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7502 #define OP_AddImm                              20
7503 #define OP_MustBeInt                           21
7504 #define OP_RealAffinity                        22
7505 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7506 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7507 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7508 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7509 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7510 #define OP_Eq                                  76   /* same as TK_EQ       */
7511 #define OP_Ne                                  75   /* same as TK_NE       */
7512 #define OP_Lt                                  79   /* same as TK_LT       */
7513 #define OP_Le                                  78   /* same as TK_LE       */
7514 #define OP_Gt                                  77   /* same as TK_GT       */
7515 #define OP_Ge                                  80   /* same as TK_GE       */
7516 #define OP_Permutation                         23
7517 #define OP_Compare                             24
7518 #define OP_Jump                                25
7519 #define OP_And                                 69   /* same as TK_AND      */
7520 #define OP_Or                                  68   /* same as TK_OR       */
7521 #define OP_Not                                 19   /* same as TK_NOT      */
7522 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7523 #define OP_If                                  26
7524 #define OP_IfNot                               27
7525 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7526 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7527 #define OP_Column                              28
7528 #define OP_Affinity                            29
7529 #define OP_MakeRecord                          30
7530 #define OP_Count                               31
7531 #define OP_Savepoint                           32
7532 #define OP_AutoCommit                          33
7533 #define OP_Transaction                         34
7534 #define OP_ReadCookie                          35
7535 #define OP_SetCookie                           36
7536 #define OP_VerifyCookie                        37
7537 #define OP_OpenRead                            38
7538 #define OP_OpenWrite                           39
7539 #define OP_OpenAutoindex                       40
7540 #define OP_OpenEphemeral                       41
7541 #define OP_OpenPseudo                          42
7542 #define OP_Close                               43
7543 #define OP_SeekLt                              44
7544 #define OP_SeekLe                              45
7545 #define OP_SeekGe                              46
7546 #define OP_SeekGt                              47
7547 #define OP_Seek                                48
7548 #define OP_NotFound                            49
7549 #define OP_Found                               50
7550 #define OP_IsUnique                            51
7551 #define OP_NotExists                           52
7552 #define OP_Sequence                            53
7553 #define OP_NewRowid                            54
7554 #define OP_Insert                              55
7555 #define OP_InsertInt                           56
7556 #define OP_Delete                              57
7557 #define OP_ResetCount                          58
7558 #define OP_RowKey                              59
7559 #define OP_RowData                             60
7560 #define OP_Rowid                               61
7561 #define OP_NullRow                             62
7562 #define OP_Last                                63
7563 #define OP_Sort                                64
7564 #define OP_Rewind                              65
7565 #define OP_Prev                                66
7566 #define OP_Next                                67
7567 #define OP_IdxInsert                           70
7568 #define OP_IdxDelete                           71
7569 #define OP_IdxRowid                            72
7570 #define OP_IdxLT                               81
7571 #define OP_IdxGE                               92
7572 #define OP_Destroy                             95
7573 #define OP_Clear                               96
7574 #define OP_CreateIndex                         97
7575 #define OP_CreateTable                         98
7576 #define OP_ParseSchema                         99
7577 #define OP_LoadAnalysis                       100
7578 #define OP_DropTable                          101
7579 #define OP_DropIndex                          102
7580 #define OP_DropTrigger                        103
7581 #define OP_IntegrityCk                        104
7582 #define OP_RowSetAdd                          105
7583 #define OP_RowSetRead                         106
7584 #define OP_RowSetTest                         107
7585 #define OP_Program                            108
7586 #define OP_Param                              109
7587 #define OP_FkCounter                          110
7588 #define OP_FkIfZero                           111
7589 #define OP_MemMax                             112
7590 #define OP_IfPos                              113
7591 #define OP_IfNeg                              114
7592 #define OP_IfZero                             115
7593 #define OP_AggStep                            116
7594 #define OP_AggFinal                           117
7595 #define OP_Checkpoint                         118
7596 #define OP_JournalMode                        119
7597 #define OP_Vacuum                             120
7598 #define OP_IncrVacuum                         121
7599 #define OP_Expire                             122
7600 #define OP_TableLock                          123
7601 #define OP_VBegin                             124
7602 #define OP_VCreate                            125
7603 #define OP_VDestroy                           126
7604 #define OP_VOpen                              127
7605 #define OP_VFilter                            128
7606 #define OP_VColumn                            129
7607 #define OP_VNext                              131
7608 #define OP_VRename                            132
7609 #define OP_VUpdate                            133
7610 #define OP_Pagecount                          134
7611 #define OP_Trace                              135
7612 #define OP_Noop                               136
7613 #define OP_Explain                            137
7614
7615 /* The following opcode values are never used */
7616 #define OP_NotUsed_138                        138
7617 #define OP_NotUsed_139                        139
7618 #define OP_NotUsed_140                        140
7619
7620
7621 /* Properties such as "out2" or "jump" that are specified in
7622 ** comments following the "case" for each opcode in the vdbe.c
7623 ** are encoded into bitvectors as follows:
7624 */
7625 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7626 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7627 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7628 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7629 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7630 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7631 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7632 #define OPFLG_INITIALIZER {\
7633 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7634 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7635 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7636 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7637 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7638 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7639 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7640 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7641 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7642 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7643 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7644 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7645 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7646 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7647 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7648 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7649 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7650 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7651 /* 144 */ 0x04, 0x04,}
7652
7653 /************** End of opcodes.h *********************************************/
7654 /************** Continuing where we left off in vdbe.h ***********************/
7655
7656 /*
7657 ** Prototypes for the VDBE interface.  See comments on the implementation
7658 ** for a description of what each of these routines does.
7659 */
7660 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7661 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7662 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7663 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7664 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7665 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7666 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7667 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7668 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7669 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7670 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7671 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7672 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7673 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7674 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7675 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7676 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7677 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7678 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7679 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7680 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7681 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7682 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7683 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7684 #ifdef SQLITE_DEBUG
7685 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7686 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7687 #endif
7688 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7689 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7690 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7691 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7692 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7693 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7694 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7695 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7696 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7697 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7698 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7699 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7700 #ifndef SQLITE_OMIT_TRACE
7701 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7702 #endif
7703
7704 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7705 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7706 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7707
7708
7709 #ifndef NDEBUG
7710 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7711 # define VdbeComment(X)  sqlite3VdbeComment X
7712 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7713 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7714 #else
7715 # define VdbeComment(X)
7716 # define VdbeNoopComment(X)
7717 #endif
7718
7719 #endif
7720
7721 /************** End of vdbe.h ************************************************/
7722 /************** Continuing where we left off in sqliteInt.h ******************/
7723 /************** Include pager.h in the middle of sqliteInt.h *****************/
7724 /************** Begin file pager.h *******************************************/
7725 /*
7726 ** 2001 September 15
7727 **
7728 ** The author disclaims copyright to this source code.  In place of
7729 ** a legal notice, here is a blessing:
7730 **
7731 **    May you do good and not evil.
7732 **    May you find forgiveness for yourself and forgive others.
7733 **    May you share freely, never taking more than you give.
7734 **
7735 *************************************************************************
7736 ** This header file defines the interface that the sqlite page cache
7737 ** subsystem.  The page cache subsystem reads and writes a file a page
7738 ** at a time and provides a journal for rollback.
7739 */
7740
7741 #ifndef _PAGER_H_
7742 #define _PAGER_H_
7743
7744 /*
7745 ** Default maximum size for persistent journal files. A negative 
7746 ** value means no limit. This value may be overridden using the 
7747 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7748 */
7749 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7750   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7751 #endif
7752
7753 /*
7754 ** The type used to represent a page number.  The first page in a file
7755 ** is called page 1.  0 is used to represent "not a page".
7756 */
7757 typedef u32 Pgno;
7758
7759 /*
7760 ** Each open file is managed by a separate instance of the "Pager" structure.
7761 */
7762 typedef struct Pager Pager;
7763
7764 /*
7765 ** Handle type for pages.
7766 */
7767 typedef struct PgHdr DbPage;
7768
7769 /*
7770 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7771 ** reserved for working around a windows/posix incompatibility). It is
7772 ** used in the journal to signify that the remainder of the journal file 
7773 ** is devoted to storing a master journal name - there are no more pages to
7774 ** roll back. See comments for function writeMasterJournal() in pager.c 
7775 ** for details.
7776 */
7777 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7778
7779 /*
7780 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7781 **
7782 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7783 */
7784 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7785 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7786
7787 /*
7788 ** Valid values for the second argument to sqlite3PagerLockingMode().
7789 */
7790 #define PAGER_LOCKINGMODE_QUERY      -1
7791 #define PAGER_LOCKINGMODE_NORMAL      0
7792 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7793
7794 /*
7795 ** Numeric constants that encode the journalmode.  
7796 */
7797 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
7798 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7799 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7800 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7801 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7802 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7803 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
7804
7805 /*
7806 ** The remainder of this file contains the declarations of the functions
7807 ** that make up the Pager sub-system API. See source code comments for 
7808 ** a detailed description of each routine.
7809 */
7810
7811 /* Open and close a Pager connection. */ 
7812 SQLITE_PRIVATE int sqlite3PagerOpen(
7813   sqlite3_vfs*,
7814   Pager **ppPager,
7815   const char*,
7816   int,
7817   int,
7818   int,
7819   void(*)(DbPage*)
7820 );
7821 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7822 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7823
7824 /* Functions used to configure a Pager object. */
7825 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7826 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7827 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7828 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7829 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7830 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7831 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
7832 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
7833 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
7834 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7835 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7836
7837 /* Functions used to obtain and release page references. */ 
7838 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7839 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7840 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7841 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7842 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7843
7844 /* Operations on page references. */
7845 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7846 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7847 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7848 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7849 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7850 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7851
7852 /* Functions used to manage pager transactions and savepoints. */
7853 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7854 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7855 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7856 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7857 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7858 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7859 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7860 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7861 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7862
7863 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
7864 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
7865 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
7866 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
7867 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
7868
7869 /* Functions used to query pager state and configuration. */
7870 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7871 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7872 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
7873 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7874 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7875 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7876 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7877 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7878 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7879 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7880
7881 /* Functions used to truncate the database file. */
7882 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7883
7884 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
7885 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
7886 #endif
7887
7888 /* Functions to support testing and debugging. */
7889 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7890 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7891 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7892 #endif
7893 #ifdef SQLITE_TEST
7894 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7895 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7896   void disable_simulated_io_errors(void);
7897   void enable_simulated_io_errors(void);
7898 #else
7899 # define disable_simulated_io_errors()
7900 # define enable_simulated_io_errors()
7901 #endif
7902
7903 #endif /* _PAGER_H_ */
7904
7905 /************** End of pager.h ***********************************************/
7906 /************** Continuing where we left off in sqliteInt.h ******************/
7907 /************** Include pcache.h in the middle of sqliteInt.h ****************/
7908 /************** Begin file pcache.h ******************************************/
7909 /*
7910 ** 2008 August 05
7911 **
7912 ** The author disclaims copyright to this source code.  In place of
7913 ** a legal notice, here is a blessing:
7914 **
7915 **    May you do good and not evil.
7916 **    May you find forgiveness for yourself and forgive others.
7917 **    May you share freely, never taking more than you give.
7918 **
7919 *************************************************************************
7920 ** This header file defines the interface that the sqlite page cache
7921 ** subsystem. 
7922 */
7923
7924 #ifndef _PCACHE_H_
7925
7926 typedef struct PgHdr PgHdr;
7927 typedef struct PCache PCache;
7928
7929 /*
7930 ** Every page in the cache is controlled by an instance of the following
7931 ** structure.
7932 */
7933 struct PgHdr {
7934   void *pData;                   /* Content of this page */
7935   void *pExtra;                  /* Extra content */
7936   PgHdr *pDirty;                 /* Transient list of dirty pages */
7937   Pgno pgno;                     /* Page number for this page */
7938   Pager *pPager;                 /* The pager this page is part of */
7939 #ifdef SQLITE_CHECK_PAGES
7940   u32 pageHash;                  /* Hash of page content */
7941 #endif
7942   u16 flags;                     /* PGHDR flags defined below */
7943
7944   /**********************************************************************
7945   ** Elements above are public.  All that follows is private to pcache.c
7946   ** and should not be accessed by other modules.
7947   */
7948   i16 nRef;                      /* Number of users of this page */
7949   PCache *pCache;                /* Cache that owns this page */
7950
7951   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7952   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7953 };
7954
7955 /* Bit values for PgHdr.flags */
7956 #define PGHDR_DIRTY             0x002  /* Page has changed */
7957 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7958                                        ** writing this page to the database */
7959 #define PGHDR_NEED_READ         0x008  /* Content is unread */
7960 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7961 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7962
7963 /* Initialize and shutdown the page cache subsystem */
7964 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7965 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7966
7967 /* Page cache buffer management:
7968 ** These routines implement SQLITE_CONFIG_PAGECACHE.
7969 */
7970 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7971
7972 /* Create a new pager cache.
7973 ** Under memory stress, invoke xStress to try to make pages clean.
7974 ** Only clean and unpinned pages can be reclaimed.
7975 */
7976 SQLITE_PRIVATE void sqlite3PcacheOpen(
7977   int szPage,                    /* Size of every page */
7978   int szExtra,                   /* Extra space associated with each page */
7979   int bPurgeable,                /* True if pages are on backing store */
7980   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7981   void *pStress,                 /* Argument to xStress */
7982   PCache *pToInit                /* Preallocated space for the PCache */
7983 );
7984
7985 /* Modify the page-size after the cache has been created. */
7986 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7987
7988 /* Return the size in bytes of a PCache object.  Used to preallocate
7989 ** storage space.
7990 */
7991 SQLITE_PRIVATE int sqlite3PcacheSize(void);
7992
7993 /* One release per successful fetch.  Page is pinned until released.
7994 ** Reference counted. 
7995 */
7996 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7997 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7998
7999 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8000 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8001 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8002 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8003
8004 /* Change a page number.  Used by incr-vacuum. */
8005 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8006
8007 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8008 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8009
8010 /* Get a list of all dirty pages in the cache, sorted by page number */
8011 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8012
8013 /* Reset and close the cache object */
8014 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8015
8016 /* Clear flags from pages of the page cache */
8017 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8018
8019 /* Discard the contents of the cache */
8020 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8021
8022 /* Return the total number of outstanding page references */
8023 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8024
8025 /* Increment the reference count of an existing page */
8026 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8027
8028 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8029
8030 /* Return the total number of pages stored in the cache */
8031 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8032
8033 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8034 /* Iterate through all dirty pages currently stored in the cache. This
8035 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8036 ** library is built.
8037 */
8038 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8039 #endif
8040
8041 /* Set and get the suggested cache-size for the specified pager-cache.
8042 **
8043 ** If no global maximum is configured, then the system attempts to limit
8044 ** the total number of pages cached by purgeable pager-caches to the sum
8045 ** of the suggested cache-sizes.
8046 */
8047 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8048 #ifdef SQLITE_TEST
8049 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8050 #endif
8051
8052 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8053 /* Try to return memory used by the pcache module to the main memory heap */
8054 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8055 #endif
8056
8057 #ifdef SQLITE_TEST
8058 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8059 #endif
8060
8061 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8062
8063 #endif /* _PCACHE_H_ */
8064
8065 /************** End of pcache.h **********************************************/
8066 /************** Continuing where we left off in sqliteInt.h ******************/
8067
8068 /************** Include os.h in the middle of sqliteInt.h ********************/
8069 /************** Begin file os.h **********************************************/
8070 /*
8071 ** 2001 September 16
8072 **
8073 ** The author disclaims copyright to this source code.  In place of
8074 ** a legal notice, here is a blessing:
8075 **
8076 **    May you do good and not evil.
8077 **    May you find forgiveness for yourself and forgive others.
8078 **    May you share freely, never taking more than you give.
8079 **
8080 ******************************************************************************
8081 **
8082 ** This header file (together with is companion C source-code file
8083 ** "os.c") attempt to abstract the underlying operating system so that
8084 ** the SQLite library will work on both POSIX and windows systems.
8085 **
8086 ** This header file is #include-ed by sqliteInt.h and thus ends up
8087 ** being included by every source file.
8088 */
8089 #ifndef _SQLITE_OS_H_
8090 #define _SQLITE_OS_H_
8091
8092 /*
8093 ** Figure out if we are dealing with Unix, Windows, or some other
8094 ** operating system.  After the following block of preprocess macros,
8095 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8096 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8097 ** three will be 0.
8098 */
8099 #if defined(SQLITE_OS_OTHER)
8100 # if SQLITE_OS_OTHER==1
8101 #   undef SQLITE_OS_UNIX
8102 #   define SQLITE_OS_UNIX 0
8103 #   undef SQLITE_OS_WIN
8104 #   define SQLITE_OS_WIN 0
8105 #   undef SQLITE_OS_OS2
8106 #   define SQLITE_OS_OS2 0
8107 # else
8108 #   undef SQLITE_OS_OTHER
8109 # endif
8110 #endif
8111 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8112 # define SQLITE_OS_OTHER 0
8113 # ifndef SQLITE_OS_WIN
8114 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8115 #     define SQLITE_OS_WIN 1
8116 #     define SQLITE_OS_UNIX 0
8117 #     define SQLITE_OS_OS2 0
8118 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8119 #     define SQLITE_OS_WIN 0
8120 #     define SQLITE_OS_UNIX 0
8121 #     define SQLITE_OS_OS2 1
8122 #   else
8123 #     define SQLITE_OS_WIN 0
8124 #     define SQLITE_OS_UNIX 1
8125 #     define SQLITE_OS_OS2 0
8126 #  endif
8127 # else
8128 #  define SQLITE_OS_UNIX 0
8129 #  define SQLITE_OS_OS2 0
8130 # endif
8131 #else
8132 # ifndef SQLITE_OS_WIN
8133 #  define SQLITE_OS_WIN 0
8134 # endif
8135 #endif
8136
8137 /*
8138 ** Determine if we are dealing with WindowsCE - which has a much
8139 ** reduced API.
8140 */
8141 #if defined(_WIN32_WCE)
8142 # define SQLITE_OS_WINCE 1
8143 #else
8144 # define SQLITE_OS_WINCE 0
8145 #endif
8146
8147
8148 /*
8149 ** Define the maximum size of a temporary filename
8150 */
8151 #if SQLITE_OS_WIN
8152 # include <windows.h>
8153 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8154 #elif SQLITE_OS_OS2
8155 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8156 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8157 # endif
8158 # define INCL_DOSDATETIME
8159 # define INCL_DOSFILEMGR
8160 # define INCL_DOSERRORS
8161 # define INCL_DOSMISC
8162 # define INCL_DOSPROCESS
8163 # define INCL_DOSMODULEMGR
8164 # define INCL_DOSSEMAPHORES
8165 # include <os2.h>
8166 # include <uconv.h>
8167 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8168 #else
8169 # define SQLITE_TEMPNAME_SIZE 200
8170 #endif
8171
8172 /* If the SET_FULLSYNC macro is not defined above, then make it
8173 ** a no-op
8174 */
8175 #ifndef SET_FULLSYNC
8176 # define SET_FULLSYNC(x,y)
8177 #endif
8178
8179 /*
8180 ** The default size of a disk sector
8181 */
8182 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8183 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8184 #endif
8185
8186 /*
8187 ** Temporary files are named starting with this prefix followed by 16 random
8188 ** alphanumeric characters, and no file extension. They are stored in the
8189 ** OS's standard temporary file directory, and are deleted prior to exit.
8190 ** If sqlite is being embedded in another program, you may wish to change the
8191 ** prefix to reflect your program's name, so that if your program exits
8192 ** prematurely, old temporary files can be easily identified. This can be done
8193 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8194 **
8195 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8196 ** Mcafee started using SQLite in their anti-virus product and it
8197 ** started putting files with the "sqlite" name in the c:/temp folder.
8198 ** This annoyed many windows users.  Those users would then do a 
8199 ** Google search for "sqlite", find the telephone numbers of the
8200 ** developers and call to wake them up at night and complain.
8201 ** For this reason, the default name prefix is changed to be "sqlite" 
8202 ** spelled backwards.  So the temp files are still identified, but
8203 ** anybody smart enough to figure out the code is also likely smart
8204 ** enough to know that calling the developer will not help get rid
8205 ** of the file.
8206 */
8207 #ifndef SQLITE_TEMP_FILE_PREFIX
8208 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8209 #endif
8210
8211 /*
8212 ** The following values may be passed as the second argument to
8213 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8214 **
8215 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8216 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8217 **            any time. Other processes may hold and obtain new SHARED locks.
8218 ** PENDING:   A single process may hold a PENDING lock on a file at
8219 **            any one time. Existing SHARED locks may persist, but no new
8220 **            SHARED locks may be obtained by other processes.
8221 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8222 **
8223 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8224 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8225 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8226 ** sqlite3OsLock().
8227 */
8228 #define NO_LOCK         0
8229 #define SHARED_LOCK     1
8230 #define RESERVED_LOCK   2
8231 #define PENDING_LOCK    3
8232 #define EXCLUSIVE_LOCK  4
8233
8234 /*
8235 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8236 **
8237 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8238 ** those functions are not available.  So we use only LockFile() and
8239 ** UnlockFile().
8240 **
8241 ** LockFile() prevents not just writing but also reading by other processes.
8242 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8243 ** byte out of a specific range of bytes. The lock byte is obtained at 
8244 ** random so two separate readers can probably access the file at the 
8245 ** same time, unless they are unlucky and choose the same lock byte.
8246 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8247 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8248 ** a single byte of the file that is designated as the reserved lock byte.
8249 ** A PENDING_LOCK is obtained by locking a designated byte different from
8250 ** the RESERVED_LOCK byte.
8251 **
8252 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8253 ** which means we can use reader/writer locks.  When reader/writer locks
8254 ** are used, the lock is placed on the same range of bytes that is used
8255 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8256 ** will support two or more Win95 readers or two or more WinNT readers.
8257 ** But a single Win95 reader will lock out all WinNT readers and a single
8258 ** WinNT reader will lock out all other Win95 readers.
8259 **
8260 ** The following #defines specify the range of bytes used for locking.
8261 ** SHARED_SIZE is the number of bytes available in the pool from which
8262 ** a random byte is selected for a shared lock.  The pool of bytes for
8263 ** shared locks begins at SHARED_FIRST. 
8264 **
8265 ** The same locking strategy and
8266 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8267 ** clients on win95, winNT, and unix all talking to the same shared file
8268 ** and all locking correctly.  To do so would require that samba (or whatever
8269 ** tool is being used for file sharing) implements locks correctly between
8270 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8271 ** using the same locking range we are at least open to the possibility.
8272 **
8273 ** Locking in windows is manditory.  For this reason, we cannot store
8274 ** actual data in the bytes used for locking.  The pager never allocates
8275 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8276 ** that all locks will fit on a single page even at the minimum page size.
8277 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8278 ** is set high so that we don't have to allocate an unused page except
8279 ** for very large databases.  But one should test the page skipping logic 
8280 ** by setting PENDING_BYTE low and running the entire regression suite.
8281 **
8282 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8283 ** file format.  Depending on how it is changed, you might not notice
8284 ** the incompatibility right away, even running a full regression test.
8285 ** The default location of PENDING_BYTE is the first byte past the
8286 ** 1GB boundary.
8287 **
8288 */
8289 #ifdef SQLITE_OMIT_WSD
8290 # define PENDING_BYTE     (0x40000000)
8291 #else
8292 # define PENDING_BYTE      sqlite3PendingByte
8293 #endif
8294 #define RESERVED_BYTE     (PENDING_BYTE+1)
8295 #define SHARED_FIRST      (PENDING_BYTE+2)
8296 #define SHARED_SIZE       510
8297
8298 /*
8299 ** Wrapper around OS specific sqlite3_os_init() function.
8300 */
8301 SQLITE_PRIVATE int sqlite3OsInit(void);
8302
8303 /* 
8304 ** Functions for accessing sqlite3_file methods 
8305 */
8306 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8307 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8308 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8309 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8310 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8311 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8312 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8313 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8314 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8315 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8316 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8317 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8318 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8319 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8320 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8321 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8322 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8323
8324 /* 
8325 ** Functions for accessing sqlite3_vfs methods 
8326 */
8327 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8328 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8329 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8330 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8331 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8332 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8333 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8334 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8335 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8336 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8337 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8338 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8339 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8340
8341 /*
8342 ** Convenience functions for opening and closing files using 
8343 ** sqlite3_malloc() to obtain space for the file-handle structure.
8344 */
8345 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8346 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8347
8348 #endif /* _SQLITE_OS_H_ */
8349
8350 /************** End of os.h **************************************************/
8351 /************** Continuing where we left off in sqliteInt.h ******************/
8352 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8353 /************** Begin file mutex.h *******************************************/
8354 /*
8355 ** 2007 August 28
8356 **
8357 ** The author disclaims copyright to this source code.  In place of
8358 ** a legal notice, here is a blessing:
8359 **
8360 **    May you do good and not evil.
8361 **    May you find forgiveness for yourself and forgive others.
8362 **    May you share freely, never taking more than you give.
8363 **
8364 *************************************************************************
8365 **
8366 ** This file contains the common header for all mutex implementations.
8367 ** The sqliteInt.h header #includes this file so that it is available
8368 ** to all source files.  We break it out in an effort to keep the code
8369 ** better organized.
8370 **
8371 ** NOTE:  source files should *not* #include this header file directly.
8372 ** Source files should #include the sqliteInt.h file and let that file
8373 ** include this one indirectly.
8374 */
8375
8376
8377 /*
8378 ** Figure out what version of the code to use.  The choices are
8379 **
8380 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8381 **                             mutexes implemention cannot be overridden
8382 **                             at start-time.
8383 **
8384 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8385 **                             mutual exclusion is provided.  But this
8386 **                             implementation can be overridden at
8387 **                             start-time.
8388 **
8389 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8390 **
8391 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8392 **
8393 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8394 */
8395 #if !SQLITE_THREADSAFE
8396 # define SQLITE_MUTEX_OMIT
8397 #endif
8398 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8399 #  if SQLITE_OS_UNIX
8400 #    define SQLITE_MUTEX_PTHREADS
8401 #  elif SQLITE_OS_WIN
8402 #    define SQLITE_MUTEX_W32
8403 #  elif SQLITE_OS_OS2
8404 #    define SQLITE_MUTEX_OS2
8405 #  else
8406 #    define SQLITE_MUTEX_NOOP
8407 #  endif
8408 #endif
8409
8410 #ifdef SQLITE_MUTEX_OMIT
8411 /*
8412 ** If this is a no-op implementation, implement everything as macros.
8413 */
8414 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8415 #define sqlite3_mutex_free(X)
8416 #define sqlite3_mutex_enter(X)
8417 #define sqlite3_mutex_try(X)      SQLITE_OK
8418 #define sqlite3_mutex_leave(X)
8419 #define sqlite3_mutex_held(X)     1
8420 #define sqlite3_mutex_notheld(X)  1
8421 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8422 #define sqlite3MutexInit()        SQLITE_OK
8423 #define sqlite3MutexEnd()
8424 #endif /* defined(SQLITE_MUTEX_OMIT) */
8425
8426 /************** End of mutex.h ***********************************************/
8427 /************** Continuing where we left off in sqliteInt.h ******************/
8428
8429
8430 /*
8431 ** Each database file to be accessed by the system is an instance
8432 ** of the following structure.  There are normally two of these structures
8433 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8434 ** aDb[1] is the database file used to hold temporary tables.  Additional
8435 ** databases may be attached.
8436 */
8437 struct Db {
8438   char *zName;         /* Name of this database */
8439   Btree *pBt;          /* The B*Tree structure for this database file */
8440   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8441   u8 safety_level;     /* How aggressive at syncing data to disk */
8442   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8443 };
8444
8445 /*
8446 ** An instance of the following structure stores a database schema.
8447 **
8448 ** If there are no virtual tables configured in this schema, the
8449 ** Schema.db variable is set to NULL. After the first virtual table
8450 ** has been added, it is set to point to the database connection 
8451 ** used to create the connection. Once a virtual table has been
8452 ** added to the Schema structure and the Schema.db variable populated, 
8453 ** only that database connection may use the Schema to prepare 
8454 ** statements.
8455 */
8456 struct Schema {
8457   int schema_cookie;   /* Database schema version number for this file */
8458   Hash tblHash;        /* All tables indexed by name */
8459   Hash idxHash;        /* All (named) indices indexed by name */
8460   Hash trigHash;       /* All triggers indexed by name */
8461   Hash fkeyHash;       /* All foreign keys by referenced table name */
8462   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8463   u8 file_format;      /* Schema format version for this file */
8464   u8 enc;              /* Text encoding used by this database */
8465   u16 flags;           /* Flags associated with this schema */
8466   int cache_size;      /* Number of pages to use in the cache */
8467 #ifndef SQLITE_OMIT_VIRTUALTABLE
8468   sqlite3 *db;         /* "Owner" connection. See comment above */
8469 #endif
8470 };
8471
8472 /*
8473 ** These macros can be used to test, set, or clear bits in the 
8474 ** Db.pSchema->flags field.
8475 */
8476 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8477 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8478 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8479 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8480
8481 /*
8482 ** Allowed values for the DB.pSchema->flags field.
8483 **
8484 ** The DB_SchemaLoaded flag is set after the database schema has been
8485 ** read into internal hash tables.
8486 **
8487 ** DB_UnresetViews means that one or more views have column names that
8488 ** have been filled out.  If the schema changes, these column names might
8489 ** changes and so the view will need to be reset.
8490 */
8491 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8492 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8493 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8494
8495 /*
8496 ** The number of different kinds of things that can be limited
8497 ** using the sqlite3_limit() interface.
8498 */
8499 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8500
8501 /*
8502 ** Lookaside malloc is a set of fixed-size buffers that can be used
8503 ** to satisfy small transient memory allocation requests for objects
8504 ** associated with a particular database connection.  The use of
8505 ** lookaside malloc provides a significant performance enhancement
8506 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8507 ** SQL statements.
8508 **
8509 ** The Lookaside structure holds configuration information about the
8510 ** lookaside malloc subsystem.  Each available memory allocation in
8511 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8512 ** objects.
8513 **
8514 ** Lookaside allocations are only allowed for objects that are associated
8515 ** with a particular database connection.  Hence, schema information cannot
8516 ** be stored in lookaside because in shared cache mode the schema information
8517 ** is shared by multiple database connections.  Therefore, while parsing
8518 ** schema information, the Lookaside.bEnabled flag is cleared so that
8519 ** lookaside allocations are not used to construct the schema objects.
8520 */
8521 struct Lookaside {
8522   u16 sz;                 /* Size of each buffer in bytes */
8523   u8 bEnabled;            /* False to disable new lookaside allocations */
8524   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8525   int nOut;               /* Number of buffers currently checked out */
8526   int mxOut;              /* Highwater mark for nOut */
8527   LookasideSlot *pFree;   /* List of available buffers */
8528   void *pStart;           /* First byte of available memory space */
8529   void *pEnd;             /* First byte past end of available space */
8530 };
8531 struct LookasideSlot {
8532   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8533 };
8534
8535 /*
8536 ** A hash table for function definitions.
8537 **
8538 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8539 ** Collisions are on the FuncDef.pHash chain.
8540 */
8541 struct FuncDefHash {
8542   FuncDef *a[23];       /* Hash table for functions */
8543 };
8544
8545 /*
8546 ** Each database connection is an instance of the following structure.
8547 **
8548 ** The sqlite.lastRowid records the last insert rowid generated by an
8549 ** insert statement.  Inserts on views do not affect its value.  Each
8550 ** trigger has its own context, so that lastRowid can be updated inside
8551 ** triggers as usual.  The previous value will be restored once the trigger
8552 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8553 ** longer (since after version 2.8.12) reset to -1.
8554 **
8555 ** The sqlite.nChange does not count changes within triggers and keeps no
8556 ** context.  It is reset at start of sqlite3_exec.
8557 ** The sqlite.lsChange represents the number of changes made by the last
8558 ** insert, update, or delete statement.  It remains constant throughout the
8559 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8560 ** context stack just like lastRowid so that the count of changes
8561 ** within a trigger is not seen outside the trigger.  Changes to views do not
8562 ** affect the value of lsChange.
8563 ** The sqlite.csChange keeps track of the number of current changes (since
8564 ** the last statement) and is used to update sqlite_lsChange.
8565 **
8566 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8567 ** store the most recent error code and, if applicable, string. The
8568 ** internal function sqlite3Error() is used to set these variables
8569 ** consistently.
8570 */
8571 struct sqlite3 {
8572   sqlite3_vfs *pVfs;            /* OS Interface */
8573   int nDb;                      /* Number of backends currently in use */
8574   Db *aDb;                      /* All backends */
8575   int flags;                    /* Miscellaneous flags. See below */
8576   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8577   int errCode;                  /* Most recent error code (SQLITE_*) */
8578   int errMask;                  /* & result codes with this before returning */
8579   u8 autoCommit;                /* The auto-commit flag. */
8580   u8 temp_store;                /* 1: file 2: memory 0: default */
8581   u8 mallocFailed;              /* True if we have seen a malloc failure */
8582   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8583   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8584   u8 suppressErr;               /* Do not issue error messages if true */
8585   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8586   int nTable;                   /* Number of tables in the database */
8587   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8588   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8589   u32 magic;                    /* Magic number for detect library misuse */
8590   int nChange;                  /* Value returned by sqlite3_changes() */
8591   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8592   sqlite3_mutex *mutex;         /* Connection mutex */
8593   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8594   struct sqlite3InitInfo {      /* Information used during initialization */
8595     int iDb;                    /* When back is being initialized */
8596     int newTnum;                /* Rootpage of table being initialized */
8597     u8 busy;                    /* TRUE if currently initializing */
8598     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8599   } init;
8600   int nExtension;               /* Number of loaded extensions */
8601   void **aExtension;            /* Array of shared library handles */
8602   struct Vdbe *pVdbe;           /* List of active virtual machines */
8603   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8604   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8605   void (*xTrace)(void*,const char*);        /* Trace function */
8606   void *pTraceArg;                          /* Argument to the trace function */
8607   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8608   void *pProfileArg;                        /* Argument to profile function */
8609   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8610   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8611   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8612   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8613   void *pUpdateArg;
8614   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8615 #ifndef SQLITE_OMIT_WAL
8616   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8617   void *pWalArg;
8618 #endif
8619   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8620   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8621   void *pCollNeededArg;
8622   sqlite3_value *pErr;          /* Most recent error message */
8623   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8624   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8625   union {
8626     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8627     double notUsed1;            /* Spacer */
8628   } u1;
8629   Lookaside lookaside;          /* Lookaside malloc configuration */
8630 #ifndef SQLITE_OMIT_AUTHORIZATION
8631   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8632                                 /* Access authorization function */
8633   void *pAuthArg;               /* 1st argument to the access auth function */
8634 #endif
8635 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8636   int (*xProgress)(void *);     /* The progress callback */
8637   void *pProgressArg;           /* Argument to the progress callback */
8638   int nProgressOps;             /* Number of opcodes for progress callback */
8639 #endif
8640 #ifndef SQLITE_OMIT_VIRTUALTABLE
8641   Hash aModule;                 /* populated by sqlite3_create_module() */
8642   Table *pVTab;                 /* vtab with active Connect/Create method */
8643   VTable **aVTrans;             /* Virtual tables with open transactions */
8644   int nVTrans;                  /* Allocated size of aVTrans */
8645   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8646 #endif
8647   FuncDefHash aFunc;            /* Hash table of connection functions */
8648   Hash aCollSeq;                /* All collating sequences */
8649   BusyHandler busyHandler;      /* Busy callback */
8650   int busyTimeout;              /* Busy handler timeout, in msec */
8651   Db aDbStatic[2];              /* Static space for the 2 default backends */
8652   Savepoint *pSavepoint;        /* List of active savepoints */
8653   int nSavepoint;               /* Number of non-transaction savepoints */
8654   int nStatement;               /* Number of nested statement-transactions  */
8655   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8656   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8657
8658 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8659   /* The following variables are all protected by the STATIC_MASTER 
8660   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
8661   **
8662   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8663   ** unlock so that it can proceed.
8664   **
8665   ** When X.pBlockingConnection==Y, that means that something that X tried
8666   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8667   ** held by Y.
8668   */
8669   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8670   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8671   void *pUnlockArg;                     /* Argument to xUnlockNotify */
8672   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8673   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8674 #endif
8675 };
8676
8677 /*
8678 ** A macro to discover the encoding of a database.
8679 */
8680 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8681
8682 /*
8683 ** Possible values for the sqlite3.flags.
8684 */
8685 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8686 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8687 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8688 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8689 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8690                                           /*   DELETE, or UPDATE and return */
8691                                           /*   the count using a callback. */
8692 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8693                                           /*   result set is empty */
8694 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8695 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8696 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8697 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
8698                                           ** accessing read-only databases */
8699 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8700 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8701 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8702 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8703 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8704 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8705 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8706 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8707 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8708 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8709 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8710
8711 /*
8712 ** Bits of the sqlite3.flags field that are used by the
8713 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8714 ** These must be the low-order bits of the flags field.
8715 */
8716 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8717 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8718 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8719 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8720 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
8721 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
8722 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
8723
8724 /*
8725 ** Possible values for the sqlite.magic field.
8726 ** The numbers are obtained at random and have no special meaning, other
8727 ** than being distinct from one another.
8728 */
8729 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8730 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8731 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8732 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8733 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8734
8735 /*
8736 ** Each SQL function is defined by an instance of the following
8737 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8738 ** hash table.  When multiple functions have the same name, the hash table
8739 ** points to a linked list of these structures.
8740 */
8741 struct FuncDef {
8742   i16 nArg;            /* Number of arguments.  -1 means unlimited */
8743   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8744   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8745   void *pUserData;     /* User data parameter */
8746   FuncDef *pNext;      /* Next function with same name */
8747   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8748   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8749   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8750   char *zName;         /* SQL name of the function. */
8751   FuncDef *pHash;      /* Next with a different name but the same hash */
8752 };
8753
8754 /*
8755 ** Possible values for FuncDef.flags
8756 */
8757 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8758 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8759 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8760 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8761 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8762 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8763 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8764
8765 /*
8766 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8767 ** used to create the initializers for the FuncDef structures.
8768 **
8769 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8770 **     Used to create a scalar function definition of a function zName 
8771 **     implemented by C function xFunc that accepts nArg arguments. The
8772 **     value passed as iArg is cast to a (void*) and made available
8773 **     as the user-data (sqlite3_user_data()) for the function. If 
8774 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8775 **
8776 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8777 **     Used to create an aggregate function definition implemented by
8778 **     the C functions xStep and xFinal. The first four parameters
8779 **     are interpreted in the same way as the first 4 parameters to
8780 **     FUNCTION().
8781 **
8782 **   LIKEFUNC(zName, nArg, pArg, flags)
8783 **     Used to create a scalar function definition of a function zName 
8784 **     that accepts nArg arguments and is implemented by a call to C 
8785 **     function likeFunc. Argument pArg is cast to a (void *) and made
8786 **     available as the function user-data (sqlite3_user_data()). The
8787 **     FuncDef.flags variable is set to the value passed as the flags
8788 **     parameter.
8789 */
8790 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8791   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8792    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8793 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8794   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8795    pArg, 0, xFunc, 0, 0, #zName, 0}
8796 #define LIKEFUNC(zName, nArg, arg, flags) \
8797   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8798 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8799   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8800    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8801
8802 /*
8803 ** All current savepoints are stored in a linked list starting at
8804 ** sqlite3.pSavepoint. The first element in the list is the most recently
8805 ** opened savepoint. Savepoints are added to the list by the vdbe
8806 ** OP_Savepoint instruction.
8807 */
8808 struct Savepoint {
8809   char *zName;                        /* Savepoint name (nul-terminated) */
8810   i64 nDeferredCons;                  /* Number of deferred fk violations */
8811   Savepoint *pNext;                   /* Parent savepoint (if any) */
8812 };
8813
8814 /*
8815 ** The following are used as the second parameter to sqlite3Savepoint(),
8816 ** and as the P1 argument to the OP_Savepoint instruction.
8817 */
8818 #define SAVEPOINT_BEGIN      0
8819 #define SAVEPOINT_RELEASE    1
8820 #define SAVEPOINT_ROLLBACK   2
8821
8822
8823 /*
8824 ** Each SQLite module (virtual table definition) is defined by an
8825 ** instance of the following structure, stored in the sqlite3.aModule
8826 ** hash table.
8827 */
8828 struct Module {
8829   const sqlite3_module *pModule;       /* Callback pointers */
8830   const char *zName;                   /* Name passed to create_module() */
8831   void *pAux;                          /* pAux passed to create_module() */
8832   void (*xDestroy)(void *);            /* Module destructor function */
8833 };
8834
8835 /*
8836 ** information about each column of an SQL table is held in an instance
8837 ** of this structure.
8838 */
8839 struct Column {
8840   char *zName;     /* Name of this column */
8841   Expr *pDflt;     /* Default value of this column */
8842   char *zDflt;     /* Original text of the default value */
8843   char *zType;     /* Data type for this column */
8844   char *zColl;     /* Collating sequence.  If NULL, use the default */
8845   u8 notNull;      /* True if there is a NOT NULL constraint */
8846   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8847   char affinity;   /* One of the SQLITE_AFF_... values */
8848 #ifndef SQLITE_OMIT_VIRTUALTABLE
8849   u8 isHidden;     /* True if this column is 'hidden' */
8850 #endif
8851 };
8852
8853 /*
8854 ** A "Collating Sequence" is defined by an instance of the following
8855 ** structure. Conceptually, a collating sequence consists of a name and
8856 ** a comparison routine that defines the order of that sequence.
8857 **
8858 ** There may two separate implementations of the collation function, one
8859 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8860 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8861 ** native byte order. When a collation sequence is invoked, SQLite selects
8862 ** the version that will require the least expensive encoding
8863 ** translations, if any.
8864 **
8865 ** The CollSeq.pUser member variable is an extra parameter that passed in
8866 ** as the first argument to the UTF-8 comparison function, xCmp.
8867 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8868 ** xCmp16.
8869 **
8870 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8871 ** collating sequence is undefined.  Indices built on an undefined
8872 ** collating sequence may not be read or written.
8873 */
8874 struct CollSeq {
8875   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8876   u8 enc;               /* Text encoding handled by xCmp() */
8877   u8 type;              /* One of the SQLITE_COLL_... values below */
8878   void *pUser;          /* First argument to xCmp() */
8879   int (*xCmp)(void*,int, const void*, int, const void*);
8880   void (*xDel)(void*);  /* Destructor for pUser */
8881 };
8882
8883 /*
8884 ** Allowed values of CollSeq.type:
8885 */
8886 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8887 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8888 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8889 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8890
8891 /*
8892 ** A sort order can be either ASC or DESC.
8893 */
8894 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
8895 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
8896
8897 /*
8898 ** Column affinity types.
8899 **
8900 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8901 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8902 ** the speed a little by numbering the values consecutively.  
8903 **
8904 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8905 ** when multiple affinity types are concatenated into a string and
8906 ** used as the P4 operand, they will be more readable.
8907 **
8908 ** Note also that the numeric types are grouped together so that testing
8909 ** for a numeric type is a single comparison.
8910 */
8911 #define SQLITE_AFF_TEXT     'a'
8912 #define SQLITE_AFF_NONE     'b'
8913 #define SQLITE_AFF_NUMERIC  'c'
8914 #define SQLITE_AFF_INTEGER  'd'
8915 #define SQLITE_AFF_REAL     'e'
8916
8917 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8918
8919 /*
8920 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8921 ** affinity value. 
8922 */
8923 #define SQLITE_AFF_MASK     0x67
8924
8925 /*
8926 ** Additional bit values that can be ORed with an affinity without
8927 ** changing the affinity.
8928 */
8929 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8930 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8931 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8932
8933 /*
8934 ** An object of this type is created for each virtual table present in
8935 ** the database schema. 
8936 **
8937 ** If the database schema is shared, then there is one instance of this
8938 ** structure for each database connection (sqlite3*) that uses the shared
8939 ** schema. This is because each database connection requires its own unique
8940 ** instance of the sqlite3_vtab* handle used to access the virtual table 
8941 ** implementation. sqlite3_vtab* handles can not be shared between 
8942 ** database connections, even when the rest of the in-memory database 
8943 ** schema is shared, as the implementation often stores the database
8944 ** connection handle passed to it via the xConnect() or xCreate() method
8945 ** during initialization internally. This database connection handle may
8946 ** then used by the virtual table implementation to access real tables 
8947 ** within the database. So that they appear as part of the callers 
8948 ** transaction, these accesses need to be made via the same database 
8949 ** connection as that used to execute SQL operations on the virtual table.
8950 **
8951 ** All VTable objects that correspond to a single table in a shared
8952 ** database schema are initially stored in a linked-list pointed to by
8953 ** the Table.pVTable member variable of the corresponding Table object.
8954 ** When an sqlite3_prepare() operation is required to access the virtual
8955 ** table, it searches the list for the VTable that corresponds to the
8956 ** database connection doing the preparing so as to use the correct
8957 ** sqlite3_vtab* handle in the compiled query.
8958 **
8959 ** When an in-memory Table object is deleted (for example when the
8960 ** schema is being reloaded for some reason), the VTable objects are not 
8961 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
8962 ** immediately. Instead, they are moved from the Table.pVTable list to
8963 ** another linked list headed by the sqlite3.pDisconnect member of the
8964 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
8965 ** next time a statement is prepared using said sqlite3*. This is done
8966 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8967 ** Refer to comments above function sqlite3VtabUnlockList() for an
8968 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8969 ** list without holding the corresponding sqlite3.mutex mutex.
8970 **
8971 ** The memory for objects of this type is always allocated by 
8972 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
8973 ** the first argument.
8974 */
8975 struct VTable {
8976   sqlite3 *db;              /* Database connection associated with this table */
8977   Module *pMod;             /* Pointer to module implementation */
8978   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8979   int nRef;                 /* Number of pointers to this structure */
8980   VTable *pNext;            /* Next in linked list (see above) */
8981 };
8982
8983 /*
8984 ** Each SQL table is represented in memory by an instance of the
8985 ** following structure.
8986 **
8987 ** Table.zName is the name of the table.  The case of the original
8988 ** CREATE TABLE statement is stored, but case is not significant for
8989 ** comparisons.
8990 **
8991 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8992 ** pointer to an array of Column structures, one for each column.
8993 **
8994 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8995 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8996 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8997 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8998 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8999 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9000 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9001 **
9002 ** Table.tnum is the page number for the root BTree page of the table in the
9003 ** database file.  If Table.iDb is the index of the database table backend
9004 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9005 ** holds temporary tables and indices.  If TF_Ephemeral is set
9006 ** then the table is stored in a file that is automatically deleted
9007 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9008 ** refers VDBE cursor number that holds the table open, not to the root
9009 ** page number.  Transient tables are used to hold the results of a
9010 ** sub-query that appears instead of a real table name in the FROM clause 
9011 ** of a SELECT statement.
9012 */
9013 struct Table {
9014   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
9015   char *zName;         /* Name of the table or view */
9016   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9017   int nCol;            /* Number of columns in this table */
9018   Column *aCol;        /* Information about each column */
9019   Index *pIndex;       /* List of SQL indexes on this table. */
9020   int tnum;            /* Root BTree node for this table (see note above) */
9021   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9022   u16 nRef;            /* Number of pointers to this Table */
9023   u8 tabFlags;         /* Mask of TF_* values */
9024   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9025   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9026   char *zColAff;       /* String defining the affinity of each column */
9027 #ifndef SQLITE_OMIT_CHECK
9028   Expr *pCheck;        /* The AND of all CHECK constraints */
9029 #endif
9030 #ifndef SQLITE_OMIT_ALTERTABLE
9031   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9032 #endif
9033 #ifndef SQLITE_OMIT_VIRTUALTABLE
9034   VTable *pVTable;     /* List of VTable objects. */
9035   int nModuleArg;      /* Number of arguments to the module */
9036   char **azModuleArg;  /* Text of all module args. [0] is module name */
9037 #endif
9038   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9039   Schema *pSchema;     /* Schema that contains this table */
9040   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9041 };
9042
9043 /*
9044 ** Allowed values for Tabe.tabFlags.
9045 */
9046 #define TF_Readonly        0x01    /* Read-only system table */
9047 #define TF_Ephemeral       0x02    /* An ephemeral table */
9048 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9049 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9050 #define TF_Virtual         0x10    /* Is a virtual table */
9051 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9052
9053
9054
9055 /*
9056 ** Test to see whether or not a table is a virtual table.  This is
9057 ** done as a macro so that it will be optimized out when virtual
9058 ** table support is omitted from the build.
9059 */
9060 #ifndef SQLITE_OMIT_VIRTUALTABLE
9061 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9062 #  define IsHiddenColumn(X) ((X)->isHidden)
9063 #else
9064 #  define IsVirtual(X)      0
9065 #  define IsHiddenColumn(X) 0
9066 #endif
9067
9068 /*
9069 ** Each foreign key constraint is an instance of the following structure.
9070 **
9071 ** A foreign key is associated with two tables.  The "from" table is
9072 ** the table that contains the REFERENCES clause that creates the foreign
9073 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9074 ** Consider this example:
9075 **
9076 **     CREATE TABLE ex1(
9077 **       a INTEGER PRIMARY KEY,
9078 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9079 **     );
9080 **
9081 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9082 **
9083 ** Each REFERENCES clause generates an instance of the following structure
9084 ** which is attached to the from-table.  The to-table need not exist when
9085 ** the from-table is created.  The existence of the to-table is not checked.
9086 */
9087 struct FKey {
9088   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9089   FKey *pNextFrom;  /* Next foreign key in pFrom */
9090   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9091   FKey *pNextTo;    /* Next foreign key on table named zTo */
9092   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9093   int nCol;         /* Number of columns in this key */
9094   /* EV: R-30323-21917 */
9095   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9096   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9097   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9098   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9099     int iFrom;         /* Index of column in pFrom */
9100     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9101   } aCol[1];        /* One entry for each of nCol column s */
9102 };
9103
9104 /*
9105 ** SQLite supports many different ways to resolve a constraint
9106 ** error.  ROLLBACK processing means that a constraint violation
9107 ** causes the operation in process to fail and for the current transaction
9108 ** to be rolled back.  ABORT processing means the operation in process
9109 ** fails and any prior changes from that one operation are backed out,
9110 ** but the transaction is not rolled back.  FAIL processing means that
9111 ** the operation in progress stops and returns an error code.  But prior
9112 ** changes due to the same operation are not backed out and no rollback
9113 ** occurs.  IGNORE means that the particular row that caused the constraint
9114 ** error is not inserted or updated.  Processing continues and no error
9115 ** is returned.  REPLACE means that preexisting database rows that caused
9116 ** a UNIQUE constraint violation are removed so that the new insert or
9117 ** update can proceed.  Processing continues and no error is reported.
9118 **
9119 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9120 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9121 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9122 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9123 ** referenced table row is propagated into the row that holds the
9124 ** foreign key.
9125 ** 
9126 ** The following symbolic values are used to record which type
9127 ** of action to take.
9128 */
9129 #define OE_None     0   /* There is no constraint to check */
9130 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9131 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9132 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9133 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9134 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9135
9136 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9137 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9138 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9139 #define OE_Cascade  9   /* Cascade the changes */
9140
9141 #define OE_Default  99  /* Do whatever the default action is */
9142
9143
9144 /*
9145 ** An instance of the following structure is passed as the first
9146 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9147 ** comparison of the two index keys.
9148 */
9149 struct KeyInfo {
9150   sqlite3 *db;        /* The database connection */
9151   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9152   u16 nField;         /* Number of entries in aColl[] */
9153   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9154   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9155 };
9156
9157 /*
9158 ** An instance of the following structure holds information about a
9159 ** single index record that has already been parsed out into individual
9160 ** values.
9161 **
9162 ** A record is an object that contains one or more fields of data.
9163 ** Records are used to store the content of a table row and to store
9164 ** the key of an index.  A blob encoding of a record is created by
9165 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9166 ** OP_Column opcode.
9167 **
9168 ** This structure holds a record that has already been disassembled
9169 ** into its constituent fields.
9170 */
9171 struct UnpackedRecord {
9172   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9173   u16 nField;         /* Number of entries in apMem[] */
9174   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9175   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9176   Mem *aMem;          /* Values */
9177 };
9178
9179 /*
9180 ** Allowed values of UnpackedRecord.flags
9181 */
9182 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9183 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9184 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9185 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9186 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9187 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9188
9189 /*
9190 ** Each SQL index is represented in memory by an
9191 ** instance of the following structure.
9192 **
9193 ** The columns of the table that are to be indexed are described
9194 ** by the aiColumn[] field of this structure.  For example, suppose
9195 ** we have the following table and index:
9196 **
9197 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9198 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9199 **
9200 ** In the Table structure describing Ex1, nCol==3 because there are
9201 ** three columns in the table.  In the Index structure describing
9202 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9203 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9204 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9205 ** The second column to be indexed (c1) has an index of 0 in
9206 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9207 **
9208 ** The Index.onError field determines whether or not the indexed columns
9209 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9210 ** it means this is not a unique index.  Otherwise it is a unique index
9211 ** and the value of Index.onError indicate the which conflict resolution 
9212 ** algorithm to employ whenever an attempt is made to insert a non-unique
9213 ** element.
9214 */
9215 struct Index {
9216   char *zName;     /* Name of this index */
9217   int nColumn;     /* Number of columns in the table used by this index */
9218   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9219   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9220   Table *pTable;   /* The SQL table being indexed */
9221   int tnum;        /* Page containing root of this index in database file */
9222   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9223   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9224   char *zColAff;   /* String defining the affinity of each column */
9225   Index *pNext;    /* The next index associated with the same table */
9226   Schema *pSchema; /* Schema containing this index */
9227   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9228   char **azColl;   /* Array of collation sequence names for index */
9229   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9230 };
9231
9232 /*
9233 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9234 ** using a structure of this type.
9235 */
9236 struct IndexSample {
9237   union {
9238     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9239     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9240   } u;
9241   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9242   u8 nByte;         /* Size in byte of text or blob. */
9243 };
9244
9245 /*
9246 ** Each token coming out of the lexer is an instance of
9247 ** this structure.  Tokens are also used as part of an expression.
9248 **
9249 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9250 ** may contain random values.  Do not make any assumptions about Token.dyn
9251 ** and Token.n when Token.z==0.
9252 */
9253 struct Token {
9254   const char *z;     /* Text of the token.  Not NULL-terminated! */
9255   unsigned int n;    /* Number of characters in this token */
9256 };
9257
9258 /*
9259 ** An instance of this structure contains information needed to generate
9260 ** code for a SELECT that contains aggregate functions.
9261 **
9262 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9263 ** pointer to this structure.  The Expr.iColumn field is the index in
9264 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9265 ** code for that node.
9266 **
9267 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9268 ** original Select structure that describes the SELECT statement.  These
9269 ** fields do not need to be freed when deallocating the AggInfo structure.
9270 */
9271 struct AggInfo {
9272   u8 directMode;          /* Direct rendering mode means take data directly
9273                           ** from source tables rather than from accumulators */
9274   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9275                           ** than the source table */
9276   int sortingIdx;         /* Cursor number of the sorting index */
9277   ExprList *pGroupBy;     /* The group by clause */
9278   int nSortingColumn;     /* Number of columns in the sorting index */
9279   struct AggInfo_col {    /* For each column used in source tables */
9280     Table *pTab;             /* Source table */
9281     int iTable;              /* Cursor number of the source table */
9282     int iColumn;             /* Column number within the source table */
9283     int iSorterColumn;       /* Column number in the sorting index */
9284     int iMem;                /* Memory location that acts as accumulator */
9285     Expr *pExpr;             /* The original expression */
9286   } *aCol;
9287   int nColumn;            /* Number of used entries in aCol[] */
9288   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9289   int nAccumulator;       /* Number of columns that show through to the output.
9290                           ** Additional columns are used only as parameters to
9291                           ** aggregate functions */
9292   struct AggInfo_func {   /* For each aggregate function */
9293     Expr *pExpr;             /* Expression encoding the function */
9294     FuncDef *pFunc;          /* The aggregate function implementation */
9295     int iMem;                /* Memory location that acts as accumulator */
9296     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9297   } *aFunc;
9298   int nFunc;              /* Number of entries in aFunc[] */
9299   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9300 };
9301
9302 /*
9303 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9304 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9305 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9306 ** it uses less memory in the Expr object, which is a big memory user
9307 ** in systems with lots of prepared statements.  And few applications
9308 ** need more than about 10 or 20 variables.  But some extreme users want
9309 ** to have prepared statements with over 32767 variables, and for them
9310 ** the option is available (at compile-time).
9311 */
9312 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9313 typedef i16 ynVar;
9314 #else
9315 typedef int ynVar;
9316 #endif
9317
9318 /*
9319 ** Each node of an expression in the parse tree is an instance
9320 ** of this structure.
9321 **
9322 ** Expr.op is the opcode. The integer parser token codes are reused
9323 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9324 ** code representing the ">=" operator. This same integer code is reused
9325 ** to represent the greater-than-or-equal-to operator in the expression
9326 ** tree.
9327 **
9328 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9329 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9330 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9331 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9332 ** then Expr.token contains the name of the function.
9333 **
9334 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9335 ** binary operator. Either or both may be NULL.
9336 **
9337 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9338 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9339 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9340 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9341 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9342 ** valid.
9343 **
9344 ** An expression of the form ID or ID.ID refers to a column in a table.
9345 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9346 ** the integer cursor number of a VDBE cursor pointing to that table and
9347 ** Expr.iColumn is the column number for the specific column.  If the
9348 ** expression is used as a result in an aggregate SELECT, then the
9349 ** value is also stored in the Expr.iAgg column in the aggregate so that
9350 ** it can be accessed after all aggregates are computed.
9351 **
9352 ** If the expression is an unbound variable marker (a question mark 
9353 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9354 ** number for that variable.
9355 **
9356 ** If the expression is a subquery then Expr.iColumn holds an integer
9357 ** register number containing the result of the subquery.  If the
9358 ** subquery gives a constant result, then iTable is -1.  If the subquery
9359 ** gives a different answer at different times during statement processing
9360 ** then iTable is the address of a subroutine that computes the subquery.
9361 **
9362 ** If the Expr is of type OP_Column, and the table it is selecting from
9363 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9364 ** corresponding table definition.
9365 **
9366 ** ALLOCATION NOTES:
9367 **
9368 ** Expr objects can use a lot of memory space in database schema.  To
9369 ** help reduce memory requirements, sometimes an Expr object will be
9370 ** truncated.  And to reduce the number of memory allocations, sometimes
9371 ** two or more Expr objects will be stored in a single memory allocation,
9372 ** together with Expr.zToken strings.
9373 **
9374 ** If the EP_Reduced and EP_TokenOnly flags are set when
9375 ** an Expr object is truncated.  When EP_Reduced is set, then all
9376 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9377 ** are contained within the same memory allocation.  Note, however, that
9378 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9379 ** allocated, regardless of whether or not EP_Reduced is set.
9380 */
9381 struct Expr {
9382   u8 op;                 /* Operation performed by this node */
9383   char affinity;         /* The affinity of the column or 0 if not a column */
9384   u16 flags;             /* Various flags.  EP_* See below */
9385   union {
9386     char *zToken;          /* Token value. Zero terminated and dequoted */
9387     int iValue;            /* Integer value if EP_IntValue */
9388   } u;
9389
9390   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9391   ** space is allocated for the fields below this point. An attempt to
9392   ** access them will result in a segfault or malfunction. 
9393   *********************************************************************/
9394
9395   Expr *pLeft;           /* Left subnode */
9396   Expr *pRight;          /* Right subnode */
9397   union {
9398     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9399     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9400   } x;
9401   CollSeq *pColl;        /* The collation type of the column or 0 */
9402
9403   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9404   ** space is allocated for the fields below this point. An attempt to
9405   ** access them will result in a segfault or malfunction.
9406   *********************************************************************/
9407
9408   int iTable;            /* TK_COLUMN: cursor number of table holding column
9409                          ** TK_REGISTER: register number
9410                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9411   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9412                          ** TK_VARIABLE: variable number (always >= 1). */
9413   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9414   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9415   u8 flags2;             /* Second set of flags.  EP2_... */
9416   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9417   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9418   Table *pTab;           /* Table for TK_COLUMN expressions. */
9419 #if SQLITE_MAX_EXPR_DEPTH>0
9420   int nHeight;           /* Height of the tree headed by this node */
9421 #endif
9422 };
9423
9424 /*
9425 ** The following are the meanings of bits in the Expr.flags field.
9426 */
9427 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9428 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9429 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9430 #define EP_Error      0x0008  /* Expression contains one or more errors */
9431 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9432 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9433 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9434 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9435 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9436 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9437 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9438 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9439
9440 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9441 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9442 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9443
9444 /*
9445 ** The following are the meanings of bits in the Expr.flags2 field.
9446 */
9447 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9448 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9449
9450 /*
9451 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9452 ** flag on an expression structure.  This flag is used for VV&A only.  The
9453 ** routine is implemented as a macro that only works when in debugging mode,
9454 ** so as not to burden production code.
9455 */
9456 #ifdef SQLITE_DEBUG
9457 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9458 #else
9459 # define ExprSetIrreducible(X)
9460 #endif
9461
9462 /*
9463 ** These macros can be used to test, set, or clear bits in the 
9464 ** Expr.flags field.
9465 */
9466 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9467 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9468 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9469 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9470
9471 /*
9472 ** Macros to determine the number of bytes required by a normal Expr 
9473 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9474 ** and an Expr struct with the EP_TokenOnly flag set.
9475 */
9476 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9477 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9478 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9479
9480 /*
9481 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9482 ** above sqlite3ExprDup() for details.
9483 */
9484 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9485
9486 /*
9487 ** A list of expressions.  Each expression may optionally have a
9488 ** name.  An expr/name combination can be used in several ways, such
9489 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9490 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9491 ** also be used as the argument to a function, in which case the a.zName
9492 ** field is not used.
9493 */
9494 struct ExprList {
9495   int nExpr;             /* Number of expressions on the list */
9496   int nAlloc;            /* Number of entries allocated below */
9497   int iECursor;          /* VDBE Cursor associated with this ExprList */
9498   struct ExprList_item {
9499     Expr *pExpr;           /* The list of expressions */
9500     char *zName;           /* Token associated with this expression */
9501     char *zSpan;           /* Original text of the expression */
9502     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9503     u8 done;               /* A flag to indicate when processing is finished */
9504     u16 iCol;              /* For ORDER BY, column number in result set */
9505     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9506   } *a;                  /* One entry for each expression */
9507 };
9508
9509 /*
9510 ** An instance of this structure is used by the parser to record both
9511 ** the parse tree for an expression and the span of input text for an
9512 ** expression.
9513 */
9514 struct ExprSpan {
9515   Expr *pExpr;          /* The expression parse tree */
9516   const char *zStart;   /* First character of input text */
9517   const char *zEnd;     /* One character past the end of input text */
9518 };
9519
9520 /*
9521 ** An instance of this structure can hold a simple list of identifiers,
9522 ** such as the list "a,b,c" in the following statements:
9523 **
9524 **      INSERT INTO t(a,b,c) VALUES ...;
9525 **      CREATE INDEX idx ON t(a,b,c);
9526 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9527 **
9528 ** The IdList.a.idx field is used when the IdList represents the list of
9529 ** column names after a table name in an INSERT statement.  In the statement
9530 **
9531 **     INSERT INTO t(a,b,c) ...
9532 **
9533 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9534 */
9535 struct IdList {
9536   struct IdList_item {
9537     char *zName;      /* Name of the identifier */
9538     int idx;          /* Index in some Table.aCol[] of a column named zName */
9539   } *a;
9540   int nId;         /* Number of identifiers on the list */
9541   int nAlloc;      /* Number of entries allocated for a[] below */
9542 };
9543
9544 /*
9545 ** The bitmask datatype defined below is used for various optimizations.
9546 **
9547 ** Changing this from a 64-bit to a 32-bit type limits the number of
9548 ** tables in a join to 32 instead of 64.  But it also reduces the size
9549 ** of the library by 738 bytes on ix86.
9550 */
9551 typedef u64 Bitmask;
9552
9553 /*
9554 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9555 */
9556 #define BMS  ((int)(sizeof(Bitmask)*8))
9557
9558 /*
9559 ** The following structure describes the FROM clause of a SELECT statement.
9560 ** Each table or subquery in the FROM clause is a separate element of
9561 ** the SrcList.a[] array.
9562 **
9563 ** With the addition of multiple database support, the following structure
9564 ** can also be used to describe a particular table such as the table that
9565 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9566 ** such a table must be a simple name: ID.  But in SQLite, the table can
9567 ** now be identified by a database name, a dot, then the table name: ID.ID.
9568 **
9569 ** The jointype starts out showing the join type between the current table
9570 ** and the next table on the list.  The parser builds the list this way.
9571 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9572 ** jointype expresses the join between the table and the previous table.
9573 **
9574 ** In the colUsed field, the high-order bit (bit 63) is set if the table
9575 ** contains more than 63 columns and the 64-th or later column is used.
9576 */
9577 struct SrcList {
9578   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9579   i16 nAlloc;      /* Number of entries allocated in a[] below */
9580   struct SrcList_item {
9581     char *zDatabase;  /* Name of database holding this table */
9582     char *zName;      /* Name of the table */
9583     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9584     Table *pTab;      /* An SQL table corresponding to zName */
9585     Select *pSelect;  /* A SELECT statement used in place of a table name */
9586     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9587     u8 jointype;      /* Type of join between this able and the previous */
9588     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9589     int iCursor;      /* The VDBE cursor number used to access this table */
9590     Expr *pOn;        /* The ON clause of a join */
9591     IdList *pUsing;   /* The USING clause of a join */
9592     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9593     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9594     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9595   } a[1];             /* One entry for each identifier on the list */
9596 };
9597
9598 /*
9599 ** Permitted values of the SrcList.a.jointype field
9600 */
9601 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9602 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9603 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9604 #define JT_LEFT      0x0008    /* Left outer join */
9605 #define JT_RIGHT     0x0010    /* Right outer join */
9606 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9607 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9608
9609
9610 /*
9611 ** A WherePlan object holds information that describes a lookup
9612 ** strategy.
9613 **
9614 ** This object is intended to be opaque outside of the where.c module.
9615 ** It is included here only so that that compiler will know how big it
9616 ** is.  None of the fields in this object should be used outside of
9617 ** the where.c module.
9618 **
9619 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9620 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9621 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9622 ** case that more than one of these conditions is true.
9623 */
9624 struct WherePlan {
9625   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9626   u32 nEq;                       /* Number of == constraints */
9627   union {
9628     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9629     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9630     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9631   } u;
9632 };
9633
9634 /*
9635 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9636 ** structure contains a single instance of this structure.  This structure
9637 ** is intended to be private the the where.c module and should not be
9638 ** access or modified by other modules.
9639 **
9640 ** The pIdxInfo field is used to help pick the best index on a
9641 ** virtual table.  The pIdxInfo pointer contains indexing
9642 ** information for the i-th table in the FROM clause before reordering.
9643 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9644 ** All other information in the i-th WhereLevel object for the i-th table
9645 ** after FROM clause ordering.
9646 */
9647 struct WhereLevel {
9648   WherePlan plan;       /* query plan for this element of the FROM clause */
9649   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9650   int iTabCur;          /* The VDBE cursor used to access the table */
9651   int iIdxCur;          /* The VDBE cursor used to access pIdx */
9652   int addrBrk;          /* Jump here to break out of the loop */
9653   int addrNxt;          /* Jump here to start the next IN combination */
9654   int addrCont;         /* Jump here to continue with the next loop cycle */
9655   int addrFirst;        /* First instruction of interior of the loop */
9656   u8 iFrom;             /* Which entry in the FROM clause */
9657   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9658   int p1, p2;           /* Operands of the opcode used to ends the loop */
9659   union {               /* Information that depends on plan.wsFlags */
9660     struct {
9661       int nIn;              /* Number of entries in aInLoop[] */
9662       struct InLoop {
9663         int iCur;              /* The VDBE cursor used by this IN operator */
9664         int addrInTop;         /* Top of the IN loop */
9665       } *aInLoop;           /* Information about each nested IN operator */
9666     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9667   } u;
9668
9669   /* The following field is really not part of the current level.  But
9670   ** we need a place to cache virtual table index information for each
9671   ** virtual table in the FROM clause and the WhereLevel structure is
9672   ** a convenient place since there is one WhereLevel for each FROM clause
9673   ** element.
9674   */
9675   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9676 };
9677
9678 /*
9679 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9680 ** and the WhereInfo.wctrlFlags member.
9681 */
9682 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9683 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9684 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9685 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9686 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9687 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9688 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9689 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9690 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9691
9692 /*
9693 ** The WHERE clause processing routine has two halves.  The
9694 ** first part does the start of the WHERE loop and the second
9695 ** half does the tail of the WHERE loop.  An instance of
9696 ** this structure is returned by the first half and passed
9697 ** into the second half to give some continuity.
9698 */
9699 struct WhereInfo {
9700   Parse *pParse;       /* Parsing and code generating context */
9701   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9702   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9703   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9704   SrcList *pTabList;             /* List of tables in the join */
9705   int iTop;                      /* The very beginning of the WHERE loop */
9706   int iContinue;                 /* Jump here to continue with next record */
9707   int iBreak;                    /* Jump here to break out of the loop */
9708   int nLevel;                    /* Number of nested loop */
9709   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9710   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
9711   WhereLevel a[1];               /* Information about each nest loop in WHERE */
9712 };
9713
9714 /*
9715 ** A NameContext defines a context in which to resolve table and column
9716 ** names.  The context consists of a list of tables (the pSrcList) field and
9717 ** a list of named expression (pEList).  The named expression list may
9718 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9719 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9720 ** pEList corresponds to the result set of a SELECT and is NULL for
9721 ** other statements.
9722 **
9723 ** NameContexts can be nested.  When resolving names, the inner-most 
9724 ** context is searched first.  If no match is found, the next outer
9725 ** context is checked.  If there is still no match, the next context
9726 ** is checked.  This process continues until either a match is found
9727 ** or all contexts are check.  When a match is found, the nRef member of
9728 ** the context containing the match is incremented. 
9729 **
9730 ** Each subquery gets a new NameContext.  The pNext field points to the
9731 ** NameContext in the parent query.  Thus the process of scanning the
9732 ** NameContext list corresponds to searching through successively outer
9733 ** subqueries looking for a match.
9734 */
9735 struct NameContext {
9736   Parse *pParse;       /* The parser */
9737   SrcList *pSrcList;   /* One or more tables used to resolve names */
9738   ExprList *pEList;    /* Optional list of named expressions */
9739   int nRef;            /* Number of names resolved by this context */
9740   int nErr;            /* Number of errors encountered while resolving names */
9741   u8 allowAgg;         /* Aggregate functions allowed here */
9742   u8 hasAgg;           /* True if aggregates are seen */
9743   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9744   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9745   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9746   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9747 };
9748
9749 /*
9750 ** An instance of the following structure contains all information
9751 ** needed to generate code for a single SELECT statement.
9752 **
9753 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9754 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9755 ** limit and nOffset to the value of the offset (or 0 if there is not
9756 ** offset).  But later on, nLimit and nOffset become the memory locations
9757 ** in the VDBE that record the limit and offset counters.
9758 **
9759 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9760 ** These addresses must be stored so that we can go back and fill in
9761 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9762 ** the number of columns in P2 can be computed at the same time
9763 ** as the OP_OpenEphm instruction is coded because not
9764 ** enough information about the compound query is known at that point.
9765 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9766 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9767 ** sequences for the ORDER BY clause.
9768 */
9769 struct Select {
9770   ExprList *pEList;      /* The fields of the result */
9771   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9772   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9773   u16 selFlags;          /* Various SF_* values */
9774   SrcList *pSrc;         /* The FROM clause */
9775   Expr *pWhere;          /* The WHERE clause */
9776   ExprList *pGroupBy;    /* The GROUP BY clause */
9777   Expr *pHaving;         /* The HAVING clause */
9778   ExprList *pOrderBy;    /* The ORDER BY clause */
9779   Select *pPrior;        /* Prior select in a compound select statement */
9780   Select *pNext;         /* Next select to the left in a compound */
9781   Select *pRightmost;    /* Right-most select in a compound select statement */
9782   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9783   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9784   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9785   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9786 };
9787
9788 /*
9789 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9790 ** "Select Flag".
9791 */
9792 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9793 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9794 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9795 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9796 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9797 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9798
9799
9800 /*
9801 ** The results of a select can be distributed in several ways.  The
9802 ** "SRT" prefix means "SELECT Result Type".
9803 */
9804 #define SRT_Union        1  /* Store result as keys in an index */
9805 #define SRT_Except       2  /* Remove result from a UNION index */
9806 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9807 #define SRT_Discard      4  /* Do not save the results anywhere */
9808
9809 /* The ORDER BY clause is ignored for all of the above */
9810 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9811
9812 #define SRT_Output       5  /* Output each row of result */
9813 #define SRT_Mem          6  /* Store result in a memory cell */
9814 #define SRT_Set          7  /* Store results as keys in an index */
9815 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9816 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9817 #define SRT_Coroutine   10  /* Generate a single row of result */
9818
9819 /*
9820 ** A structure used to customize the behavior of sqlite3Select(). See
9821 ** comments above sqlite3Select() for details.
9822 */
9823 typedef struct SelectDest SelectDest;
9824 struct SelectDest {
9825   u8 eDest;         /* How to dispose of the results */
9826   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9827   int iParm;        /* A parameter used by the eDest disposal method */
9828   int iMem;         /* Base register where results are written */
9829   int nMem;         /* Number of registers allocated */
9830 };
9831
9832 /*
9833 ** During code generation of statements that do inserts into AUTOINCREMENT 
9834 ** tables, the following information is attached to the Table.u.autoInc.p
9835 ** pointer of each autoincrement table to record some side information that
9836 ** the code generator needs.  We have to keep per-table autoincrement
9837 ** information in case inserts are down within triggers.  Triggers do not
9838 ** normally coordinate their activities, but we do need to coordinate the
9839 ** loading and saving of autoincrement information.
9840 */
9841 struct AutoincInfo {
9842   AutoincInfo *pNext;   /* Next info block in a list of them all */
9843   Table *pTab;          /* Table this info block refers to */
9844   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9845   int regCtr;           /* Memory register holding the rowid counter */
9846 };
9847
9848 /*
9849 ** Size of the column cache
9850 */
9851 #ifndef SQLITE_N_COLCACHE
9852 # define SQLITE_N_COLCACHE 10
9853 #endif
9854
9855 /*
9856 ** At least one instance of the following structure is created for each 
9857 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9858 ** statement. All such objects are stored in the linked list headed at
9859 ** Parse.pTriggerPrg and deleted once statement compilation has been
9860 ** completed.
9861 **
9862 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
9863 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9864 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9865 ** The Parse.pTriggerPrg list never contains two entries with the same
9866 ** values for both pTrigger and orconf.
9867 **
9868 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9869 ** accessed (or set to 0 for triggers fired as a result of INSERT 
9870 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9871 ** a mask of new.* columns used by the program.
9872 */
9873 struct TriggerPrg {
9874   Trigger *pTrigger;      /* Trigger this program was coded from */
9875   int orconf;             /* Default ON CONFLICT policy */
9876   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9877   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9878   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9879 };
9880
9881 /*
9882 ** An SQL parser context.  A copy of this structure is passed through
9883 ** the parser and down into all the parser action routine in order to
9884 ** carry around information that is global to the entire parse.
9885 **
9886 ** The structure is divided into two parts.  When the parser and code
9887 ** generate call themselves recursively, the first part of the structure
9888 ** is constant but the second part is reset at the beginning and end of
9889 ** each recursion.
9890 **
9891 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9892 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9893 ** used to store the set of table-locks required by the statement being
9894 ** compiled. Function sqlite3TableLock() is used to add entries to the
9895 ** list.
9896 */
9897 struct Parse {
9898   sqlite3 *db;         /* The main database structure */
9899   int rc;              /* Return code from execution */
9900   char *zErrMsg;       /* An error message */
9901   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9902   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9903   u8 nameClash;        /* A permanent table name clashes with temp table name */
9904   u8 checkSchema;      /* Causes schema cookie check after an error */
9905   u8 nested;           /* Number of nested calls to the parser/code generator */
9906   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9907   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9908   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9909   int aTempReg[8];     /* Holding area for temporary registers */
9910   int nRangeReg;       /* Size of the temporary register block */
9911   int iRangeReg;       /* First register in temporary register block */
9912   int nErr;            /* Number of errors seen */
9913   int nTab;            /* Number of previously allocated VDBE cursors */
9914   int nMem;            /* Number of memory cells used so far */
9915   int nSet;            /* Number of sets used so far */
9916   int ckBase;          /* Base register of data during check constraints */
9917   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9918   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9919   u8 nColCache;        /* Number of entries in the column cache */
9920   u8 iColCache;        /* Next entry of the cache to replace */
9921   struct yColCache {
9922     int iTable;           /* Table cursor number */
9923     int iColumn;          /* Table column number */
9924     u8 tempReg;           /* iReg is a temp register that needs to be freed */
9925     int iLevel;           /* Nesting level */
9926     int iReg;             /* Reg with value of this column. 0 means none. */
9927     int lru;              /* Least recently used entry has the smallest value */
9928   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9929   u32 writeMask;       /* Start a write transaction on these databases */
9930   u32 cookieMask;      /* Bitmask of schema verified databases */
9931   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9932   u8 mayAbort;         /* True if statement may throw an ABORT exception */
9933   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9934   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9935 #ifndef SQLITE_OMIT_SHARED_CACHE
9936   int nTableLock;        /* Number of locks in aTableLock */
9937   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9938 #endif
9939   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9940   int regRoot;         /* Register holding root page number for new objects */
9941   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9942   int nMaxArg;         /* Max args passed to user function by sub-program */
9943
9944   /* Information used while coding trigger programs. */
9945   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9946   Table *pTriggerTab;  /* Table triggers are being coded for */
9947   u32 oldmask;         /* Mask of old.* columns referenced */
9948   u32 newmask;         /* Mask of new.* columns referenced */
9949   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9950   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9951   u8 disableTriggers;  /* True to disable triggers */
9952   double nQueryLoop;   /* Estimated number of iterations of a query */
9953
9954   /* Above is constant between recursions.  Below is reset before and after
9955   ** each recursion */
9956
9957   int nVar;            /* Number of '?' variables seen in the SQL so far */
9958   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9959   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9960   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9961   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9962   int nAlias;          /* Number of aliased result set columns */
9963   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9964   int *aAlias;         /* Register used to hold aliased result */
9965   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9966   Token sNameToken;    /* Token with unqualified schema object name */
9967   Token sLastToken;    /* The last token parsed */
9968   const char *zTail;   /* All SQL text past the last semicolon parsed */
9969   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9970   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9971   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9972 #ifndef SQLITE_OMIT_VIRTUALTABLE
9973   Token sArg;                /* Complete text of a module argument */
9974   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9975   int nVtabLock;             /* Number of virtual tables to lock */
9976   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9977 #endif
9978   int nHeight;            /* Expression tree height of current sub-select */
9979   Table *pZombieTab;      /* List of Table objects to delete after code gen */
9980   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9981 };
9982
9983 #ifdef SQLITE_OMIT_VIRTUALTABLE
9984   #define IN_DECLARE_VTAB 0
9985 #else
9986   #define IN_DECLARE_VTAB (pParse->declareVtab)
9987 #endif
9988
9989 /*
9990 ** An instance of the following structure can be declared on a stack and used
9991 ** to save the Parse.zAuthContext value so that it can be restored later.
9992 */
9993 struct AuthContext {
9994   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9995   Parse *pParse;              /* The Parse structure */
9996 };
9997
9998 /*
9999 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10000 */
10001 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10002 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10003 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10004 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10005 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10006 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10007
10008 /*
10009  * Each trigger present in the database schema is stored as an instance of
10010  * struct Trigger. 
10011  *
10012  * Pointers to instances of struct Trigger are stored in two ways.
10013  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10014  *    database). This allows Trigger structures to be retrieved by name.
10015  * 2. All triggers associated with a single table form a linked list, using the
10016  *    pNext member of struct Trigger. A pointer to the first element of the
10017  *    linked list is stored as the "pTrigger" member of the associated
10018  *    struct Table.
10019  *
10020  * The "step_list" member points to the first element of a linked list
10021  * containing the SQL statements specified as the trigger program.
10022  */
10023 struct Trigger {
10024   char *zName;            /* The name of the trigger                        */
10025   char *table;            /* The table or view to which the trigger applies */
10026   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10027   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10028   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10029   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10030                              the <column-list> is stored here */
10031   Schema *pSchema;        /* Schema containing the trigger */
10032   Schema *pTabSchema;     /* Schema containing the table */
10033   TriggerStep *step_list; /* Link list of trigger program steps             */
10034   Trigger *pNext;         /* Next trigger associated with the table */
10035 };
10036
10037 /*
10038 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10039 ** determine which. 
10040 **
10041 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10042 ** In that cases, the constants below can be ORed together.
10043 */
10044 #define TRIGGER_BEFORE  1
10045 #define TRIGGER_AFTER   2
10046
10047 /*
10048  * An instance of struct TriggerStep is used to store a single SQL statement
10049  * that is a part of a trigger-program. 
10050  *
10051  * Instances of struct TriggerStep are stored in a singly linked list (linked
10052  * using the "pNext" member) referenced by the "step_list" member of the 
10053  * associated struct Trigger instance. The first element of the linked list is
10054  * the first step of the trigger-program.
10055  * 
10056  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10057  * "SELECT" statement. The meanings of the other members is determined by the 
10058  * value of "op" as follows:
10059  *
10060  * (op == TK_INSERT)
10061  * orconf    -> stores the ON CONFLICT algorithm
10062  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10063  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10064  * target    -> A token holding the quoted name of the table to insert into.
10065  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10066  *              this stores values to be inserted. Otherwise NULL.
10067  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10068  *              statement, then this stores the column-names to be
10069  *              inserted into.
10070  *
10071  * (op == TK_DELETE)
10072  * target    -> A token holding the quoted name of the table to delete from.
10073  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10074  *              Otherwise NULL.
10075  * 
10076  * (op == TK_UPDATE)
10077  * target    -> A token holding the quoted name of the table to update rows of.
10078  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10079  *              Otherwise NULL.
10080  * pExprList -> A list of the columns to update and the expressions to update
10081  *              them to. See sqlite3Update() documentation of "pChanges"
10082  *              argument.
10083  * 
10084  */
10085 struct TriggerStep {
10086   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10087   u8 orconf;           /* OE_Rollback etc. */
10088   Trigger *pTrig;      /* The trigger that this step is a part of */
10089   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10090   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10091   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10092   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10093   IdList *pIdList;     /* Column names for INSERT */
10094   TriggerStep *pNext;  /* Next in the link-list */
10095   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10096 };
10097
10098 /*
10099 ** The following structure contains information used by the sqliteFix...
10100 ** routines as they walk the parse tree to make database references
10101 ** explicit.  
10102 */
10103 typedef struct DbFixer DbFixer;
10104 struct DbFixer {
10105   Parse *pParse;      /* The parsing context.  Error messages written here */
10106   const char *zDb;    /* Make sure all objects are contained in this database */
10107   const char *zType;  /* Type of the container - used for error messages */
10108   const Token *pName; /* Name of the container - used for error messages */
10109 };
10110
10111 /*
10112 ** An objected used to accumulate the text of a string where we
10113 ** do not necessarily know how big the string will be in the end.
10114 */
10115 struct StrAccum {
10116   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10117   char *zBase;         /* A base allocation.  Not from malloc. */
10118   char *zText;         /* The string collected so far */
10119   int  nChar;          /* Length of the string so far */
10120   int  nAlloc;         /* Amount of space allocated in zText */
10121   int  mxAlloc;        /* Maximum allowed string length */
10122   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10123   u8   useMalloc;      /* True if zText is enlargeable using realloc */
10124   u8   tooBig;         /* Becomes true if string size exceeds limits */
10125 };
10126
10127 /*
10128 ** A pointer to this structure is used to communicate information
10129 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10130 */
10131 typedef struct {
10132   sqlite3 *db;        /* The database being initialized */
10133   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10134   char **pzErrMsg;    /* Error message stored here */
10135   int rc;             /* Result code stored here */
10136 } InitData;
10137
10138 /*
10139 ** Structure containing global configuration data for the SQLite library.
10140 **
10141 ** This structure also contains some state information.
10142 */
10143 struct Sqlite3Config {
10144   int bMemstat;                     /* True to enable memory status */
10145   int bCoreMutex;                   /* True to enable core mutexing */
10146   int bFullMutex;                   /* True to enable full mutexing */
10147   int mxStrlen;                     /* Maximum string length */
10148   int szLookaside;                  /* Default lookaside buffer size */
10149   int nLookaside;                   /* Default lookaside buffer count */
10150   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10151   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10152   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10153   void *pHeap;                      /* Heap storage space */
10154   int nHeap;                        /* Size of pHeap[] */
10155   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10156   void *pScratch;                   /* Scratch memory */
10157   int szScratch;                    /* Size of each scratch buffer */
10158   int nScratch;                     /* Number of scratch buffers */
10159   void *pPage;                      /* Page cache memory */
10160   int szPage;                       /* Size of each page in pPage[] */
10161   int nPage;                        /* Number of pages in pPage[] */
10162   int mxParserStack;                /* maximum depth of the parser stack */
10163   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10164   /* The above might be initialized to non-zero.  The following need to always
10165   ** initially be zero, however. */
10166   int isInit;                       /* True after initialization has finished */
10167   int inProgress;                   /* True while initialization in progress */
10168   int isMutexInit;                  /* True after mutexes are initialized */
10169   int isMallocInit;                 /* True after malloc is initialized */
10170   int isPCacheInit;                 /* True after malloc is initialized */
10171   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10172   int nRefInitMutex;                /* Number of users of pInitMutex */
10173   void (*xLog)(void*,int,const char*); /* Function for logging */
10174   void *pLogArg;                       /* First argument to xLog() */
10175 };
10176
10177 /*
10178 ** Context pointer passed down through the tree-walk.
10179 */
10180 struct Walker {
10181   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10182   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10183   Parse *pParse;                            /* Parser context.  */
10184   union {                                   /* Extra data for callback */
10185     NameContext *pNC;                          /* Naming context */
10186     int i;                                     /* Integer value */
10187   } u;
10188 };
10189
10190 /* Forward declarations */
10191 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10192 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10193 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10194 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10195 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10196
10197 /*
10198 ** Return code from the parse-tree walking primitives and their
10199 ** callbacks.
10200 */
10201 #define WRC_Continue    0   /* Continue down into children */
10202 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10203 #define WRC_Abort       2   /* Abandon the tree walk */
10204
10205 /*
10206 ** Assuming zIn points to the first byte of a UTF-8 character,
10207 ** advance zIn to point to the first byte of the next UTF-8 character.
10208 */
10209 #define SQLITE_SKIP_UTF8(zIn) {                        \
10210   if( (*(zIn++))>=0xc0 ){                              \
10211     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10212   }                                                    \
10213 }
10214
10215 /*
10216 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10217 ** the same name but without the _BKPT suffix.  These macros invoke
10218 ** routines that report the line-number on which the error originated
10219 ** using sqlite3_log().  The routines also provide a convenient place
10220 ** to set a debugger breakpoint.
10221 */
10222 SQLITE_PRIVATE int sqlite3CorruptError(int);
10223 SQLITE_PRIVATE int sqlite3MisuseError(int);
10224 SQLITE_PRIVATE int sqlite3CantopenError(int);
10225 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10226 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10227 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10228
10229
10230 /*
10231 ** FTS4 is really an extension for FTS3.  It is enabled using the
10232 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10233 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10234 */
10235 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10236 # define SQLITE_ENABLE_FTS3
10237 #endif
10238
10239 /*
10240 ** The ctype.h header is needed for non-ASCII systems.  It is also
10241 ** needed by FTS3 when FTS3 is included in the amalgamation.
10242 */
10243 #if !defined(SQLITE_ASCII) || \
10244     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10245 # include <ctype.h>
10246 #endif
10247
10248 /*
10249 ** The following macros mimic the standard library functions toupper(),
10250 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10251 ** sqlite versions only work for ASCII characters, regardless of locale.
10252 */
10253 #ifdef SQLITE_ASCII
10254 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10255 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10256 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10257 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10258 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10259 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10260 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10261 #else
10262 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10263 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10264 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10265 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10266 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10267 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10268 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10269 #endif
10270
10271 /*
10272 ** Internal function prototypes
10273 */
10274 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10275 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10276 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10277 #define sqlite3StrNICmp sqlite3_strnicmp
10278
10279 SQLITE_PRIVATE int sqlite3MallocInit(void);
10280 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10281 SQLITE_PRIVATE void *sqlite3Malloc(int);
10282 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10283 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10284 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10285 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10286 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10287 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10288 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10289 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10290 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10291 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10292 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10293 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10294 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10295 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10296 SQLITE_PRIVATE void sqlite3PageFree(void*);
10297 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10298 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10299 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10300
10301 /*
10302 ** On systems with ample stack space and that support alloca(), make
10303 ** use of alloca() to obtain space for large automatic objects.  By default,
10304 ** obtain space from malloc().
10305 **
10306 ** The alloca() routine never returns NULL.  This will cause code paths
10307 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10308 */
10309 #ifdef SQLITE_USE_ALLOCA
10310 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10311 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10312 # define sqlite3StackFree(D,P)       
10313 #else
10314 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10315 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10316 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10317 #endif
10318
10319 #ifdef SQLITE_ENABLE_MEMSYS3
10320 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10321 #endif
10322 #ifdef SQLITE_ENABLE_MEMSYS5
10323 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10324 #endif
10325
10326
10327 #ifndef SQLITE_MUTEX_OMIT
10328 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10329 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10330 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10331 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10332 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10333 #endif
10334
10335 SQLITE_PRIVATE int sqlite3StatusValue(int);
10336 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10337 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10338
10339 #ifndef SQLITE_OMIT_FLOATING_POINT
10340 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10341 #else
10342 # define sqlite3IsNaN(X)  0
10343 #endif
10344
10345 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10346 #ifndef SQLITE_OMIT_TRACE
10347 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10348 #endif
10349 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10350 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10351 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10352 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10353 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10354 #endif
10355 #if defined(SQLITE_TEST)
10356 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10357 #endif
10358 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10359 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10360 SQLITE_PRIVATE int sqlite3Dequote(char*);
10361 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10362 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10363 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10364 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10365 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10366 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10367 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10368 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10369 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10370 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10371 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10372 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10373 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10374 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10375 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10376 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10377 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10378 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10379 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10380 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10381 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10382 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10383 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10384 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10385 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10386 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10387 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10388 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10389 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10390 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10391 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10392 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10393 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10394 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10395 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10396 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10397
10398 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10399 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10400 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10401 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10402 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10403 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10404 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10405
10406 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10407 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10408 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10409 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10410 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10411
10412 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10413
10414 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10415 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10416 #else
10417 # define sqlite3ViewGetColumnNames(A,B) 0
10418 #endif
10419
10420 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10421 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10422 #ifndef SQLITE_OMIT_AUTOINCREMENT
10423 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10424 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10425 #else
10426 # define sqlite3AutoincrementBegin(X)
10427 # define sqlite3AutoincrementEnd(X)
10428 #endif
10429 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10430 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10431 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10432 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10433 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10434 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10435 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10436                                       Token*, Select*, Expr*, IdList*);
10437 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10438 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10439 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10440 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10441 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10442 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10443 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10444                         Token*, int, int);
10445 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10446 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10447 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10448                          Expr*,ExprList*,int,Expr*,Expr*);
10449 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10450 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10451 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10452 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10453 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10454 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10455 #endif
10456 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10457 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10458 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10459 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10460 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10461 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10462 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10463 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10464 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10465 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10466 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10467 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10468 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10469 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10470 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10471 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10472 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10473 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10474 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10475 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10476 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10477 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10478 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10479 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10480 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10481 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10482 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10483 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10484 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10485 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10486 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10487 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10488 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10489 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10490 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10491 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10492 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10493 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10494 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10495 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10496 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10497 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10498 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10499 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10500 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10501 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10502 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10503 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10504 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10505 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10506 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10507 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10508 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10509 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10510 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10511 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10512 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10513 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10514                                      int*,int,int,int,int,int*);
10515 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10516 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10517 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10518 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10519 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10520 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10521 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10522 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10523 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10524 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10525 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10526 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10527 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10528 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10529 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10530 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10531 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10532 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10533 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10534
10535 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10536 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10537 #endif
10538
10539 #ifndef SQLITE_OMIT_TRIGGER
10540 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10541                            Expr*,int, int);
10542 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10543 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10544 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10545 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10546 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10547 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10548                             int, int, int);
10549 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10550   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10551 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10552 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10553 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10554                                         ExprList*,Select*,u8);
10555 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10556 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10557 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10558 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10559 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10560 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10561 #else
10562 # define sqlite3TriggersExist(B,C,D,E,F) 0
10563 # define sqlite3DeleteTrigger(A,B)
10564 # define sqlite3DropTriggerPtr(A,B)
10565 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10566 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10567 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10568 # define sqlite3TriggerList(X, Y) 0
10569 # define sqlite3ParseToplevel(p) p
10570 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10571 #endif
10572
10573 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10574 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10575 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10576 #ifndef SQLITE_OMIT_AUTHORIZATION
10577 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10578 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10579 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10580 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10581 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10582 #else
10583 # define sqlite3AuthRead(a,b,c,d)
10584 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10585 # define sqlite3AuthContextPush(a,b,c)
10586 # define sqlite3AuthContextPop(a)  ((void)(a))
10587 #endif
10588 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10589 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10590 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10591                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10592 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10593 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10594 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10595 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10596 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10597 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10598 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10599 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10600 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10601 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10602 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10603 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10604
10605 /*
10606 ** Routines to read and write variable-length integers.  These used to
10607 ** be defined locally, but now we use the varint routines in the util.c
10608 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10609 ** are coded to assume the single byte case is already handled (which 
10610 ** the MACRO form does).
10611 */
10612 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10613 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10614 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10615 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10616 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10617
10618 /*
10619 ** The header of a record consists of a sequence variable-length integers.
10620 ** These integers are almost always small and are encoded as a single byte.
10621 ** The following macros take advantage this fact to provide a fast encode
10622 ** and decode of the integers in a record header.  It is faster for the common
10623 ** case where the integer is a single byte.  It is a little slower when the
10624 ** integer is two or more bytes.  But overall it is faster.
10625 **
10626 ** The following expressions are equivalent:
10627 **
10628 **     x = sqlite3GetVarint32( A, &B );
10629 **     x = sqlite3PutVarint32( A, B );
10630 **
10631 **     x = getVarint32( A, B );
10632 **     x = putVarint32( A, B );
10633 **
10634 */
10635 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10636 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10637 #define getVarint    sqlite3GetVarint
10638 #define putVarint    sqlite3PutVarint
10639
10640
10641 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10642 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10643 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10644 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10645 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10646 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10647 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10648 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10649 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10650 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10651 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10652 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10653 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10654 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10655 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10656 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10657 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10658 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10659
10660 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10661 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10662 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10663                         void(*)(void*));
10664 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10665 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10666 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10667 #ifdef SQLITE_ENABLE_STAT2
10668 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10669 #endif
10670 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10671 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10672 #ifndef SQLITE_AMALGAMATION
10673 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10674 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10675 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10676 SQLITE_PRIVATE const Token sqlite3IntTokens[];
10677 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10678 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10679 #ifndef SQLITE_OMIT_WSD
10680 SQLITE_PRIVATE int sqlite3PendingByte;
10681 #endif
10682 #endif
10683 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10684 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10685 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10686 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10687 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10688 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10689 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10690 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10691 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10692 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10693 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10694 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10695 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10696 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10697 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10698 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10699 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10700 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10701 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10702 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10703 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10704 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10705 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10706 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10707 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10708 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10709 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10710 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10711 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10712 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10713 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10714 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10715   void (*)(sqlite3_context*,int,sqlite3_value **),
10716   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10717 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10718 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10719
10720 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10721 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10722 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10723 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10724 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10725 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10726
10727 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10728 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10729
10730 /*
10731 ** The interface to the LEMON-generated parser
10732 */
10733 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10734 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10735 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10736 #ifdef YYTRACKMAXSTACKDEPTH
10737 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10738 #endif
10739
10740 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10741 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10742 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10743 #else
10744 # define sqlite3CloseExtensions(X)
10745 #endif
10746
10747 #ifndef SQLITE_OMIT_SHARED_CACHE
10748 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10749 #else
10750   #define sqlite3TableLock(v,w,x,y,z)
10751 #endif
10752
10753 #ifdef SQLITE_TEST
10754 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10755 #endif
10756
10757 #ifdef SQLITE_OMIT_VIRTUALTABLE
10758 #  define sqlite3VtabClear(Y)
10759 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10760 #  define sqlite3VtabRollback(X)
10761 #  define sqlite3VtabCommit(X)
10762 #  define sqlite3VtabInSync(db) 0
10763 #  define sqlite3VtabLock(X) 
10764 #  define sqlite3VtabUnlock(X)
10765 #  define sqlite3VtabUnlockList(X)
10766 #else
10767 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10768 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10769 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10770 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10771 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10772 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10773 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10774 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10775 #endif
10776 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10777 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10778 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10779 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10780 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10781 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10782 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10783 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10784 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10785 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10786 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10787 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10788 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10789 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10790 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10791 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10792 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10793 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10794 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
10795 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
10796 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
10797
10798 /* Declarations for functions in fkey.c. All of these are replaced by
10799 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10800 ** key functionality is available. If OMIT_TRIGGER is defined but
10801 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10802 ** this case foreign keys are parsed, but no other functionality is 
10803 ** provided (enforcement of FK constraints requires the triggers sub-system).
10804 */
10805 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10806 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10807 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10808 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10809 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10810 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10811 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10812 #else
10813   #define sqlite3FkActions(a,b,c,d)
10814   #define sqlite3FkCheck(a,b,c,d)
10815   #define sqlite3FkDropTable(a,b,c)
10816   #define sqlite3FkOldmask(a,b)      0
10817   #define sqlite3FkRequired(a,b,c,d) 0
10818 #endif
10819 #ifndef SQLITE_OMIT_FOREIGN_KEY
10820 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10821 #else
10822   #define sqlite3FkDelete(a)
10823 #endif
10824
10825
10826 /*
10827 ** Available fault injectors.  Should be numbered beginning with 0.
10828 */
10829 #define SQLITE_FAULTINJECTOR_MALLOC     0
10830 #define SQLITE_FAULTINJECTOR_COUNT      1
10831
10832 /*
10833 ** The interface to the code in fault.c used for identifying "benign"
10834 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10835 ** is not defined.
10836 */
10837 #ifndef SQLITE_OMIT_BUILTIN_TEST
10838 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10839 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10840 #else
10841   #define sqlite3BeginBenignMalloc()
10842   #define sqlite3EndBenignMalloc()
10843 #endif
10844
10845 #define IN_INDEX_ROWID           1
10846 #define IN_INDEX_EPH             2
10847 #define IN_INDEX_INDEX           3
10848 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10849
10850 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10851 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10852 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10853 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10854 #else
10855   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10856 #endif
10857
10858 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10859 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10860 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10861
10862 #if SQLITE_MAX_EXPR_DEPTH>0
10863 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10864 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10865 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10866 #else
10867   #define sqlite3ExprSetHeight(x,y)
10868   #define sqlite3SelectExprHeight(x) 0
10869   #define sqlite3ExprCheckHeight(x,y)
10870 #endif
10871
10872 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10873 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10874
10875 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10876 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10877 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10878 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10879 #else
10880   #define sqlite3ConnectionBlocked(x,y)
10881   #define sqlite3ConnectionUnlocked(x)
10882   #define sqlite3ConnectionClosed(x)
10883 #endif
10884
10885 #ifdef SQLITE_DEBUG
10886 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10887 #endif
10888
10889 /*
10890 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10891 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10892 ** print I/O tracing messages. 
10893 */
10894 #ifdef SQLITE_ENABLE_IOTRACE
10895 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10896 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10897 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10898 #else
10899 # define IOTRACE(A)
10900 # define sqlite3VdbeIOTraceSql(X)
10901 #endif
10902
10903 /*
10904 ** These routines are available for the mem2.c debugging memory allocator
10905 ** only.  They are used to verify that different "types" of memory
10906 ** allocations are properly tracked by the system.
10907 **
10908 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
10909 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
10910 ** a single bit set.
10911 **
10912 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
10913 ** argument match the type set by the previous sqlite3MemdebugSetType().
10914 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
10915 ** For example:
10916 **
10917 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
10918 **
10919 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
10920 ** and MEMTYPE_DB.  If an allocation is MEMTYPE_DB, that means it might have
10921 ** been allocated by lookaside, except the allocation was too large or
10922 ** lookaside was already full.  It is important to verify that allocations
10923 ** that might have been satisfied by lookaside are not passed back to 
10924 ** non-lookaside free() routines.  Asserts such as the example above are
10925 ** placed on the non-lookaside free() routines to verify this constraint. 
10926 **
10927 ** All of this is no-op for a production build.  It only comes into
10928 ** play when the SQLITE_MEMDEBUG compile-time option is used.
10929 */
10930 #ifdef SQLITE_MEMDEBUG
10931 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
10932 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
10933 #else
10934 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
10935 # define sqlite3MemdebugHasType(X,Y)  1
10936 #endif
10937 #define MEMTYPE_HEAP     0x01    /* General heap allocations */
10938 #define MEMTYPE_DB       0x02    /* Associated with a database connection */
10939 #define MEMTYPE_SCRATCH  0x04    /* Scratch allocations */
10940 #define MEMTYPE_PCACHE   0x08    /* Page cache allocations */
10941
10942 #endif /* _SQLITEINT_H_ */
10943
10944 /************** End of sqliteInt.h *******************************************/
10945 /************** Begin file global.c ******************************************/
10946 /*
10947 ** 2008 June 13
10948 **
10949 ** The author disclaims copyright to this source code.  In place of
10950 ** a legal notice, here is a blessing:
10951 **
10952 **    May you do good and not evil.
10953 **    May you find forgiveness for yourself and forgive others.
10954 **    May you share freely, never taking more than you give.
10955 **
10956 *************************************************************************
10957 **
10958 ** This file contains definitions of global variables and contants.
10959 */
10960
10961 /* An array to map all upper-case characters into their corresponding
10962 ** lower-case character. 
10963 **
10964 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10965 ** handle case conversions for the UTF character set since the tables
10966 ** involved are nearly as big or bigger than SQLite itself.
10967 */
10968 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10969 #ifdef SQLITE_ASCII
10970       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10971      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10972      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10973      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10974     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10975     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10976     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10977     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10978     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10979     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10980     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10981     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10982     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10983     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10984     252,253,254,255
10985 #endif
10986 #ifdef SQLITE_EBCDIC
10987       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10988      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10989      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10990      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10991      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10992      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10993      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10994     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10995     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10996     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10997     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10998     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10999     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11000     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11001     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11002     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11003 #endif
11004 };
11005
11006 /*
11007 ** The following 256 byte lookup table is used to support SQLites built-in
11008 ** equivalents to the following standard library functions:
11009 **
11010 **   isspace()                        0x01
11011 **   isalpha()                        0x02
11012 **   isdigit()                        0x04
11013 **   isalnum()                        0x06
11014 **   isxdigit()                       0x08
11015 **   toupper()                        0x20
11016 **   SQLite identifier character      0x40
11017 **
11018 ** Bit 0x20 is set if the mapped character requires translation to upper
11019 ** case. i.e. if the character is a lower-case ASCII character.
11020 ** If x is a lower-case ASCII character, then its upper-case equivalent
11021 ** is (x - 0x20). Therefore toupper() can be implemented as:
11022 **
11023 **   (x & ~(map[x]&0x20))
11024 **
11025 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11026 ** array. tolower() is used more often than toupper() by SQLite.
11027 **
11028 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11029 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11030 ** non-ASCII UTF character. Hence the test for whether or not a character is
11031 ** part of an identifier is 0x46.
11032 **
11033 ** SQLite's versions are identical to the standard versions assuming a
11034 ** locale of "C". They are implemented as macros in sqliteInt.h.
11035 */
11036 #ifdef SQLITE_ASCII
11037 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11038   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11039   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11040   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11041   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11042   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11043   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11044   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11045   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11046
11047   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11048   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11049   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11050   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11051   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11052   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11053   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11054   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11055
11056   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11057   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11058   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11059   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11060   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11061   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11062   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11063   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11064
11065   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11066   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11067   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11068   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11069   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11070   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11071   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11072   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11073 };
11074 #endif
11075
11076
11077
11078 /*
11079 ** The following singleton contains the global configuration for
11080 ** the SQLite library.
11081 */
11082 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11083    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11084    1,                         /* bCoreMutex */
11085    SQLITE_THREADSAFE==1,      /* bFullMutex */
11086    0x7ffffffe,                /* mxStrlen */
11087    100,                       /* szLookaside */
11088    500,                       /* nLookaside */
11089    {0,0,0,0,0,0,0,0},         /* m */
11090    {0,0,0,0,0,0,0,0,0},       /* mutex */
11091    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11092    (void*)0,                  /* pHeap */
11093    0,                         /* nHeap */
11094    0, 0,                      /* mnHeap, mxHeap */
11095    (void*)0,                  /* pScratch */
11096    0,                         /* szScratch */
11097    0,                         /* nScratch */
11098    (void*)0,                  /* pPage */
11099    0,                         /* szPage */
11100    0,                         /* nPage */
11101    0,                         /* mxParserStack */
11102    0,                         /* sharedCacheEnabled */
11103    /* All the rest should always be initialized to zero */
11104    0,                         /* isInit */
11105    0,                         /* inProgress */
11106    0,                         /* isMutexInit */
11107    0,                         /* isMallocInit */
11108    0,                         /* isPCacheInit */
11109    0,                         /* pInitMutex */
11110    0,                         /* nRefInitMutex */
11111    0,                         /* xLog */
11112    0,                         /* pLogArg */
11113 };
11114
11115
11116 /*
11117 ** Hash table for global functions - functions common to all
11118 ** database connections.  After initialization, this table is
11119 ** read-only.
11120 */
11121 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11122
11123 /*
11124 ** Constant tokens for values 0 and 1.
11125 */
11126 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11127    { "0", 1 },
11128    { "1", 1 }
11129 };
11130
11131
11132 /*
11133 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11134 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11135 ** the database page that contains the pending byte.  It never attempts
11136 ** to read or write that page.  The pending byte page is set assign
11137 ** for use by the VFS layers as space for managing file locks.
11138 **
11139 ** During testing, it is often desirable to move the pending byte to
11140 ** a different position in the file.  This allows code that has to
11141 ** deal with the pending byte to run on files that are much smaller
11142 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11143 ** move the pending byte.
11144 **
11145 ** IMPORTANT:  Changing the pending byte to any value other than
11146 ** 0x40000000 results in an incompatible database file format!
11147 ** Changing the pending byte during operating results in undefined
11148 ** and dileterious behavior.
11149 */
11150 #ifndef SQLITE_OMIT_WSD
11151 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11152 #endif
11153
11154 /*
11155 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11156 ** created by mkopcodeh.awk during compilation.  Data is obtained
11157 ** from the comments following the "case OP_xxxx:" statements in
11158 ** the vdbe.c file.  
11159 */
11160 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11161
11162 /************** End of global.c **********************************************/
11163 /************** Begin file ctime.c *******************************************/
11164 /*
11165 ** 2010 February 23
11166 **
11167 ** The author disclaims copyright to this source code.  In place of
11168 ** a legal notice, here is a blessing:
11169 **
11170 **    May you do good and not evil.
11171 **    May you find forgiveness for yourself and forgive others.
11172 **    May you share freely, never taking more than you give.
11173 **
11174 *************************************************************************
11175 **
11176 ** This file implements routines used to report what compile-time options
11177 ** SQLite was built with.
11178 */
11179
11180 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11181
11182
11183 /*
11184 ** An array of names of all compile-time options.  This array should 
11185 ** be sorted A-Z.
11186 **
11187 ** This array looks large, but in a typical installation actually uses
11188 ** only a handful of compile-time options, so most times this array is usually
11189 ** rather short and uses little memory space.
11190 */
11191 static const char * const azCompileOpt[] = {
11192
11193 /* These macros are provided to "stringify" the value of the define
11194 ** for those options in which the value is meaningful. */
11195 #define CTIMEOPT_VAL_(opt) #opt
11196 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11197
11198 #ifdef SQLITE_32BIT_ROWID
11199   "32BIT_ROWID",
11200 #endif
11201 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11202   "4_BYTE_ALIGNED_MALLOC",
11203 #endif
11204 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11205   "CASE_SENSITIVE_LIKE",
11206 #endif
11207 #ifdef SQLITE_CHECK_PAGES
11208   "CHECK_PAGES",
11209 #endif
11210 #ifdef SQLITE_COVERAGE_TEST
11211   "COVERAGE_TEST",
11212 #endif
11213 #ifdef SQLITE_DEBUG
11214   "DEBUG",
11215 #endif
11216 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11217   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11218 #endif
11219 #ifdef SQLITE_DISABLE_DIRSYNC
11220   "DISABLE_DIRSYNC",
11221 #endif
11222 #ifdef SQLITE_DISABLE_LFS
11223   "DISABLE_LFS",
11224 #endif
11225 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11226   "ENABLE_ATOMIC_WRITE",
11227 #endif
11228 #ifdef SQLITE_ENABLE_CEROD
11229   "ENABLE_CEROD",
11230 #endif
11231 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11232   "ENABLE_COLUMN_METADATA",
11233 #endif
11234 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11235   "ENABLE_EXPENSIVE_ASSERT",
11236 #endif
11237 #ifdef SQLITE_ENABLE_FTS1
11238   "ENABLE_FTS1",
11239 #endif
11240 #ifdef SQLITE_ENABLE_FTS2
11241   "ENABLE_FTS2",
11242 #endif
11243 #ifdef SQLITE_ENABLE_FTS3
11244   "ENABLE_FTS3",
11245 #endif
11246 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11247   "ENABLE_FTS3_PARENTHESIS",
11248 #endif
11249 #ifdef SQLITE_ENABLE_FTS4
11250   "ENABLE_FTS4",
11251 #endif
11252 #ifdef SQLITE_ENABLE_ICU
11253   "ENABLE_ICU",
11254 #endif
11255 #ifdef SQLITE_ENABLE_IOTRACE
11256   "ENABLE_IOTRACE",
11257 #endif
11258 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11259   "ENABLE_LOAD_EXTENSION",
11260 #endif
11261 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11262   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11263 #endif
11264 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11265   "ENABLE_MEMORY_MANAGEMENT",
11266 #endif
11267 #ifdef SQLITE_ENABLE_MEMSYS3
11268   "ENABLE_MEMSYS3",
11269 #endif
11270 #ifdef SQLITE_ENABLE_MEMSYS5
11271   "ENABLE_MEMSYS5",
11272 #endif
11273 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11274   "ENABLE_OVERSIZE_CELL_CHECK",
11275 #endif
11276 #ifdef SQLITE_ENABLE_RTREE
11277   "ENABLE_RTREE",
11278 #endif
11279 #ifdef SQLITE_ENABLE_STAT2
11280   "ENABLE_STAT2",
11281 #endif
11282 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11283   "ENABLE_UNLOCK_NOTIFY",
11284 #endif
11285 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11286   "ENABLE_UPDATE_DELETE_LIMIT",
11287 #endif
11288 #ifdef SQLITE_HAS_CODEC
11289   "HAS_CODEC",
11290 #endif
11291 #ifdef SQLITE_HAVE_ISNAN
11292   "HAVE_ISNAN",
11293 #endif
11294 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11295   "HOMEGROWN_RECURSIVE_MUTEX",
11296 #endif
11297 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11298   "IGNORE_AFP_LOCK_ERRORS",
11299 #endif
11300 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11301   "IGNORE_FLOCK_LOCK_ERRORS",
11302 #endif
11303 #ifdef SQLITE_INT64_TYPE
11304   "INT64_TYPE",
11305 #endif
11306 #ifdef SQLITE_LOCK_TRACE
11307   "LOCK_TRACE",
11308 #endif
11309 #ifdef SQLITE_MEMDEBUG
11310   "MEMDEBUG",
11311 #endif
11312 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11313   "MIXED_ENDIAN_64BIT_FLOAT",
11314 #endif
11315 #ifdef SQLITE_NO_SYNC
11316   "NO_SYNC",
11317 #endif
11318 #ifdef SQLITE_OMIT_ALTERTABLE
11319   "OMIT_ALTERTABLE",
11320 #endif
11321 #ifdef SQLITE_OMIT_ANALYZE
11322   "OMIT_ANALYZE",
11323 #endif
11324 #ifdef SQLITE_OMIT_ATTACH
11325   "OMIT_ATTACH",
11326 #endif
11327 #ifdef SQLITE_OMIT_AUTHORIZATION
11328   "OMIT_AUTHORIZATION",
11329 #endif
11330 #ifdef SQLITE_OMIT_AUTOINCREMENT
11331   "OMIT_AUTOINCREMENT",
11332 #endif
11333 #ifdef SQLITE_OMIT_AUTOINIT
11334   "OMIT_AUTOINIT",
11335 #endif
11336 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11337   "OMIT_AUTOMATIC_INDEX",
11338 #endif
11339 #ifdef SQLITE_OMIT_AUTOVACUUM
11340   "OMIT_AUTOVACUUM",
11341 #endif
11342 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11343   "OMIT_BETWEEN_OPTIMIZATION",
11344 #endif
11345 #ifdef SQLITE_OMIT_BLOB_LITERAL
11346   "OMIT_BLOB_LITERAL",
11347 #endif
11348 #ifdef SQLITE_OMIT_BTREECOUNT
11349   "OMIT_BTREECOUNT",
11350 #endif
11351 #ifdef SQLITE_OMIT_BUILTIN_TEST
11352   "OMIT_BUILTIN_TEST",
11353 #endif
11354 #ifdef SQLITE_OMIT_CAST
11355   "OMIT_CAST",
11356 #endif
11357 #ifdef SQLITE_OMIT_CHECK
11358   "OMIT_CHECK",
11359 #endif
11360 /* // redundant
11361 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11362 **   "OMIT_COMPILEOPTION_DIAGS",
11363 ** #endif
11364 */
11365 #ifdef SQLITE_OMIT_COMPLETE
11366   "OMIT_COMPLETE",
11367 #endif
11368 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11369   "OMIT_COMPOUND_SELECT",
11370 #endif
11371 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11372   "OMIT_DATETIME_FUNCS",
11373 #endif
11374 #ifdef SQLITE_OMIT_DECLTYPE
11375   "OMIT_DECLTYPE",
11376 #endif
11377 #ifdef SQLITE_OMIT_DEPRECATED
11378   "OMIT_DEPRECATED",
11379 #endif
11380 #ifdef SQLITE_OMIT_DISKIO
11381   "OMIT_DISKIO",
11382 #endif
11383 #ifdef SQLITE_OMIT_EXPLAIN
11384   "OMIT_EXPLAIN",
11385 #endif
11386 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11387   "OMIT_FLAG_PRAGMAS",
11388 #endif
11389 #ifdef SQLITE_OMIT_FLOATING_POINT
11390   "OMIT_FLOATING_POINT",
11391 #endif
11392 #ifdef SQLITE_OMIT_FOREIGN_KEY
11393   "OMIT_FOREIGN_KEY",
11394 #endif
11395 #ifdef SQLITE_OMIT_GET_TABLE
11396   "OMIT_GET_TABLE",
11397 #endif
11398 #ifdef SQLITE_OMIT_INCRBLOB
11399   "OMIT_INCRBLOB",
11400 #endif
11401 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11402   "OMIT_INTEGRITY_CHECK",
11403 #endif
11404 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11405   "OMIT_LIKE_OPTIMIZATION",
11406 #endif
11407 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11408   "OMIT_LOAD_EXTENSION",
11409 #endif
11410 #ifdef SQLITE_OMIT_LOCALTIME
11411   "OMIT_LOCALTIME",
11412 #endif
11413 #ifdef SQLITE_OMIT_LOOKASIDE
11414   "OMIT_LOOKASIDE",
11415 #endif
11416 #ifdef SQLITE_OMIT_MEMORYDB
11417   "OMIT_MEMORYDB",
11418 #endif
11419 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11420   "OMIT_OR_OPTIMIZATION",
11421 #endif
11422 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11423   "OMIT_PAGER_PRAGMAS",
11424 #endif
11425 #ifdef SQLITE_OMIT_PRAGMA
11426   "OMIT_PRAGMA",
11427 #endif
11428 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11429   "OMIT_PROGRESS_CALLBACK",
11430 #endif
11431 #ifdef SQLITE_OMIT_QUICKBALANCE
11432   "OMIT_QUICKBALANCE",
11433 #endif
11434 #ifdef SQLITE_OMIT_REINDEX
11435   "OMIT_REINDEX",
11436 #endif
11437 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11438   "OMIT_SCHEMA_PRAGMAS",
11439 #endif
11440 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11441   "OMIT_SCHEMA_VERSION_PRAGMAS",
11442 #endif
11443 #ifdef SQLITE_OMIT_SHARED_CACHE
11444   "OMIT_SHARED_CACHE",
11445 #endif
11446 #ifdef SQLITE_OMIT_SUBQUERY
11447   "OMIT_SUBQUERY",
11448 #endif
11449 #ifdef SQLITE_OMIT_TCL_VARIABLE
11450   "OMIT_TCL_VARIABLE",
11451 #endif
11452 #ifdef SQLITE_OMIT_TEMPDB
11453   "OMIT_TEMPDB",
11454 #endif
11455 #ifdef SQLITE_OMIT_TRACE
11456   "OMIT_TRACE",
11457 #endif
11458 #ifdef SQLITE_OMIT_TRIGGER
11459   "OMIT_TRIGGER",
11460 #endif
11461 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11462   "OMIT_TRUNCATE_OPTIMIZATION",
11463 #endif
11464 #ifdef SQLITE_OMIT_UTF16
11465   "OMIT_UTF16",
11466 #endif
11467 #ifdef SQLITE_OMIT_VACUUM
11468   "OMIT_VACUUM",
11469 #endif
11470 #ifdef SQLITE_OMIT_VIEW
11471   "OMIT_VIEW",
11472 #endif
11473 #ifdef SQLITE_OMIT_VIRTUALTABLE
11474   "OMIT_VIRTUALTABLE",
11475 #endif
11476 #ifdef SQLITE_OMIT_WAL
11477   "OMIT_WAL",
11478 #endif
11479 #ifdef SQLITE_OMIT_WSD
11480   "OMIT_WSD",
11481 #endif
11482 #ifdef SQLITE_OMIT_XFER_OPT
11483   "OMIT_XFER_OPT",
11484 #endif
11485 #ifdef SQLITE_PERFORMANCE_TRACE
11486   "PERFORMANCE_TRACE",
11487 #endif
11488 #ifdef SQLITE_PROXY_DEBUG
11489   "PROXY_DEBUG",
11490 #endif
11491 #ifdef SQLITE_SECURE_DELETE
11492   "SECURE_DELETE",
11493 #endif
11494 #ifdef SQLITE_SMALL_STACK
11495   "SMALL_STACK",
11496 #endif
11497 #ifdef SQLITE_SOUNDEX
11498   "SOUNDEX",
11499 #endif
11500 #ifdef SQLITE_TCL
11501   "TCL",
11502 #endif
11503 #ifdef SQLITE_TEMP_STORE
11504   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11505 #endif
11506 #ifdef SQLITE_TEST
11507   "TEST",
11508 #endif
11509 #ifdef SQLITE_THREADSAFE
11510   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11511 #endif
11512 #ifdef SQLITE_USE_ALLOCA
11513   "USE_ALLOCA",
11514 #endif
11515 #ifdef SQLITE_ZERO_MALLOC
11516   "ZERO_MALLOC"
11517 #endif
11518 };
11519
11520 /*
11521 ** Given the name of a compile-time option, return true if that option
11522 ** was used and false if not.
11523 **
11524 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11525 ** is not required for a match.
11526 */
11527 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11528   int i, n;
11529   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11530   n = sqlite3Strlen30(zOptName);
11531
11532   /* Since ArraySize(azCompileOpt) is normally in single digits, a
11533   ** linear search is adequate.  No need for a binary search. */
11534   for(i=0; i<ArraySize(azCompileOpt); i++){
11535     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11536        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11537   }
11538   return 0;
11539 }
11540
11541 /*
11542 ** Return the N-th compile-time option string.  If N is out of range,
11543 ** return a NULL pointer.
11544 */
11545 SQLITE_API const char *sqlite3_compileoption_get(int N){
11546   if( N>=0 && N<ArraySize(azCompileOpt) ){
11547     return azCompileOpt[N];
11548   }
11549   return 0;
11550 }
11551
11552 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11553
11554 /************** End of ctime.c ***********************************************/
11555 /************** Begin file status.c ******************************************/
11556 /*
11557 ** 2008 June 18
11558 **
11559 ** The author disclaims copyright to this source code.  In place of
11560 ** a legal notice, here is a blessing:
11561 **
11562 **    May you do good and not evil.
11563 **    May you find forgiveness for yourself and forgive others.
11564 **    May you share freely, never taking more than you give.
11565 **
11566 *************************************************************************
11567 **
11568 ** This module implements the sqlite3_status() interface and related
11569 ** functionality.
11570 */
11571
11572 /*
11573 ** Variables in which to record status information.
11574 */
11575 typedef struct sqlite3StatType sqlite3StatType;
11576 static SQLITE_WSD struct sqlite3StatType {
11577   int nowValue[9];         /* Current value */
11578   int mxValue[9];          /* Maximum value */
11579 } sqlite3Stat = { {0,}, {0,} };
11580
11581
11582 /* The "wsdStat" macro will resolve to the status information
11583 ** state vector.  If writable static data is unsupported on the target,
11584 ** we have to locate the state vector at run-time.  In the more common
11585 ** case where writable static data is supported, wsdStat can refer directly
11586 ** to the "sqlite3Stat" state vector declared above.
11587 */
11588 #ifdef SQLITE_OMIT_WSD
11589 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11590 # define wsdStat x[0]
11591 #else
11592 # define wsdStatInit
11593 # define wsdStat sqlite3Stat
11594 #endif
11595
11596 /*
11597 ** Return the current value of a status parameter.
11598 */
11599 SQLITE_PRIVATE int sqlite3StatusValue(int op){
11600   wsdStatInit;
11601   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11602   return wsdStat.nowValue[op];
11603 }
11604
11605 /*
11606 ** Add N to the value of a status record.  It is assumed that the
11607 ** caller holds appropriate locks.
11608 */
11609 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11610   wsdStatInit;
11611   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11612   wsdStat.nowValue[op] += N;
11613   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11614     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11615   }
11616 }
11617
11618 /*
11619 ** Set the value of a status to X.
11620 */
11621 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11622   wsdStatInit;
11623   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11624   wsdStat.nowValue[op] = X;
11625   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11626     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11627   }
11628 }
11629
11630 /*
11631 ** Query status information.
11632 **
11633 ** This implementation assumes that reading or writing an aligned
11634 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11635 ** then this routine is not threadsafe.
11636 */
11637 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11638   wsdStatInit;
11639   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11640     return SQLITE_MISUSE_BKPT;
11641   }
11642   *pCurrent = wsdStat.nowValue[op];
11643   *pHighwater = wsdStat.mxValue[op];
11644   if( resetFlag ){
11645     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11646   }
11647   return SQLITE_OK;
11648 }
11649
11650 /*
11651 ** Query status information for a single database connection
11652 */
11653 SQLITE_API int sqlite3_db_status(
11654   sqlite3 *db,          /* The database connection whose status is desired */
11655   int op,               /* Status verb */
11656   int *pCurrent,        /* Write current value here */
11657   int *pHighwater,      /* Write high-water mark here */
11658   int resetFlag         /* Reset high-water mark if true */
11659 ){
11660   switch( op ){
11661     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11662       *pCurrent = db->lookaside.nOut;
11663       *pHighwater = db->lookaside.mxOut;
11664       if( resetFlag ){
11665         db->lookaside.mxOut = db->lookaside.nOut;
11666       }
11667       break;
11668     }
11669
11670     /* 
11671     ** Return an approximation for the amount of memory currently used
11672     ** by all pagers associated with the given database connection.  The
11673     ** highwater mark is meaningless and is returned as zero.
11674     */
11675     case SQLITE_DBSTATUS_CACHE_USED: {
11676       int totalUsed = 0;
11677       int i;
11678       for(i=0; i<db->nDb; i++){
11679         Btree *pBt = db->aDb[i].pBt;
11680         if( pBt ){
11681           Pager *pPager = sqlite3BtreePager(pBt);
11682           totalUsed += sqlite3PagerMemUsed(pPager);
11683         }
11684       }
11685       *pCurrent = totalUsed;
11686       *pHighwater = 0;
11687       break;
11688     }
11689     default: {
11690       return SQLITE_ERROR;
11691     }
11692   }
11693   return SQLITE_OK;
11694 }
11695
11696 /************** End of status.c **********************************************/
11697 /************** Begin file date.c ********************************************/
11698 /*
11699 ** 2003 October 31
11700 **
11701 ** The author disclaims copyright to this source code.  In place of
11702 ** a legal notice, here is a blessing:
11703 **
11704 **    May you do good and not evil.
11705 **    May you find forgiveness for yourself and forgive others.
11706 **    May you share freely, never taking more than you give.
11707 **
11708 *************************************************************************
11709 ** This file contains the C functions that implement date and time
11710 ** functions for SQLite.  
11711 **
11712 ** There is only one exported symbol in this file - the function
11713 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11714 ** All other code has file scope.
11715 **
11716 ** SQLite processes all times and dates as Julian Day numbers.  The
11717 ** dates and times are stored as the number of days since noon
11718 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11719 ** calendar system. 
11720 **
11721 ** 1970-01-01 00:00:00 is JD 2440587.5
11722 ** 2000-01-01 00:00:00 is JD 2451544.5
11723 **
11724 ** This implemention requires years to be expressed as a 4-digit number
11725 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11726 ** be represented, even though julian day numbers allow a much wider
11727 ** range of dates.
11728 **
11729 ** The Gregorian calendar system is used for all dates and times,
11730 ** even those that predate the Gregorian calendar.  Historians usually
11731 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11732 ** dates afterwards, depending on locale.  Beware of this difference.
11733 **
11734 ** The conversion algorithms are implemented based on descriptions
11735 ** in the following text:
11736 **
11737 **      Jean Meeus
11738 **      Astronomical Algorithms, 2nd Edition, 1998
11739 **      ISBM 0-943396-61-1
11740 **      Willmann-Bell, Inc
11741 **      Richmond, Virginia (USA)
11742 */
11743 #include <time.h>
11744
11745 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11746
11747 /*
11748 ** On recent Windows platforms, the localtime_s() function is available
11749 ** as part of the "Secure CRT". It is essentially equivalent to 
11750 ** localtime_r() available under most POSIX platforms, except that the 
11751 ** order of the parameters is reversed.
11752 **
11753 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11754 **
11755 ** If the user has not indicated to use localtime_r() or localtime_s()
11756 ** already, check for an MSVC build environment that provides 
11757 ** localtime_s().
11758 */
11759 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11760      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11761 #define HAVE_LOCALTIME_S 1
11762 #endif
11763
11764 /*
11765 ** A structure for holding a single date and time.
11766 */
11767 typedef struct DateTime DateTime;
11768 struct DateTime {
11769   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11770   int Y, M, D;       /* Year, month, and day */
11771   int h, m;          /* Hour and minutes */
11772   int tz;            /* Timezone offset in minutes */
11773   double s;          /* Seconds */
11774   char validYMD;     /* True (1) if Y,M,D are valid */
11775   char validHMS;     /* True (1) if h,m,s are valid */
11776   char validJD;      /* True (1) if iJD is valid */
11777   char validTZ;      /* True (1) if tz is valid */
11778 };
11779
11780
11781 /*
11782 ** Convert zDate into one or more integers.  Additional arguments
11783 ** come in groups of 5 as follows:
11784 **
11785 **       N       number of digits in the integer
11786 **       min     minimum allowed value of the integer
11787 **       max     maximum allowed value of the integer
11788 **       nextC   first character after the integer
11789 **       pVal    where to write the integers value.
11790 **
11791 ** Conversions continue until one with nextC==0 is encountered.
11792 ** The function returns the number of successful conversions.
11793 */
11794 static int getDigits(const char *zDate, ...){
11795   va_list ap;
11796   int val;
11797   int N;
11798   int min;
11799   int max;
11800   int nextC;
11801   int *pVal;
11802   int cnt = 0;
11803   va_start(ap, zDate);
11804   do{
11805     N = va_arg(ap, int);
11806     min = va_arg(ap, int);
11807     max = va_arg(ap, int);
11808     nextC = va_arg(ap, int);
11809     pVal = va_arg(ap, int*);
11810     val = 0;
11811     while( N-- ){
11812       if( !sqlite3Isdigit(*zDate) ){
11813         goto end_getDigits;
11814       }
11815       val = val*10 + *zDate - '0';
11816       zDate++;
11817     }
11818     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11819       goto end_getDigits;
11820     }
11821     *pVal = val;
11822     zDate++;
11823     cnt++;
11824   }while( nextC );
11825 end_getDigits:
11826   va_end(ap);
11827   return cnt;
11828 }
11829
11830 /*
11831 ** Read text from z[] and convert into a floating point number.  Return
11832 ** the number of digits converted.
11833 */
11834 #define getValue sqlite3AtoF
11835
11836 /*
11837 ** Parse a timezone extension on the end of a date-time.
11838 ** The extension is of the form:
11839 **
11840 **        (+/-)HH:MM
11841 **
11842 ** Or the "zulu" notation:
11843 **
11844 **        Z
11845 **
11846 ** If the parse is successful, write the number of minutes
11847 ** of change in p->tz and return 0.  If a parser error occurs,
11848 ** return non-zero.
11849 **
11850 ** A missing specifier is not considered an error.
11851 */
11852 static int parseTimezone(const char *zDate, DateTime *p){
11853   int sgn = 0;
11854   int nHr, nMn;
11855   int c;
11856   while( sqlite3Isspace(*zDate) ){ zDate++; }
11857   p->tz = 0;
11858   c = *zDate;
11859   if( c=='-' ){
11860     sgn = -1;
11861   }else if( c=='+' ){
11862     sgn = +1;
11863   }else if( c=='Z' || c=='z' ){
11864     zDate++;
11865     goto zulu_time;
11866   }else{
11867     return c!=0;
11868   }
11869   zDate++;
11870   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11871     return 1;
11872   }
11873   zDate += 5;
11874   p->tz = sgn*(nMn + nHr*60);
11875 zulu_time:
11876   while( sqlite3Isspace(*zDate) ){ zDate++; }
11877   return *zDate!=0;
11878 }
11879
11880 /*
11881 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11882 ** The HH, MM, and SS must each be exactly 2 digits.  The
11883 ** fractional seconds FFFF can be one or more digits.
11884 **
11885 ** Return 1 if there is a parsing error and 0 on success.
11886 */
11887 static int parseHhMmSs(const char *zDate, DateTime *p){
11888   int h, m, s;
11889   double ms = 0.0;
11890   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11891     return 1;
11892   }
11893   zDate += 5;
11894   if( *zDate==':' ){
11895     zDate++;
11896     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11897       return 1;
11898     }
11899     zDate += 2;
11900     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11901       double rScale = 1.0;
11902       zDate++;
11903       while( sqlite3Isdigit(*zDate) ){
11904         ms = ms*10.0 + *zDate - '0';
11905         rScale *= 10.0;
11906         zDate++;
11907       }
11908       ms /= rScale;
11909     }
11910   }else{
11911     s = 0;
11912   }
11913   p->validJD = 0;
11914   p->validHMS = 1;
11915   p->h = h;
11916   p->m = m;
11917   p->s = s + ms;
11918   if( parseTimezone(zDate, p) ) return 1;
11919   p->validTZ = (p->tz!=0)?1:0;
11920   return 0;
11921 }
11922
11923 /*
11924 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11925 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11926 **
11927 ** Reference:  Meeus page 61
11928 */
11929 static void computeJD(DateTime *p){
11930   int Y, M, D, A, B, X1, X2;
11931
11932   if( p->validJD ) return;
11933   if( p->validYMD ){
11934     Y = p->Y;
11935     M = p->M;
11936     D = p->D;
11937   }else{
11938     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11939     M = 1;
11940     D = 1;
11941   }
11942   if( M<=2 ){
11943     Y--;
11944     M += 12;
11945   }
11946   A = Y/100;
11947   B = 2 - A + (A/4);
11948   X1 = 36525*(Y+4716)/100;
11949   X2 = 306001*(M+1)/10000;
11950   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11951   p->validJD = 1;
11952   if( p->validHMS ){
11953     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11954     if( p->validTZ ){
11955       p->iJD -= p->tz*60000;
11956       p->validYMD = 0;
11957       p->validHMS = 0;
11958       p->validTZ = 0;
11959     }
11960   }
11961 }
11962
11963 /*
11964 ** Parse dates of the form
11965 **
11966 **     YYYY-MM-DD HH:MM:SS.FFF
11967 **     YYYY-MM-DD HH:MM:SS
11968 **     YYYY-MM-DD HH:MM
11969 **     YYYY-MM-DD
11970 **
11971 ** Write the result into the DateTime structure and return 0
11972 ** on success and 1 if the input string is not a well-formed
11973 ** date.
11974 */
11975 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11976   int Y, M, D, neg;
11977
11978   if( zDate[0]=='-' ){
11979     zDate++;
11980     neg = 1;
11981   }else{
11982     neg = 0;
11983   }
11984   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11985     return 1;
11986   }
11987   zDate += 10;
11988   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11989   if( parseHhMmSs(zDate, p)==0 ){
11990     /* We got the time */
11991   }else if( *zDate==0 ){
11992     p->validHMS = 0;
11993   }else{
11994     return 1;
11995   }
11996   p->validJD = 0;
11997   p->validYMD = 1;
11998   p->Y = neg ? -Y : Y;
11999   p->M = M;
12000   p->D = D;
12001   if( p->validTZ ){
12002     computeJD(p);
12003   }
12004   return 0;
12005 }
12006
12007 /*
12008 ** Set the time to the current time reported by the VFS
12009 */
12010 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12011   sqlite3 *db = sqlite3_context_db_handle(context);
12012   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12013   p->validJD = 1;
12014 }
12015
12016 /*
12017 ** Attempt to parse the given string into a Julian Day Number.  Return
12018 ** the number of errors.
12019 **
12020 ** The following are acceptable forms for the input string:
12021 **
12022 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12023 **      DDDD.DD 
12024 **      now
12025 **
12026 ** In the first form, the +/-HH:MM is always optional.  The fractional
12027 ** seconds extension (the ".FFF") is optional.  The seconds portion
12028 ** (":SS.FFF") is option.  The year and date can be omitted as long
12029 ** as there is a time string.  The time string can be omitted as long
12030 ** as there is a year and date.
12031 */
12032 static int parseDateOrTime(
12033   sqlite3_context *context, 
12034   const char *zDate, 
12035   DateTime *p
12036 ){
12037   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
12038   if( parseYyyyMmDd(zDate,p)==0 ){
12039     return 0;
12040   }else if( parseHhMmSs(zDate, p)==0 ){
12041     return 0;
12042   }else if( sqlite3StrICmp(zDate,"now")==0){
12043     setDateTimeToCurrent(context, p);
12044     return 0;
12045   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
12046     double r;
12047     getValue(zDate, &r);
12048     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12049     p->validJD = 1;
12050     return 0;
12051   }
12052   return 1;
12053 }
12054
12055 /*
12056 ** Compute the Year, Month, and Day from the julian day number.
12057 */
12058 static void computeYMD(DateTime *p){
12059   int Z, A, B, C, D, E, X1;
12060   if( p->validYMD ) return;
12061   if( !p->validJD ){
12062     p->Y = 2000;
12063     p->M = 1;
12064     p->D = 1;
12065   }else{
12066     Z = (int)((p->iJD + 43200000)/86400000);
12067     A = (int)((Z - 1867216.25)/36524.25);
12068     A = Z + 1 + A - (A/4);
12069     B = A + 1524;
12070     C = (int)((B - 122.1)/365.25);
12071     D = (36525*C)/100;
12072     E = (int)((B-D)/30.6001);
12073     X1 = (int)(30.6001*E);
12074     p->D = B - D - X1;
12075     p->M = E<14 ? E-1 : E-13;
12076     p->Y = p->M>2 ? C - 4716 : C - 4715;
12077   }
12078   p->validYMD = 1;
12079 }
12080
12081 /*
12082 ** Compute the Hour, Minute, and Seconds from the julian day number.
12083 */
12084 static void computeHMS(DateTime *p){
12085   int s;
12086   if( p->validHMS ) return;
12087   computeJD(p);
12088   s = (int)((p->iJD + 43200000) % 86400000);
12089   p->s = s/1000.0;
12090   s = (int)p->s;
12091   p->s -= s;
12092   p->h = s/3600;
12093   s -= p->h*3600;
12094   p->m = s/60;
12095   p->s += s - p->m*60;
12096   p->validHMS = 1;
12097 }
12098
12099 /*
12100 ** Compute both YMD and HMS
12101 */
12102 static void computeYMD_HMS(DateTime *p){
12103   computeYMD(p);
12104   computeHMS(p);
12105 }
12106
12107 /*
12108 ** Clear the YMD and HMS and the TZ
12109 */
12110 static void clearYMD_HMS_TZ(DateTime *p){
12111   p->validYMD = 0;
12112   p->validHMS = 0;
12113   p->validTZ = 0;
12114 }
12115
12116 #ifndef SQLITE_OMIT_LOCALTIME
12117 /*
12118 ** Compute the difference (in milliseconds)
12119 ** between localtime and UTC (a.k.a. GMT)
12120 ** for the time value p where p is in UTC.
12121 */
12122 static sqlite3_int64 localtimeOffset(DateTime *p){
12123   DateTime x, y;
12124   time_t t;
12125   x = *p;
12126   computeYMD_HMS(&x);
12127   if( x.Y<1971 || x.Y>=2038 ){
12128     x.Y = 2000;
12129     x.M = 1;
12130     x.D = 1;
12131     x.h = 0;
12132     x.m = 0;
12133     x.s = 0.0;
12134   } else {
12135     int s = (int)(x.s + 0.5);
12136     x.s = s;
12137   }
12138   x.tz = 0;
12139   x.validJD = 0;
12140   computeJD(&x);
12141   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12142 #ifdef HAVE_LOCALTIME_R
12143   {
12144     struct tm sLocal;
12145     localtime_r(&t, &sLocal);
12146     y.Y = sLocal.tm_year + 1900;
12147     y.M = sLocal.tm_mon + 1;
12148     y.D = sLocal.tm_mday;
12149     y.h = sLocal.tm_hour;
12150     y.m = sLocal.tm_min;
12151     y.s = sLocal.tm_sec;
12152   }
12153 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12154   {
12155     struct tm sLocal;
12156     localtime_s(&sLocal, &t);
12157     y.Y = sLocal.tm_year + 1900;
12158     y.M = sLocal.tm_mon + 1;
12159     y.D = sLocal.tm_mday;
12160     y.h = sLocal.tm_hour;
12161     y.m = sLocal.tm_min;
12162     y.s = sLocal.tm_sec;
12163   }
12164 #else
12165   {
12166     struct tm *pTm;
12167     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12168     pTm = localtime(&t);
12169     y.Y = pTm->tm_year + 1900;
12170     y.M = pTm->tm_mon + 1;
12171     y.D = pTm->tm_mday;
12172     y.h = pTm->tm_hour;
12173     y.m = pTm->tm_min;
12174     y.s = pTm->tm_sec;
12175     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12176   }
12177 #endif
12178   y.validYMD = 1;
12179   y.validHMS = 1;
12180   y.validJD = 0;
12181   y.validTZ = 0;
12182   computeJD(&y);
12183   return y.iJD - x.iJD;
12184 }
12185 #endif /* SQLITE_OMIT_LOCALTIME */
12186
12187 /*
12188 ** Process a modifier to a date-time stamp.  The modifiers are
12189 ** as follows:
12190 **
12191 **     NNN days
12192 **     NNN hours
12193 **     NNN minutes
12194 **     NNN.NNNN seconds
12195 **     NNN months
12196 **     NNN years
12197 **     start of month
12198 **     start of year
12199 **     start of week
12200 **     start of day
12201 **     weekday N
12202 **     unixepoch
12203 **     localtime
12204 **     utc
12205 **
12206 ** Return 0 on success and 1 if there is any kind of error.
12207 */
12208 static int parseModifier(const char *zMod, DateTime *p){
12209   int rc = 1;
12210   int n;
12211   double r;
12212   char *z, zBuf[30];
12213   z = zBuf;
12214   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12215     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12216   }
12217   z[n] = 0;
12218   switch( z[0] ){
12219 #ifndef SQLITE_OMIT_LOCALTIME
12220     case 'l': {
12221       /*    localtime
12222       **
12223       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12224       ** show local time.
12225       */
12226       if( strcmp(z, "localtime")==0 ){
12227         computeJD(p);
12228         p->iJD += localtimeOffset(p);
12229         clearYMD_HMS_TZ(p);
12230         rc = 0;
12231       }
12232       break;
12233     }
12234 #endif
12235     case 'u': {
12236       /*
12237       **    unixepoch
12238       **
12239       ** Treat the current value of p->iJD as the number of
12240       ** seconds since 1970.  Convert to a real julian day number.
12241       */
12242       if( strcmp(z, "unixepoch")==0 && p->validJD ){
12243         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
12244         clearYMD_HMS_TZ(p);
12245         rc = 0;
12246       }
12247 #ifndef SQLITE_OMIT_LOCALTIME
12248       else if( strcmp(z, "utc")==0 ){
12249         sqlite3_int64 c1;
12250         computeJD(p);
12251         c1 = localtimeOffset(p);
12252         p->iJD -= c1;
12253         clearYMD_HMS_TZ(p);
12254         p->iJD += c1 - localtimeOffset(p);
12255         rc = 0;
12256       }
12257 #endif
12258       break;
12259     }
12260     case 'w': {
12261       /*
12262       **    weekday N
12263       **
12264       ** Move the date to the same time on the next occurrence of
12265       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12266       ** date is already on the appropriate weekday, this is a no-op.
12267       */
12268       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12269                  && (n=(int)r)==r && n>=0 && r<7 ){
12270         sqlite3_int64 Z;
12271         computeYMD_HMS(p);
12272         p->validTZ = 0;
12273         p->validJD = 0;
12274         computeJD(p);
12275         Z = ((p->iJD + 129600000)/86400000) % 7;
12276         if( Z>n ) Z -= 7;
12277         p->iJD += (n - Z)*86400000;
12278         clearYMD_HMS_TZ(p);
12279         rc = 0;
12280       }
12281       break;
12282     }
12283     case 's': {
12284       /*
12285       **    start of TTTTT
12286       **
12287       ** Move the date backwards to the beginning of the current day,
12288       ** or month or year.
12289       */
12290       if( strncmp(z, "start of ", 9)!=0 ) break;
12291       z += 9;
12292       computeYMD(p);
12293       p->validHMS = 1;
12294       p->h = p->m = 0;
12295       p->s = 0.0;
12296       p->validTZ = 0;
12297       p->validJD = 0;
12298       if( strcmp(z,"month")==0 ){
12299         p->D = 1;
12300         rc = 0;
12301       }else if( strcmp(z,"year")==0 ){
12302         computeYMD(p);
12303         p->M = 1;
12304         p->D = 1;
12305         rc = 0;
12306       }else if( strcmp(z,"day")==0 ){
12307         rc = 0;
12308       }
12309       break;
12310     }
12311     case '+':
12312     case '-':
12313     case '0':
12314     case '1':
12315     case '2':
12316     case '3':
12317     case '4':
12318     case '5':
12319     case '6':
12320     case '7':
12321     case '8':
12322     case '9': {
12323       double rRounder;
12324       n = getValue(z, &r);
12325       assert( n>=1 );
12326       if( z[n]==':' ){
12327         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12328         ** specified number of hours, minutes, seconds, and fractional seconds
12329         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12330         ** omitted.
12331         */
12332         const char *z2 = z;
12333         DateTime tx;
12334         sqlite3_int64 day;
12335         if( !sqlite3Isdigit(*z2) ) z2++;
12336         memset(&tx, 0, sizeof(tx));
12337         if( parseHhMmSs(z2, &tx) ) break;
12338         computeJD(&tx);
12339         tx.iJD -= 43200000;
12340         day = tx.iJD/86400000;
12341         tx.iJD -= day*86400000;
12342         if( z[0]=='-' ) tx.iJD = -tx.iJD;
12343         computeJD(p);
12344         clearYMD_HMS_TZ(p);
12345         p->iJD += tx.iJD;
12346         rc = 0;
12347         break;
12348       }
12349       z += n;
12350       while( sqlite3Isspace(*z) ) z++;
12351       n = sqlite3Strlen30(z);
12352       if( n>10 || n<3 ) break;
12353       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12354       computeJD(p);
12355       rc = 0;
12356       rRounder = r<0 ? -0.5 : +0.5;
12357       if( n==3 && strcmp(z,"day")==0 ){
12358         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12359       }else if( n==4 && strcmp(z,"hour")==0 ){
12360         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12361       }else if( n==6 && strcmp(z,"minute")==0 ){
12362         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12363       }else if( n==6 && strcmp(z,"second")==0 ){
12364         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12365       }else if( n==5 && strcmp(z,"month")==0 ){
12366         int x, y;
12367         computeYMD_HMS(p);
12368         p->M += (int)r;
12369         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12370         p->Y += x;
12371         p->M -= x*12;
12372         p->validJD = 0;
12373         computeJD(p);
12374         y = (int)r;
12375         if( y!=r ){
12376           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12377         }
12378       }else if( n==4 && strcmp(z,"year")==0 ){
12379         int y = (int)r;
12380         computeYMD_HMS(p);
12381         p->Y += y;
12382         p->validJD = 0;
12383         computeJD(p);
12384         if( y!=r ){
12385           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12386         }
12387       }else{
12388         rc = 1;
12389       }
12390       clearYMD_HMS_TZ(p);
12391       break;
12392     }
12393     default: {
12394       break;
12395     }
12396   }
12397   return rc;
12398 }
12399
12400 /*
12401 ** Process time function arguments.  argv[0] is a date-time stamp.
12402 ** argv[1] and following are modifiers.  Parse them all and write
12403 ** the resulting time into the DateTime structure p.  Return 0
12404 ** on success and 1 if there are any errors.
12405 **
12406 ** If there are zero parameters (if even argv[0] is undefined)
12407 ** then assume a default value of "now" for argv[0].
12408 */
12409 static int isDate(
12410   sqlite3_context *context, 
12411   int argc, 
12412   sqlite3_value **argv, 
12413   DateTime *p
12414 ){
12415   int i;
12416   const unsigned char *z;
12417   int eType;
12418   memset(p, 0, sizeof(*p));
12419   if( argc==0 ){
12420     setDateTimeToCurrent(context, p);
12421   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12422                    || eType==SQLITE_INTEGER ){
12423     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12424     p->validJD = 1;
12425   }else{
12426     z = sqlite3_value_text(argv[0]);
12427     if( !z || parseDateOrTime(context, (char*)z, p) ){
12428       return 1;
12429     }
12430   }
12431   for(i=1; i<argc; i++){
12432     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12433       return 1;
12434     }
12435   }
12436   return 0;
12437 }
12438
12439
12440 /*
12441 ** The following routines implement the various date and time functions
12442 ** of SQLite.
12443 */
12444
12445 /*
12446 **    julianday( TIMESTRING, MOD, MOD, ...)
12447 **
12448 ** Return the julian day number of the date specified in the arguments
12449 */
12450 static void juliandayFunc(
12451   sqlite3_context *context,
12452   int argc,
12453   sqlite3_value **argv
12454 ){
12455   DateTime x;
12456   if( isDate(context, argc, argv, &x)==0 ){
12457     computeJD(&x);
12458     sqlite3_result_double(context, x.iJD/86400000.0);
12459   }
12460 }
12461
12462 /*
12463 **    datetime( TIMESTRING, MOD, MOD, ...)
12464 **
12465 ** Return YYYY-MM-DD HH:MM:SS
12466 */
12467 static void datetimeFunc(
12468   sqlite3_context *context,
12469   int argc,
12470   sqlite3_value **argv
12471 ){
12472   DateTime x;
12473   if( isDate(context, argc, argv, &x)==0 ){
12474     char zBuf[100];
12475     computeYMD_HMS(&x);
12476     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12477                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12478     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12479   }
12480 }
12481
12482 /*
12483 **    time( TIMESTRING, MOD, MOD, ...)
12484 **
12485 ** Return HH:MM:SS
12486 */
12487 static void timeFunc(
12488   sqlite3_context *context,
12489   int argc,
12490   sqlite3_value **argv
12491 ){
12492   DateTime x;
12493   if( isDate(context, argc, argv, &x)==0 ){
12494     char zBuf[100];
12495     computeHMS(&x);
12496     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12497     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12498   }
12499 }
12500
12501 /*
12502 **    date( TIMESTRING, MOD, MOD, ...)
12503 **
12504 ** Return YYYY-MM-DD
12505 */
12506 static void dateFunc(
12507   sqlite3_context *context,
12508   int argc,
12509   sqlite3_value **argv
12510 ){
12511   DateTime x;
12512   if( isDate(context, argc, argv, &x)==0 ){
12513     char zBuf[100];
12514     computeYMD(&x);
12515     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12516     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12517   }
12518 }
12519
12520 /*
12521 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12522 **
12523 ** Return a string described by FORMAT.  Conversions as follows:
12524 **
12525 **   %d  day of month
12526 **   %f  ** fractional seconds  SS.SSS
12527 **   %H  hour 00-24
12528 **   %j  day of year 000-366
12529 **   %J  ** Julian day number
12530 **   %m  month 01-12
12531 **   %M  minute 00-59
12532 **   %s  seconds since 1970-01-01
12533 **   %S  seconds 00-59
12534 **   %w  day of week 0-6  sunday==0
12535 **   %W  week of year 00-53
12536 **   %Y  year 0000-9999
12537 **   %%  %
12538 */
12539 static void strftimeFunc(
12540   sqlite3_context *context,
12541   int argc,
12542   sqlite3_value **argv
12543 ){
12544   DateTime x;
12545   u64 n;
12546   size_t i,j;
12547   char *z;
12548   sqlite3 *db;
12549   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12550   char zBuf[100];
12551   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12552   db = sqlite3_context_db_handle(context);
12553   for(i=0, n=1; zFmt[i]; i++, n++){
12554     if( zFmt[i]=='%' ){
12555       switch( zFmt[i+1] ){
12556         case 'd':
12557         case 'H':
12558         case 'm':
12559         case 'M':
12560         case 'S':
12561         case 'W':
12562           n++;
12563           /* fall thru */
12564         case 'w':
12565         case '%':
12566           break;
12567         case 'f':
12568           n += 8;
12569           break;
12570         case 'j':
12571           n += 3;
12572           break;
12573         case 'Y':
12574           n += 8;
12575           break;
12576         case 's':
12577         case 'J':
12578           n += 50;
12579           break;
12580         default:
12581           return;  /* ERROR.  return a NULL */
12582       }
12583       i++;
12584     }
12585   }
12586   testcase( n==sizeof(zBuf)-1 );
12587   testcase( n==sizeof(zBuf) );
12588   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12589   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12590   if( n<sizeof(zBuf) ){
12591     z = zBuf;
12592   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12593     sqlite3_result_error_toobig(context);
12594     return;
12595   }else{
12596     z = sqlite3DbMallocRaw(db, (int)n);
12597     if( z==0 ){
12598       sqlite3_result_error_nomem(context);
12599       return;
12600     }
12601   }
12602   computeJD(&x);
12603   computeYMD_HMS(&x);
12604   for(i=j=0; zFmt[i]; i++){
12605     if( zFmt[i]!='%' ){
12606       z[j++] = zFmt[i];
12607     }else{
12608       i++;
12609       switch( zFmt[i] ){
12610         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12611         case 'f': {
12612           double s = x.s;
12613           if( s>59.999 ) s = 59.999;
12614           sqlite3_snprintf(7, &z[j],"%06.3f", s);
12615           j += sqlite3Strlen30(&z[j]);
12616           break;
12617         }
12618         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12619         case 'W': /* Fall thru */
12620         case 'j': {
12621           int nDay;             /* Number of days since 1st day of year */
12622           DateTime y = x;
12623           y.validJD = 0;
12624           y.M = 1;
12625           y.D = 1;
12626           computeJD(&y);
12627           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12628           if( zFmt[i]=='W' ){
12629             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12630             wd = (int)(((x.iJD+43200000)/86400000)%7);
12631             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12632             j += 2;
12633           }else{
12634             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12635             j += 3;
12636           }
12637           break;
12638         }
12639         case 'J': {
12640           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12641           j+=sqlite3Strlen30(&z[j]);
12642           break;
12643         }
12644         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12645         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12646         case 's': {
12647           sqlite3_snprintf(30,&z[j],"%lld",
12648                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
12649           j += sqlite3Strlen30(&z[j]);
12650           break;
12651         }
12652         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12653         case 'w': {
12654           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12655           break;
12656         }
12657         case 'Y': {
12658           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12659           break;
12660         }
12661         default:   z[j++] = '%'; break;
12662       }
12663     }
12664   }
12665   z[j] = 0;
12666   sqlite3_result_text(context, z, -1,
12667                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12668 }
12669
12670 /*
12671 ** current_time()
12672 **
12673 ** This function returns the same value as time('now').
12674 */
12675 static void ctimeFunc(
12676   sqlite3_context *context,
12677   int NotUsed,
12678   sqlite3_value **NotUsed2
12679 ){
12680   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12681   timeFunc(context, 0, 0);
12682 }
12683
12684 /*
12685 ** current_date()
12686 **
12687 ** This function returns the same value as date('now').
12688 */
12689 static void cdateFunc(
12690   sqlite3_context *context,
12691   int NotUsed,
12692   sqlite3_value **NotUsed2
12693 ){
12694   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12695   dateFunc(context, 0, 0);
12696 }
12697
12698 /*
12699 ** current_timestamp()
12700 **
12701 ** This function returns the same value as datetime('now').
12702 */
12703 static void ctimestampFunc(
12704   sqlite3_context *context,
12705   int NotUsed,
12706   sqlite3_value **NotUsed2
12707 ){
12708   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12709   datetimeFunc(context, 0, 0);
12710 }
12711 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12712
12713 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12714 /*
12715 ** If the library is compiled to omit the full-scale date and time
12716 ** handling (to get a smaller binary), the following minimal version
12717 ** of the functions current_time(), current_date() and current_timestamp()
12718 ** are included instead. This is to support column declarations that
12719 ** include "DEFAULT CURRENT_TIME" etc.
12720 **
12721 ** This function uses the C-library functions time(), gmtime()
12722 ** and strftime(). The format string to pass to strftime() is supplied
12723 ** as the user-data for the function.
12724 */
12725 static void currentTimeFunc(
12726   sqlite3_context *context,
12727   int argc,
12728   sqlite3_value **argv
12729 ){
12730   time_t t;
12731   char *zFormat = (char *)sqlite3_user_data(context);
12732   sqlite3 *db;
12733   sqlite3_int64 iT;
12734   char zBuf[20];
12735
12736   UNUSED_PARAMETER(argc);
12737   UNUSED_PARAMETER(argv);
12738
12739   db = sqlite3_context_db_handle(context);
12740   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
12741   t = iT/1000 - 10000*(sqlite3_int64)21086676;
12742 #ifdef HAVE_GMTIME_R
12743   {
12744     struct tm sNow;
12745     gmtime_r(&t, &sNow);
12746     strftime(zBuf, 20, zFormat, &sNow);
12747   }
12748 #else
12749   {
12750     struct tm *pTm;
12751     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12752     pTm = gmtime(&t);
12753     strftime(zBuf, 20, zFormat, pTm);
12754     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12755   }
12756 #endif
12757
12758   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12759 }
12760 #endif
12761
12762 /*
12763 ** This function registered all of the above C functions as SQL
12764 ** functions.  This should be the only routine in this file with
12765 ** external linkage.
12766 */
12767 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12768   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12769 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12770     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12771     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12772     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12773     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12774     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12775     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12776     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12777     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12778 #else
12779     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12780     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
12781     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12782 #endif
12783   };
12784   int i;
12785   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12786   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12787
12788   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12789     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12790   }
12791 }
12792
12793 /************** End of date.c ************************************************/
12794 /************** Begin file os.c **********************************************/
12795 /*
12796 ** 2005 November 29
12797 **
12798 ** The author disclaims copyright to this source code.  In place of
12799 ** a legal notice, here is a blessing:
12800 **
12801 **    May you do good and not evil.
12802 **    May you find forgiveness for yourself and forgive others.
12803 **    May you share freely, never taking more than you give.
12804 **
12805 ******************************************************************************
12806 **
12807 ** This file contains OS interface code that is common to all
12808 ** architectures.
12809 */
12810 #define _SQLITE_OS_C_ 1
12811 #undef _SQLITE_OS_C_
12812
12813 /*
12814 ** The default SQLite sqlite3_vfs implementations do not allocate
12815 ** memory (actually, os_unix.c allocates a small amount of memory
12816 ** from within OsOpen()), but some third-party implementations may.
12817 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12818 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12819 **
12820 ** The following functions are instrumented for malloc() failure 
12821 ** testing:
12822 **
12823 **     sqlite3OsOpen()
12824 **     sqlite3OsRead()
12825 **     sqlite3OsWrite()
12826 **     sqlite3OsSync()
12827 **     sqlite3OsLock()
12828 **
12829 */
12830 #if defined(SQLITE_TEST)
12831 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
12832   #define DO_OS_MALLOC_TEST(x)                                       \
12833   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
12834     void *pTstAlloc = sqlite3Malloc(10);                             \
12835     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12836     sqlite3_free(pTstAlloc);                                         \
12837   }
12838 #else
12839   #define DO_OS_MALLOC_TEST(x)
12840 #endif
12841
12842 /*
12843 ** The following routines are convenience wrappers around methods
12844 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12845 ** of this would be completely automatic if SQLite were coded using
12846 ** C++ instead of plain old C.
12847 */
12848 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12849   int rc = SQLITE_OK;
12850   if( pId->pMethods ){
12851     rc = pId->pMethods->xClose(pId);
12852     pId->pMethods = 0;
12853   }
12854   return rc;
12855 }
12856 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12857   DO_OS_MALLOC_TEST(id);
12858   return id->pMethods->xRead(id, pBuf, amt, offset);
12859 }
12860 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12861   DO_OS_MALLOC_TEST(id);
12862   return id->pMethods->xWrite(id, pBuf, amt, offset);
12863 }
12864 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12865   return id->pMethods->xTruncate(id, size);
12866 }
12867 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12868   DO_OS_MALLOC_TEST(id);
12869   return id->pMethods->xSync(id, flags);
12870 }
12871 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12872   DO_OS_MALLOC_TEST(id);
12873   return id->pMethods->xFileSize(id, pSize);
12874 }
12875 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12876   DO_OS_MALLOC_TEST(id);
12877   return id->pMethods->xLock(id, lockType);
12878 }
12879 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12880   return id->pMethods->xUnlock(id, lockType);
12881 }
12882 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12883   DO_OS_MALLOC_TEST(id);
12884   return id->pMethods->xCheckReservedLock(id, pResOut);
12885 }
12886 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12887   return id->pMethods->xFileControl(id, op, pArg);
12888 }
12889 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12890   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12891   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12892 }
12893 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12894   return id->pMethods->xDeviceCharacteristics(id);
12895 }
12896 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
12897   return id->pMethods->xShmLock(id, offset, n, flags);
12898 }
12899 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
12900   id->pMethods->xShmBarrier(id);
12901 }
12902 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
12903   return id->pMethods->xShmUnmap(id, deleteFlag);
12904 }
12905 SQLITE_PRIVATE int sqlite3OsShmMap(
12906   sqlite3_file *id,               /* Database file handle */
12907   int iPage,
12908   int pgsz,
12909   int bExtend,                    /* True to extend file if necessary */
12910   void volatile **pp              /* OUT: Pointer to mapping */
12911 ){
12912   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
12913 }
12914
12915 /*
12916 ** The next group of routines are convenience wrappers around the
12917 ** VFS methods.
12918 */
12919 SQLITE_PRIVATE int sqlite3OsOpen(
12920   sqlite3_vfs *pVfs, 
12921   const char *zPath, 
12922   sqlite3_file *pFile, 
12923   int flags, 
12924   int *pFlagsOut
12925 ){
12926   int rc;
12927   DO_OS_MALLOC_TEST(0);
12928   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12929   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12930   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12931   ** reaching the VFS. */
12932   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
12933   assert( rc==SQLITE_OK || pFile->pMethods==0 );
12934   return rc;
12935 }
12936 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12937   return pVfs->xDelete(pVfs, zPath, dirSync);
12938 }
12939 SQLITE_PRIVATE int sqlite3OsAccess(
12940   sqlite3_vfs *pVfs, 
12941   const char *zPath, 
12942   int flags, 
12943   int *pResOut
12944 ){
12945   DO_OS_MALLOC_TEST(0);
12946   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12947 }
12948 SQLITE_PRIVATE int sqlite3OsFullPathname(
12949   sqlite3_vfs *pVfs, 
12950   const char *zPath, 
12951   int nPathOut, 
12952   char *zPathOut
12953 ){
12954   zPathOut[0] = 0;
12955   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12956 }
12957 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12958 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12959   return pVfs->xDlOpen(pVfs, zPath);
12960 }
12961 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12962   pVfs->xDlError(pVfs, nByte, zBufOut);
12963 }
12964 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12965   return pVfs->xDlSym(pVfs, pHdle, zSym);
12966 }
12967 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12968   pVfs->xDlClose(pVfs, pHandle);
12969 }
12970 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12971 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12972   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12973 }
12974 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12975   return pVfs->xSleep(pVfs, nMicro);
12976 }
12977 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
12978   int rc;
12979   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
12980     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
12981   }else{
12982     double r;
12983     rc = pVfs->xCurrentTime(pVfs, &r);
12984     *pTimeOut = (sqlite3_int64)(r*86400000.0);
12985   }
12986   return rc;
12987 }
12988
12989 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12990   sqlite3_vfs *pVfs, 
12991   const char *zFile, 
12992   sqlite3_file **ppFile, 
12993   int flags,
12994   int *pOutFlags
12995 ){
12996   int rc = SQLITE_NOMEM;
12997   sqlite3_file *pFile;
12998   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12999   if( pFile ){
13000     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13001     if( rc!=SQLITE_OK ){
13002       sqlite3_free(pFile);
13003     }else{
13004       *ppFile = pFile;
13005     }
13006   }
13007   return rc;
13008 }
13009 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13010   int rc = SQLITE_OK;
13011   assert( pFile );
13012   rc = sqlite3OsClose(pFile);
13013   sqlite3_free(pFile);
13014   return rc;
13015 }
13016
13017 /*
13018 ** This function is a wrapper around the OS specific implementation of
13019 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
13020 ** ability to simulate a malloc failure, so that the handling of an
13021 ** error in sqlite3_os_init() by the upper layers can be tested.
13022 */
13023 SQLITE_PRIVATE int sqlite3OsInit(void){
13024   void *p = sqlite3_malloc(10);
13025   if( p==0 ) return SQLITE_NOMEM;
13026   sqlite3_free(p);
13027   return sqlite3_os_init();
13028 }
13029
13030 /*
13031 ** The list of all registered VFS implementations.
13032 */
13033 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13034 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13035
13036 /*
13037 ** Locate a VFS by name.  If no name is given, simply return the
13038 ** first VFS on the list.
13039 */
13040 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13041   sqlite3_vfs *pVfs = 0;
13042 #if SQLITE_THREADSAFE
13043   sqlite3_mutex *mutex;
13044 #endif
13045 #ifndef SQLITE_OMIT_AUTOINIT
13046   int rc = sqlite3_initialize();
13047   if( rc ) return 0;
13048 #endif
13049 #if SQLITE_THREADSAFE
13050   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13051 #endif
13052   sqlite3_mutex_enter(mutex);
13053   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13054     if( zVfs==0 ) break;
13055     if( strcmp(zVfs, pVfs->zName)==0 ) break;
13056   }
13057   sqlite3_mutex_leave(mutex);
13058   return pVfs;
13059 }
13060
13061 /*
13062 ** Unlink a VFS from the linked list
13063 */
13064 static void vfsUnlink(sqlite3_vfs *pVfs){
13065   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13066   if( pVfs==0 ){
13067     /* No-op */
13068   }else if( vfsList==pVfs ){
13069     vfsList = pVfs->pNext;
13070   }else if( vfsList ){
13071     sqlite3_vfs *p = vfsList;
13072     while( p->pNext && p->pNext!=pVfs ){
13073       p = p->pNext;
13074     }
13075     if( p->pNext==pVfs ){
13076       p->pNext = pVfs->pNext;
13077     }
13078   }
13079 }
13080
13081 /*
13082 ** Register a VFS with the system.  It is harmless to register the same
13083 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
13084 ** true.
13085 */
13086 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13087   sqlite3_mutex *mutex = 0;
13088 #ifndef SQLITE_OMIT_AUTOINIT
13089   int rc = sqlite3_initialize();
13090   if( rc ) return rc;
13091 #endif
13092   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13093   sqlite3_mutex_enter(mutex);
13094   vfsUnlink(pVfs);
13095   if( makeDflt || vfsList==0 ){
13096     pVfs->pNext = vfsList;
13097     vfsList = pVfs;
13098   }else{
13099     pVfs->pNext = vfsList->pNext;
13100     vfsList->pNext = pVfs;
13101   }
13102   assert(vfsList);
13103   sqlite3_mutex_leave(mutex);
13104   return SQLITE_OK;
13105 }
13106
13107 /*
13108 ** Unregister a VFS so that it is no longer accessible.
13109 */
13110 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13111 #if SQLITE_THREADSAFE
13112   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13113 #endif
13114   sqlite3_mutex_enter(mutex);
13115   vfsUnlink(pVfs);
13116   sqlite3_mutex_leave(mutex);
13117   return SQLITE_OK;
13118 }
13119
13120 /************** End of os.c **************************************************/
13121 /************** Begin file fault.c *******************************************/
13122 /*
13123 ** 2008 Jan 22
13124 **
13125 ** The author disclaims copyright to this source code.  In place of
13126 ** a legal notice, here is a blessing:
13127 **
13128 **    May you do good and not evil.
13129 **    May you find forgiveness for yourself and forgive others.
13130 **    May you share freely, never taking more than you give.
13131 **
13132 *************************************************************************
13133 **
13134 ** This file contains code to support the concept of "benign" 
13135 ** malloc failures (when the xMalloc() or xRealloc() method of the
13136 ** sqlite3_mem_methods structure fails to allocate a block of memory
13137 ** and returns 0). 
13138 **
13139 ** Most malloc failures are non-benign. After they occur, SQLite
13140 ** abandons the current operation and returns an error code (usually
13141 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13142 ** fatal. For example, if a malloc fails while resizing a hash table, this 
13143 ** is completely recoverable simply by not carrying out the resize. The 
13144 ** hash table will continue to function normally.  So a malloc failure 
13145 ** during a hash table resize is a benign fault.
13146 */
13147
13148
13149 #ifndef SQLITE_OMIT_BUILTIN_TEST
13150
13151 /*
13152 ** Global variables.
13153 */
13154 typedef struct BenignMallocHooks BenignMallocHooks;
13155 static SQLITE_WSD struct BenignMallocHooks {
13156   void (*xBenignBegin)(void);
13157   void (*xBenignEnd)(void);
13158 } sqlite3Hooks = { 0, 0 };
13159
13160 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13161 ** structure.  If writable static data is unsupported on the target,
13162 ** we have to locate the state vector at run-time.  In the more common
13163 ** case where writable static data is supported, wsdHooks can refer directly
13164 ** to the "sqlite3Hooks" state vector declared above.
13165 */
13166 #ifdef SQLITE_OMIT_WSD
13167 # define wsdHooksInit \
13168   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13169 # define wsdHooks x[0]
13170 #else
13171 # define wsdHooksInit
13172 # define wsdHooks sqlite3Hooks
13173 #endif
13174
13175
13176 /*
13177 ** Register hooks to call when sqlite3BeginBenignMalloc() and
13178 ** sqlite3EndBenignMalloc() are called, respectively.
13179 */
13180 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13181   void (*xBenignBegin)(void),
13182   void (*xBenignEnd)(void)
13183 ){
13184   wsdHooksInit;
13185   wsdHooks.xBenignBegin = xBenignBegin;
13186   wsdHooks.xBenignEnd = xBenignEnd;
13187 }
13188
13189 /*
13190 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13191 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13192 ** indicates that subsequent malloc failures are non-benign.
13193 */
13194 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13195   wsdHooksInit;
13196   if( wsdHooks.xBenignBegin ){
13197     wsdHooks.xBenignBegin();
13198   }
13199 }
13200 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13201   wsdHooksInit;
13202   if( wsdHooks.xBenignEnd ){
13203     wsdHooks.xBenignEnd();
13204   }
13205 }
13206
13207 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13208
13209 /************** End of fault.c ***********************************************/
13210 /************** Begin file mem0.c ********************************************/
13211 /*
13212 ** 2008 October 28
13213 **
13214 ** The author disclaims copyright to this source code.  In place of
13215 ** a legal notice, here is a blessing:
13216 **
13217 **    May you do good and not evil.
13218 **    May you find forgiveness for yourself and forgive others.
13219 **    May you share freely, never taking more than you give.
13220 **
13221 *************************************************************************
13222 **
13223 ** This file contains a no-op memory allocation drivers for use when
13224 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13225 ** here always fail.  SQLite will not operate with these drivers.  These
13226 ** are merely placeholders.  Real drivers must be substituted using
13227 ** sqlite3_config() before SQLite will operate.
13228 */
13229
13230 /*
13231 ** This version of the memory allocator is the default.  It is
13232 ** used when no other memory allocator is specified using compile-time
13233 ** macros.
13234 */
13235 #ifdef SQLITE_ZERO_MALLOC
13236
13237 /*
13238 ** No-op versions of all memory allocation routines
13239 */
13240 static void *sqlite3MemMalloc(int nByte){ return 0; }
13241 static void sqlite3MemFree(void *pPrior){ return; }
13242 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13243 static int sqlite3MemSize(void *pPrior){ return 0; }
13244 static int sqlite3MemRoundup(int n){ return n; }
13245 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13246 static void sqlite3MemShutdown(void *NotUsed){ return; }
13247
13248 /*
13249 ** This routine is the only routine in this file with external linkage.
13250 **
13251 ** Populate the low-level memory allocation function pointers in
13252 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13253 */
13254 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13255   static const sqlite3_mem_methods defaultMethods = {
13256      sqlite3MemMalloc,
13257      sqlite3MemFree,
13258      sqlite3MemRealloc,
13259      sqlite3MemSize,
13260      sqlite3MemRoundup,
13261      sqlite3MemInit,
13262      sqlite3MemShutdown,
13263      0
13264   };
13265   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13266 }
13267
13268 #endif /* SQLITE_ZERO_MALLOC */
13269
13270 /************** End of mem0.c ************************************************/
13271 /************** Begin file mem1.c ********************************************/
13272 /*
13273 ** 2007 August 14
13274 **
13275 ** The author disclaims copyright to this source code.  In place of
13276 ** a legal notice, here is a blessing:
13277 **
13278 **    May you do good and not evil.
13279 **    May you find forgiveness for yourself and forgive others.
13280 **    May you share freely, never taking more than you give.
13281 **
13282 *************************************************************************
13283 **
13284 ** This file contains low-level memory allocation drivers for when
13285 ** SQLite will use the standard C-library malloc/realloc/free interface
13286 ** to obtain the memory it needs.
13287 **
13288 ** This file contains implementations of the low-level memory allocation
13289 ** routines specified in the sqlite3_mem_methods object.
13290 */
13291
13292 /*
13293 ** This version of the memory allocator is the default.  It is
13294 ** used when no other memory allocator is specified using compile-time
13295 ** macros.
13296 */
13297 #ifdef SQLITE_SYSTEM_MALLOC
13298
13299 /*
13300 ** Like malloc(), but remember the size of the allocation
13301 ** so that we can find it later using sqlite3MemSize().
13302 **
13303 ** For this low-level routine, we are guaranteed that nByte>0 because
13304 ** cases of nByte<=0 will be intercepted and dealt with by higher level
13305 ** routines.
13306 */
13307 static void *sqlite3MemMalloc(int nByte){
13308   sqlite3_int64 *p;
13309   assert( nByte>0 );
13310   nByte = ROUND8(nByte);
13311   p = malloc( nByte+8 );
13312   if( p ){
13313     p[0] = nByte;
13314     p++;
13315   }else{
13316     testcase( sqlite3GlobalConfig.xLog!=0 );
13317     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
13318   }
13319   return (void *)p;
13320 }
13321
13322 /*
13323 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
13324 ** or sqlite3MemRealloc().
13325 **
13326 ** For this low-level routine, we already know that pPrior!=0 since
13327 ** cases where pPrior==0 will have been intecepted and dealt with
13328 ** by higher-level routines.
13329 */
13330 static void sqlite3MemFree(void *pPrior){
13331   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13332   assert( pPrior!=0 );
13333   p--;
13334   free(p);
13335 }
13336
13337 /*
13338 ** Report the allocated size of a prior return from xMalloc()
13339 ** or xRealloc().
13340 */
13341 static int sqlite3MemSize(void *pPrior){
13342   sqlite3_int64 *p;
13343   if( pPrior==0 ) return 0;
13344   p = (sqlite3_int64*)pPrior;
13345   p--;
13346   return (int)p[0];
13347 }
13348
13349 /*
13350 ** Like realloc().  Resize an allocation previously obtained from
13351 ** sqlite3MemMalloc().
13352 **
13353 ** For this low-level interface, we know that pPrior!=0.  Cases where
13354 ** pPrior==0 while have been intercepted by higher-level routine and
13355 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13356 ** cases where nByte<=0 will have been intercepted by higher-level
13357 ** routines and redirected to xFree.
13358 */
13359 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13360   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13361   assert( pPrior!=0 && nByte>0 );
13362   nByte = ROUND8(nByte);
13363   p--;
13364   p = realloc(p, nByte+8 );
13365   if( p ){
13366     p[0] = nByte;
13367     p++;
13368   }else{
13369     testcase( sqlite3GlobalConfig.xLog!=0 );
13370     sqlite3_log(SQLITE_NOMEM,
13371       "failed memory resize %u to %u bytes",
13372       sqlite3MemSize(pPrior), nByte);
13373   }
13374   return (void*)p;
13375 }
13376
13377 /*
13378 ** Round up a request size to the next valid allocation size.
13379 */
13380 static int sqlite3MemRoundup(int n){
13381   return ROUND8(n);
13382 }
13383
13384 /*
13385 ** Initialize this module.
13386 */
13387 static int sqlite3MemInit(void *NotUsed){
13388   UNUSED_PARAMETER(NotUsed);
13389   return SQLITE_OK;
13390 }
13391
13392 /*
13393 ** Deinitialize this module.
13394 */
13395 static void sqlite3MemShutdown(void *NotUsed){
13396   UNUSED_PARAMETER(NotUsed);
13397   return;
13398 }
13399
13400 /*
13401 ** This routine is the only routine in this file with external linkage.
13402 **
13403 ** Populate the low-level memory allocation function pointers in
13404 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13405 */
13406 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13407   static const sqlite3_mem_methods defaultMethods = {
13408      sqlite3MemMalloc,
13409      sqlite3MemFree,
13410      sqlite3MemRealloc,
13411      sqlite3MemSize,
13412      sqlite3MemRoundup,
13413      sqlite3MemInit,
13414      sqlite3MemShutdown,
13415      0
13416   };
13417   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13418 }
13419
13420 #endif /* SQLITE_SYSTEM_MALLOC */
13421
13422 /************** End of mem1.c ************************************************/
13423 /************** Begin file mem2.c ********************************************/
13424 /*
13425 ** 2007 August 15
13426 **
13427 ** The author disclaims copyright to this source code.  In place of
13428 ** a legal notice, here is a blessing:
13429 **
13430 **    May you do good and not evil.
13431 **    May you find forgiveness for yourself and forgive others.
13432 **    May you share freely, never taking more than you give.
13433 **
13434 *************************************************************************
13435 **
13436 ** This file contains low-level memory allocation drivers for when
13437 ** SQLite will use the standard C-library malloc/realloc/free interface
13438 ** to obtain the memory it needs while adding lots of additional debugging
13439 ** information to each allocation in order to help detect and fix memory
13440 ** leaks and memory usage errors.
13441 **
13442 ** This file contains implementations of the low-level memory allocation
13443 ** routines specified in the sqlite3_mem_methods object.
13444 */
13445
13446 /*
13447 ** This version of the memory allocator is used only if the
13448 ** SQLITE_MEMDEBUG macro is defined
13449 */
13450 #ifdef SQLITE_MEMDEBUG
13451
13452 /*
13453 ** The backtrace functionality is only available with GLIBC
13454 */
13455 #ifdef __GLIBC__
13456   extern int backtrace(void**,int);
13457   extern void backtrace_symbols_fd(void*const*,int,int);
13458 #else
13459 # define backtrace(A,B) 1
13460 # define backtrace_symbols_fd(A,B,C)
13461 #endif
13462
13463 /*
13464 ** Each memory allocation looks like this:
13465 **
13466 **  ------------------------------------------------------------------------
13467 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13468 **  ------------------------------------------------------------------------
13469 **
13470 ** The application code sees only a pointer to the allocation.  We have
13471 ** to back up from the allocation pointer to find the MemBlockHdr.  The
13472 ** MemBlockHdr tells us the size of the allocation and the number of
13473 ** backtrace pointers.  There is also a guard word at the end of the
13474 ** MemBlockHdr.
13475 */
13476 struct MemBlockHdr {
13477   i64 iSize;                          /* Size of this allocation */
13478   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13479   char nBacktrace;                    /* Number of backtraces on this alloc */
13480   char nBacktraceSlots;               /* Available backtrace slots */
13481   u8 nTitle;                          /* Bytes of title; includes '\0' */
13482   u8 eType;                           /* Allocation type code */
13483   int iForeGuard;                     /* Guard word for sanity */
13484 };
13485
13486 /*
13487 ** Guard words
13488 */
13489 #define FOREGUARD 0x80F5E153
13490 #define REARGUARD 0xE4676B53
13491
13492 /*
13493 ** Number of malloc size increments to track.
13494 */
13495 #define NCSIZE  1000
13496
13497 /*
13498 ** All of the static variables used by this module are collected
13499 ** into a single structure named "mem".  This is to keep the
13500 ** static variables organized and to reduce namespace pollution
13501 ** when this module is combined with other in the amalgamation.
13502 */
13503 static struct {
13504   
13505   /*
13506   ** Mutex to control access to the memory allocation subsystem.
13507   */
13508   sqlite3_mutex *mutex;
13509
13510   /*
13511   ** Head and tail of a linked list of all outstanding allocations
13512   */
13513   struct MemBlockHdr *pFirst;
13514   struct MemBlockHdr *pLast;
13515   
13516   /*
13517   ** The number of levels of backtrace to save in new allocations.
13518   */
13519   int nBacktrace;
13520   void (*xBacktrace)(int, int, void **);
13521
13522   /*
13523   ** Title text to insert in front of each block
13524   */
13525   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13526   char zTitle[100];  /* The title text */
13527
13528   /* 
13529   ** sqlite3MallocDisallow() increments the following counter.
13530   ** sqlite3MallocAllow() decrements it.
13531   */
13532   int disallow; /* Do not allow memory allocation */
13533
13534   /*
13535   ** Gather statistics on the sizes of memory allocations.
13536   ** nAlloc[i] is the number of allocation attempts of i*8
13537   ** bytes.  i==NCSIZE is the number of allocation attempts for
13538   ** sizes more than NCSIZE*8 bytes.
13539   */
13540   int nAlloc[NCSIZE];      /* Total number of allocations */
13541   int nCurrent[NCSIZE];    /* Current number of allocations */
13542   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13543
13544 } mem;
13545
13546
13547 /*
13548 ** Adjust memory usage statistics
13549 */
13550 static void adjustStats(int iSize, int increment){
13551   int i = ROUND8(iSize)/8;
13552   if( i>NCSIZE-1 ){
13553     i = NCSIZE - 1;
13554   }
13555   if( increment>0 ){
13556     mem.nAlloc[i]++;
13557     mem.nCurrent[i]++;
13558     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13559       mem.mxCurrent[i] = mem.nCurrent[i];
13560     }
13561   }else{
13562     mem.nCurrent[i]--;
13563     assert( mem.nCurrent[i]>=0 );
13564   }
13565 }
13566
13567 /*
13568 ** Given an allocation, find the MemBlockHdr for that allocation.
13569 **
13570 ** This routine checks the guards at either end of the allocation and
13571 ** if they are incorrect it asserts.
13572 */
13573 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13574   struct MemBlockHdr *p;
13575   int *pInt;
13576   u8 *pU8;
13577   int nReserve;
13578
13579   p = (struct MemBlockHdr*)pAllocation;
13580   p--;
13581   assert( p->iForeGuard==(int)FOREGUARD );
13582   nReserve = ROUND8(p->iSize);
13583   pInt = (int*)pAllocation;
13584   pU8 = (u8*)pAllocation;
13585   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13586   /* This checks any of the "extra" bytes allocated due
13587   ** to rounding up to an 8 byte boundary to ensure 
13588   ** they haven't been overwritten.
13589   */
13590   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13591   return p;
13592 }
13593
13594 /*
13595 ** Return the number of bytes currently allocated at address p.
13596 */
13597 static int sqlite3MemSize(void *p){
13598   struct MemBlockHdr *pHdr;
13599   if( !p ){
13600     return 0;
13601   }
13602   pHdr = sqlite3MemsysGetHeader(p);
13603   return pHdr->iSize;
13604 }
13605
13606 /*
13607 ** Initialize the memory allocation subsystem.
13608 */
13609 static int sqlite3MemInit(void *NotUsed){
13610   UNUSED_PARAMETER(NotUsed);
13611   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13612   if( !sqlite3GlobalConfig.bMemstat ){
13613     /* If memory status is enabled, then the malloc.c wrapper will already
13614     ** hold the STATIC_MEM mutex when the routines here are invoked. */
13615     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13616   }
13617   return SQLITE_OK;
13618 }
13619
13620 /*
13621 ** Deinitialize the memory allocation subsystem.
13622 */
13623 static void sqlite3MemShutdown(void *NotUsed){
13624   UNUSED_PARAMETER(NotUsed);
13625   mem.mutex = 0;
13626 }
13627
13628 /*
13629 ** Round up a request size to the next valid allocation size.
13630 */
13631 static int sqlite3MemRoundup(int n){
13632   return ROUND8(n);
13633 }
13634
13635 /*
13636 ** Fill a buffer with pseudo-random bytes.  This is used to preset
13637 ** the content of a new memory allocation to unpredictable values and
13638 ** to clear the content of a freed allocation to unpredictable values.
13639 */
13640 static void randomFill(char *pBuf, int nByte){
13641   unsigned int x, y, r;
13642   x = SQLITE_PTR_TO_INT(pBuf);
13643   y = nByte | 1;
13644   while( nByte >= 4 ){
13645     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13646     y = y*1103515245 + 12345;
13647     r = x ^ y;
13648     *(int*)pBuf = r;
13649     pBuf += 4;
13650     nByte -= 4;
13651   }
13652   while( nByte-- > 0 ){
13653     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13654     y = y*1103515245 + 12345;
13655     r = x ^ y;
13656     *(pBuf++) = r & 0xff;
13657   }
13658 }
13659
13660 /*
13661 ** Allocate nByte bytes of memory.
13662 */
13663 static void *sqlite3MemMalloc(int nByte){
13664   struct MemBlockHdr *pHdr;
13665   void **pBt;
13666   char *z;
13667   int *pInt;
13668   void *p = 0;
13669   int totalSize;
13670   int nReserve;
13671   sqlite3_mutex_enter(mem.mutex);
13672   assert( mem.disallow==0 );
13673   nReserve = ROUND8(nByte);
13674   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13675                mem.nBacktrace*sizeof(void*) + mem.nTitle;
13676   p = malloc(totalSize);
13677   if( p ){
13678     z = p;
13679     pBt = (void**)&z[mem.nTitle];
13680     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13681     pHdr->pNext = 0;
13682     pHdr->pPrev = mem.pLast;
13683     if( mem.pLast ){
13684       mem.pLast->pNext = pHdr;
13685     }else{
13686       mem.pFirst = pHdr;
13687     }
13688     mem.pLast = pHdr;
13689     pHdr->iForeGuard = FOREGUARD;
13690     pHdr->eType = MEMTYPE_HEAP;
13691     pHdr->nBacktraceSlots = mem.nBacktrace;
13692     pHdr->nTitle = mem.nTitle;
13693     if( mem.nBacktrace ){
13694       void *aAddr[40];
13695       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13696       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13697       assert(pBt[0]);
13698       if( mem.xBacktrace ){
13699         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13700       }
13701     }else{
13702       pHdr->nBacktrace = 0;
13703     }
13704     if( mem.nTitle ){
13705       memcpy(z, mem.zTitle, mem.nTitle);
13706     }
13707     pHdr->iSize = nByte;
13708     adjustStats(nByte, +1);
13709     pInt = (int*)&pHdr[1];
13710     pInt[nReserve/sizeof(int)] = REARGUARD;
13711     randomFill((char*)pInt, nByte);
13712     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
13713     p = (void*)pInt;
13714   }
13715   sqlite3_mutex_leave(mem.mutex);
13716   return p; 
13717 }
13718
13719 /*
13720 ** Free memory.
13721 */
13722 static void sqlite3MemFree(void *pPrior){
13723   struct MemBlockHdr *pHdr;
13724   void **pBt;
13725   char *z;
13726   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
13727        || mem.mutex!=0 );
13728   pHdr = sqlite3MemsysGetHeader(pPrior);
13729   pBt = (void**)pHdr;
13730   pBt -= pHdr->nBacktraceSlots;
13731   sqlite3_mutex_enter(mem.mutex);
13732   if( pHdr->pPrev ){
13733     assert( pHdr->pPrev->pNext==pHdr );
13734     pHdr->pPrev->pNext = pHdr->pNext;
13735   }else{
13736     assert( mem.pFirst==pHdr );
13737     mem.pFirst = pHdr->pNext;
13738   }
13739   if( pHdr->pNext ){
13740     assert( pHdr->pNext->pPrev==pHdr );
13741     pHdr->pNext->pPrev = pHdr->pPrev;
13742   }else{
13743     assert( mem.pLast==pHdr );
13744     mem.pLast = pHdr->pPrev;
13745   }
13746   z = (char*)pBt;
13747   z -= pHdr->nTitle;
13748   adjustStats(pHdr->iSize, -1);
13749   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13750                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
13751   free(z);
13752   sqlite3_mutex_leave(mem.mutex);  
13753 }
13754
13755 /*
13756 ** Change the size of an existing memory allocation.
13757 **
13758 ** For this debugging implementation, we *always* make a copy of the
13759 ** allocation into a new place in memory.  In this way, if the 
13760 ** higher level code is using pointer to the old allocation, it is 
13761 ** much more likely to break and we are much more liking to find
13762 ** the error.
13763 */
13764 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13765   struct MemBlockHdr *pOldHdr;
13766   void *pNew;
13767   assert( mem.disallow==0 );
13768   pOldHdr = sqlite3MemsysGetHeader(pPrior);
13769   pNew = sqlite3MemMalloc(nByte);
13770   if( pNew ){
13771     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13772     if( nByte>pOldHdr->iSize ){
13773       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13774     }
13775     sqlite3MemFree(pPrior);
13776   }
13777   return pNew;
13778 }
13779
13780 /*
13781 ** Populate the low-level memory allocation function pointers in
13782 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13783 */
13784 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13785   static const sqlite3_mem_methods defaultMethods = {
13786      sqlite3MemMalloc,
13787      sqlite3MemFree,
13788      sqlite3MemRealloc,
13789      sqlite3MemSize,
13790      sqlite3MemRoundup,
13791      sqlite3MemInit,
13792      sqlite3MemShutdown,
13793      0
13794   };
13795   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13796 }
13797
13798 /*
13799 ** Set the "type" of an allocation.
13800 */
13801 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
13802   if( p ){
13803     struct MemBlockHdr *pHdr;
13804     pHdr = sqlite3MemsysGetHeader(p);
13805     assert( pHdr->iForeGuard==FOREGUARD );
13806     pHdr->eType = eType;
13807   }
13808 }
13809
13810 /*
13811 ** Return TRUE if the mask of type in eType matches the type of the
13812 ** allocation p.  Also return true if p==NULL.
13813 **
13814 ** This routine is designed for use within an assert() statement, to
13815 ** verify the type of an allocation.  For example:
13816 **
13817 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
13818 */
13819 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
13820   int rc = 1;
13821   if( p ){
13822     struct MemBlockHdr *pHdr;
13823     pHdr = sqlite3MemsysGetHeader(p);
13824     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
13825     assert( (pHdr->eType & (pHdr->eType-1))==0 );  /* Only one type bit set */
13826     if( (pHdr->eType&eType)==0 ){
13827       void **pBt;
13828       pBt = (void**)pHdr;
13829       pBt -= pHdr->nBacktraceSlots;
13830       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(stderr));
13831       fprintf(stderr, "\n");
13832       rc = 0;
13833     }
13834   }
13835   return rc;
13836 }
13837  
13838
13839 /*
13840 ** Set the number of backtrace levels kept for each allocation.
13841 ** A value of zero turns off backtracing.  The number is always rounded
13842 ** up to a multiple of 2.
13843 */
13844 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13845   if( depth<0 ){ depth = 0; }
13846   if( depth>20 ){ depth = 20; }
13847   depth = (depth+1)&0xfe;
13848   mem.nBacktrace = depth;
13849 }
13850
13851 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13852   mem.xBacktrace = xBacktrace;
13853 }
13854
13855 /*
13856 ** Set the title string for subsequent allocations.
13857 */
13858 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13859   unsigned int n = sqlite3Strlen30(zTitle) + 1;
13860   sqlite3_mutex_enter(mem.mutex);
13861   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13862   memcpy(mem.zTitle, zTitle, n);
13863   mem.zTitle[n] = 0;
13864   mem.nTitle = ROUND8(n);
13865   sqlite3_mutex_leave(mem.mutex);
13866 }
13867
13868 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13869   struct MemBlockHdr *pHdr;
13870   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13871     void **pBt = (void**)pHdr;
13872     pBt -= pHdr->nBacktraceSlots;
13873     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13874   }
13875 }
13876
13877 /*
13878 ** Open the file indicated and write a log of all unfreed memory 
13879 ** allocations into that log.
13880 */
13881 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13882   FILE *out;
13883   struct MemBlockHdr *pHdr;
13884   void **pBt;
13885   int i;
13886   out = fopen(zFilename, "w");
13887   if( out==0 ){
13888     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13889                     zFilename);
13890     return;
13891   }
13892   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13893     char *z = (char*)pHdr;
13894     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13895     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13896             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13897     if( pHdr->nBacktrace ){
13898       fflush(out);
13899       pBt = (void**)pHdr;
13900       pBt -= pHdr->nBacktraceSlots;
13901       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13902       fprintf(out, "\n");
13903     }
13904   }
13905   fprintf(out, "COUNTS:\n");
13906   for(i=0; i<NCSIZE-1; i++){
13907     if( mem.nAlloc[i] ){
13908       fprintf(out, "   %5d: %10d %10d %10d\n", 
13909             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13910     }
13911   }
13912   if( mem.nAlloc[NCSIZE-1] ){
13913     fprintf(out, "   %5d: %10d %10d %10d\n",
13914              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13915              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13916   }
13917   fclose(out);
13918 }
13919
13920 /*
13921 ** Return the number of times sqlite3MemMalloc() has been called.
13922 */
13923 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13924   int i;
13925   int nTotal = 0;
13926   for(i=0; i<NCSIZE; i++){
13927     nTotal += mem.nAlloc[i];
13928   }
13929   return nTotal;
13930 }
13931
13932
13933 #endif /* SQLITE_MEMDEBUG */
13934
13935 /************** End of mem2.c ************************************************/
13936 /************** Begin file mem3.c ********************************************/
13937 /*
13938 ** 2007 October 14
13939 **
13940 ** The author disclaims copyright to this source code.  In place of
13941 ** a legal notice, here is a blessing:
13942 **
13943 **    May you do good and not evil.
13944 **    May you find forgiveness for yourself and forgive others.
13945 **    May you share freely, never taking more than you give.
13946 **
13947 *************************************************************************
13948 ** This file contains the C functions that implement a memory
13949 ** allocation subsystem for use by SQLite. 
13950 **
13951 ** This version of the memory allocation subsystem omits all
13952 ** use of malloc(). The SQLite user supplies a block of memory
13953 ** before calling sqlite3_initialize() from which allocations
13954 ** are made and returned by the xMalloc() and xRealloc() 
13955 ** implementations. Once sqlite3_initialize() has been called,
13956 ** the amount of memory available to SQLite is fixed and cannot
13957 ** be changed.
13958 **
13959 ** This version of the memory allocation subsystem is included
13960 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13961 */
13962
13963 /*
13964 ** This version of the memory allocator is only built into the library
13965 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13966 ** mean that the library will use a memory-pool by default, just that
13967 ** it is available. The mempool allocator is activated by calling
13968 ** sqlite3_config().
13969 */
13970 #ifdef SQLITE_ENABLE_MEMSYS3
13971
13972 /*
13973 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13974 */
13975 #define MX_SMALL 10
13976
13977
13978 /*
13979 ** Number of freelist hash slots
13980 */
13981 #define N_HASH  61
13982
13983 /*
13984 ** A memory allocation (also called a "chunk") consists of two or 
13985 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13986 ** a header that is not returned to the user.
13987 **
13988 ** A chunk is two or more blocks that is either checked out or
13989 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13990 ** size of the allocation in blocks if the allocation is free.
13991 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13992 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13993 ** is true if the previous chunk is checked out and false if the
13994 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13995 ** the previous chunk in blocks if the previous chunk is on the
13996 ** freelist. If the previous chunk is checked out, then
13997 ** u.hdr.prevSize can be part of the data for that chunk and should
13998 ** not be read or written.
13999 **
14000 ** We often identify a chunk by its index in mem3.aPool[].  When
14001 ** this is done, the chunk index refers to the second block of
14002 ** the chunk.  In this way, the first chunk has an index of 1.
14003 ** A chunk index of 0 means "no such chunk" and is the equivalent
14004 ** of a NULL pointer.
14005 **
14006 ** The second block of free chunks is of the form u.list.  The
14007 ** two fields form a double-linked list of chunks of related sizes.
14008 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
14009 ** for smaller chunks and mem3.aiHash[] for larger chunks.
14010 **
14011 ** The second block of a chunk is user data if the chunk is checked 
14012 ** out.  If a chunk is checked out, the user data may extend into
14013 ** the u.hdr.prevSize value of the following chunk.
14014 */
14015 typedef struct Mem3Block Mem3Block;
14016 struct Mem3Block {
14017   union {
14018     struct {
14019       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14020       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14021     } hdr;
14022     struct {
14023       u32 next;       /* Index in mem3.aPool[] of next free chunk */
14024       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14025     } list;
14026   } u;
14027 };
14028
14029 /*
14030 ** All of the static variables used by this module are collected
14031 ** into a single structure named "mem3".  This is to keep the
14032 ** static variables organized and to reduce namespace pollution
14033 ** when this module is combined with other in the amalgamation.
14034 */
14035 static SQLITE_WSD struct Mem3Global {
14036   /*
14037   ** Memory available for allocation. nPool is the size of the array
14038   ** (in Mem3Blocks) pointed to by aPool less 2.
14039   */
14040   u32 nPool;
14041   Mem3Block *aPool;
14042
14043   /*
14044   ** True if we are evaluating an out-of-memory callback.
14045   */
14046   int alarmBusy;
14047   
14048   /*
14049   ** Mutex to control access to the memory allocation subsystem.
14050   */
14051   sqlite3_mutex *mutex;
14052   
14053   /*
14054   ** The minimum amount of free space that we have seen.
14055   */
14056   u32 mnMaster;
14057
14058   /*
14059   ** iMaster is the index of the master chunk.  Most new allocations
14060   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14061   ** of the current master.  iMaster is 0 if there is not master chunk.
14062   ** The master chunk is not in either the aiHash[] or aiSmall[].
14063   */
14064   u32 iMaster;
14065   u32 szMaster;
14066
14067   /*
14068   ** Array of lists of free blocks according to the block size 
14069   ** for smaller chunks, or a hash on the block size for larger
14070   ** chunks.
14071   */
14072   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14073   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14074 } mem3 = { 97535575 };
14075
14076 #define mem3 GLOBAL(struct Mem3Global, mem3)
14077
14078 /*
14079 ** Unlink the chunk at mem3.aPool[i] from list it is currently
14080 ** on.  *pRoot is the list that i is a member of.
14081 */
14082 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14083   u32 next = mem3.aPool[i].u.list.next;
14084   u32 prev = mem3.aPool[i].u.list.prev;
14085   assert( sqlite3_mutex_held(mem3.mutex) );
14086   if( prev==0 ){
14087     *pRoot = next;
14088   }else{
14089     mem3.aPool[prev].u.list.next = next;
14090   }
14091   if( next ){
14092     mem3.aPool[next].u.list.prev = prev;
14093   }
14094   mem3.aPool[i].u.list.next = 0;
14095   mem3.aPool[i].u.list.prev = 0;
14096 }
14097
14098 /*
14099 ** Unlink the chunk at index i from 
14100 ** whatever list is currently a member of.
14101 */
14102 static void memsys3Unlink(u32 i){
14103   u32 size, hash;
14104   assert( sqlite3_mutex_held(mem3.mutex) );
14105   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14106   assert( i>=1 );
14107   size = mem3.aPool[i-1].u.hdr.size4x/4;
14108   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14109   assert( size>=2 );
14110   if( size <= MX_SMALL ){
14111     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14112   }else{
14113     hash = size % N_HASH;
14114     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14115   }
14116 }
14117
14118 /*
14119 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
14120 ** at *pRoot.
14121 */
14122 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14123   assert( sqlite3_mutex_held(mem3.mutex) );
14124   mem3.aPool[i].u.list.next = *pRoot;
14125   mem3.aPool[i].u.list.prev = 0;
14126   if( *pRoot ){
14127     mem3.aPool[*pRoot].u.list.prev = i;
14128   }
14129   *pRoot = i;
14130 }
14131
14132 /*
14133 ** Link the chunk at index i into either the appropriate
14134 ** small chunk list, or into the large chunk hash table.
14135 */
14136 static void memsys3Link(u32 i){
14137   u32 size, hash;
14138   assert( sqlite3_mutex_held(mem3.mutex) );
14139   assert( i>=1 );
14140   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14141   size = mem3.aPool[i-1].u.hdr.size4x/4;
14142   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14143   assert( size>=2 );
14144   if( size <= MX_SMALL ){
14145     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14146   }else{
14147     hash = size % N_HASH;
14148     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14149   }
14150 }
14151
14152 /*
14153 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14154 ** will already be held (obtained by code in malloc.c) if
14155 ** sqlite3GlobalConfig.bMemStat is true.
14156 */
14157 static void memsys3Enter(void){
14158   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14159     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14160   }
14161   sqlite3_mutex_enter(mem3.mutex);
14162 }
14163 static void memsys3Leave(void){
14164   sqlite3_mutex_leave(mem3.mutex);
14165 }
14166
14167 /*
14168 ** Called when we are unable to satisfy an allocation of nBytes.
14169 */
14170 static void memsys3OutOfMemory(int nByte){
14171   if( !mem3.alarmBusy ){
14172     mem3.alarmBusy = 1;
14173     assert( sqlite3_mutex_held(mem3.mutex) );
14174     sqlite3_mutex_leave(mem3.mutex);
14175     sqlite3_release_memory(nByte);
14176     sqlite3_mutex_enter(mem3.mutex);
14177     mem3.alarmBusy = 0;
14178   }
14179 }
14180
14181
14182 /*
14183 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
14184 ** size parameters for check-out and return a pointer to the 
14185 ** user portion of the chunk.
14186 */
14187 static void *memsys3Checkout(u32 i, u32 nBlock){
14188   u32 x;
14189   assert( sqlite3_mutex_held(mem3.mutex) );
14190   assert( i>=1 );
14191   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14192   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14193   x = mem3.aPool[i-1].u.hdr.size4x;
14194   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14195   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14196   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14197   return &mem3.aPool[i];
14198 }
14199
14200 /*
14201 ** Carve a piece off of the end of the mem3.iMaster free chunk.
14202 ** Return a pointer to the new allocation.  Or, if the master chunk
14203 ** is not large enough, return 0.
14204 */
14205 static void *memsys3FromMaster(u32 nBlock){
14206   assert( sqlite3_mutex_held(mem3.mutex) );
14207   assert( mem3.szMaster>=nBlock );
14208   if( nBlock>=mem3.szMaster-1 ){
14209     /* Use the entire master */
14210     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14211     mem3.iMaster = 0;
14212     mem3.szMaster = 0;
14213     mem3.mnMaster = 0;
14214     return p;
14215   }else{
14216     /* Split the master block.  Return the tail. */
14217     u32 newi, x;
14218     newi = mem3.iMaster + mem3.szMaster - nBlock;
14219     assert( newi > mem3.iMaster+1 );
14220     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14221     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14222     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14223     mem3.szMaster -= nBlock;
14224     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14225     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14226     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14227     if( mem3.szMaster < mem3.mnMaster ){
14228       mem3.mnMaster = mem3.szMaster;
14229     }
14230     return (void*)&mem3.aPool[newi];
14231   }
14232 }
14233
14234 /*
14235 ** *pRoot is the head of a list of free chunks of the same size
14236 ** or same size hash.  In other words, *pRoot is an entry in either
14237 ** mem3.aiSmall[] or mem3.aiHash[].  
14238 **
14239 ** This routine examines all entries on the given list and tries
14240 ** to coalesce each entries with adjacent free chunks.  
14241 **
14242 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
14243 ** the current mem3.iMaster with the new larger chunk.  In order for
14244 ** this mem3.iMaster replacement to work, the master chunk must be
14245 ** linked into the hash tables.  That is not the normal state of
14246 ** affairs, of course.  The calling routine must link the master
14247 ** chunk before invoking this routine, then must unlink the (possibly
14248 ** changed) master chunk once this routine has finished.
14249 */
14250 static void memsys3Merge(u32 *pRoot){
14251   u32 iNext, prev, size, i, x;
14252
14253   assert( sqlite3_mutex_held(mem3.mutex) );
14254   for(i=*pRoot; i>0; i=iNext){
14255     iNext = mem3.aPool[i].u.list.next;
14256     size = mem3.aPool[i-1].u.hdr.size4x;
14257     assert( (size&1)==0 );
14258     if( (size&2)==0 ){
14259       memsys3UnlinkFromList(i, pRoot);
14260       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14261       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14262       if( prev==iNext ){
14263         iNext = mem3.aPool[prev].u.list.next;
14264       }
14265       memsys3Unlink(prev);
14266       size = i + size/4 - prev;
14267       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14268       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14269       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14270       memsys3Link(prev);
14271       i = prev;
14272     }else{
14273       size /= 4;
14274     }
14275     if( size>mem3.szMaster ){
14276       mem3.iMaster = i;
14277       mem3.szMaster = size;
14278     }
14279   }
14280 }
14281
14282 /*
14283 ** Return a block of memory of at least nBytes in size.
14284 ** Return NULL if unable.
14285 **
14286 ** This function assumes that the necessary mutexes, if any, are
14287 ** already held by the caller. Hence "Unsafe".
14288 */
14289 static void *memsys3MallocUnsafe(int nByte){
14290   u32 i;
14291   u32 nBlock;
14292   u32 toFree;
14293
14294   assert( sqlite3_mutex_held(mem3.mutex) );
14295   assert( sizeof(Mem3Block)==8 );
14296   if( nByte<=12 ){
14297     nBlock = 2;
14298   }else{
14299     nBlock = (nByte + 11)/8;
14300   }
14301   assert( nBlock>=2 );
14302
14303   /* STEP 1:
14304   ** Look for an entry of the correct size in either the small
14305   ** chunk table or in the large chunk hash table.  This is
14306   ** successful most of the time (about 9 times out of 10).
14307   */
14308   if( nBlock <= MX_SMALL ){
14309     i = mem3.aiSmall[nBlock-2];
14310     if( i>0 ){
14311       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14312       return memsys3Checkout(i, nBlock);
14313     }
14314   }else{
14315     int hash = nBlock % N_HASH;
14316     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14317       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14318         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14319         return memsys3Checkout(i, nBlock);
14320       }
14321     }
14322   }
14323
14324   /* STEP 2:
14325   ** Try to satisfy the allocation by carving a piece off of the end
14326   ** of the master chunk.  This step usually works if step 1 fails.
14327   */
14328   if( mem3.szMaster>=nBlock ){
14329     return memsys3FromMaster(nBlock);
14330   }
14331
14332
14333   /* STEP 3:  
14334   ** Loop through the entire memory pool.  Coalesce adjacent free
14335   ** chunks.  Recompute the master chunk as the largest free chunk.
14336   ** Then try again to satisfy the allocation by carving a piece off
14337   ** of the end of the master chunk.  This step happens very
14338   ** rarely (we hope!)
14339   */
14340   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14341     memsys3OutOfMemory(toFree);
14342     if( mem3.iMaster ){
14343       memsys3Link(mem3.iMaster);
14344       mem3.iMaster = 0;
14345       mem3.szMaster = 0;
14346     }
14347     for(i=0; i<N_HASH; i++){
14348       memsys3Merge(&mem3.aiHash[i]);
14349     }
14350     for(i=0; i<MX_SMALL-1; i++){
14351       memsys3Merge(&mem3.aiSmall[i]);
14352     }
14353     if( mem3.szMaster ){
14354       memsys3Unlink(mem3.iMaster);
14355       if( mem3.szMaster>=nBlock ){
14356         return memsys3FromMaster(nBlock);
14357       }
14358     }
14359   }
14360
14361   /* If none of the above worked, then we fail. */
14362   return 0;
14363 }
14364
14365 /*
14366 ** Free an outstanding memory allocation.
14367 **
14368 ** This function assumes that the necessary mutexes, if any, are
14369 ** already held by the caller. Hence "Unsafe".
14370 */
14371 void memsys3FreeUnsafe(void *pOld){
14372   Mem3Block *p = (Mem3Block*)pOld;
14373   int i;
14374   u32 size, x;
14375   assert( sqlite3_mutex_held(mem3.mutex) );
14376   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14377   i = p - mem3.aPool;
14378   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14379   size = mem3.aPool[i-1].u.hdr.size4x/4;
14380   assert( i+size<=mem3.nPool+1 );
14381   mem3.aPool[i-1].u.hdr.size4x &= ~1;
14382   mem3.aPool[i+size-1].u.hdr.prevSize = size;
14383   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14384   memsys3Link(i);
14385
14386   /* Try to expand the master using the newly freed chunk */
14387   if( mem3.iMaster ){
14388     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14389       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14390       mem3.iMaster -= size;
14391       mem3.szMaster += size;
14392       memsys3Unlink(mem3.iMaster);
14393       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14394       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14395       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14396     }
14397     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14398     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14399       memsys3Unlink(mem3.iMaster+mem3.szMaster);
14400       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14401       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14402       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14403     }
14404   }
14405 }
14406
14407 /*
14408 ** Return the size of an outstanding allocation, in bytes.  The
14409 ** size returned omits the 8-byte header overhead.  This only
14410 ** works for chunks that are currently checked out.
14411 */
14412 static int memsys3Size(void *p){
14413   Mem3Block *pBlock;
14414   if( p==0 ) return 0;
14415   pBlock = (Mem3Block*)p;
14416   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14417   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14418 }
14419
14420 /*
14421 ** Round up a request size to the next valid allocation size.
14422 */
14423 static int memsys3Roundup(int n){
14424   if( n<=12 ){
14425     return 12;
14426   }else{
14427     return ((n+11)&~7) - 4;
14428   }
14429 }
14430
14431 /*
14432 ** Allocate nBytes of memory.
14433 */
14434 static void *memsys3Malloc(int nBytes){
14435   sqlite3_int64 *p;
14436   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14437   memsys3Enter();
14438   p = memsys3MallocUnsafe(nBytes);
14439   memsys3Leave();
14440   return (void*)p; 
14441 }
14442
14443 /*
14444 ** Free memory.
14445 */
14446 void memsys3Free(void *pPrior){
14447   assert( pPrior );
14448   memsys3Enter();
14449   memsys3FreeUnsafe(pPrior);
14450   memsys3Leave();
14451 }
14452
14453 /*
14454 ** Change the size of an existing memory allocation
14455 */
14456 void *memsys3Realloc(void *pPrior, int nBytes){
14457   int nOld;
14458   void *p;
14459   if( pPrior==0 ){
14460     return sqlite3_malloc(nBytes);
14461   }
14462   if( nBytes<=0 ){
14463     sqlite3_free(pPrior);
14464     return 0;
14465   }
14466   nOld = memsys3Size(pPrior);
14467   if( nBytes<=nOld && nBytes>=nOld-128 ){
14468     return pPrior;
14469   }
14470   memsys3Enter();
14471   p = memsys3MallocUnsafe(nBytes);
14472   if( p ){
14473     if( nOld<nBytes ){
14474       memcpy(p, pPrior, nOld);
14475     }else{
14476       memcpy(p, pPrior, nBytes);
14477     }
14478     memsys3FreeUnsafe(pPrior);
14479   }
14480   memsys3Leave();
14481   return p;
14482 }
14483
14484 /*
14485 ** Initialize this module.
14486 */
14487 static int memsys3Init(void *NotUsed){
14488   UNUSED_PARAMETER(NotUsed);
14489   if( !sqlite3GlobalConfig.pHeap ){
14490     return SQLITE_ERROR;
14491   }
14492
14493   /* Store a pointer to the memory block in global structure mem3. */
14494   assert( sizeof(Mem3Block)==8 );
14495   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14496   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14497
14498   /* Initialize the master block. */
14499   mem3.szMaster = mem3.nPool;
14500   mem3.mnMaster = mem3.szMaster;
14501   mem3.iMaster = 1;
14502   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14503   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14504   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14505
14506   return SQLITE_OK;
14507 }
14508
14509 /*
14510 ** Deinitialize this module.
14511 */
14512 static void memsys3Shutdown(void *NotUsed){
14513   UNUSED_PARAMETER(NotUsed);
14514   mem3.mutex = 0;
14515   return;
14516 }
14517
14518
14519
14520 /*
14521 ** Open the file indicated and write a log of all unfreed memory 
14522 ** allocations into that log.
14523 */
14524 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14525 #ifdef SQLITE_DEBUG
14526   FILE *out;
14527   u32 i, j;
14528   u32 size;
14529   if( zFilename==0 || zFilename[0]==0 ){
14530     out = stdout;
14531   }else{
14532     out = fopen(zFilename, "w");
14533     if( out==0 ){
14534       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14535                       zFilename);
14536       return;
14537     }
14538   }
14539   memsys3Enter();
14540   fprintf(out, "CHUNKS:\n");
14541   for(i=1; i<=mem3.nPool; i+=size/4){
14542     size = mem3.aPool[i-1].u.hdr.size4x;
14543     if( size/4<=1 ){
14544       fprintf(out, "%p size error\n", &mem3.aPool[i]);
14545       assert( 0 );
14546       break;
14547     }
14548     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14549       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14550       assert( 0 );
14551       break;
14552     }
14553     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14554       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14555       assert( 0 );
14556       break;
14557     }
14558     if( size&1 ){
14559       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14560     }else{
14561       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14562                   i==mem3.iMaster ? " **master**" : "");
14563     }
14564   }
14565   for(i=0; i<MX_SMALL-1; i++){
14566     if( mem3.aiSmall[i]==0 ) continue;
14567     fprintf(out, "small(%2d):", i);
14568     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14569       fprintf(out, " %p(%d)", &mem3.aPool[j],
14570               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14571     }
14572     fprintf(out, "\n"); 
14573   }
14574   for(i=0; i<N_HASH; i++){
14575     if( mem3.aiHash[i]==0 ) continue;
14576     fprintf(out, "hash(%2d):", i);
14577     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14578       fprintf(out, " %p(%d)", &mem3.aPool[j],
14579               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14580     }
14581     fprintf(out, "\n"); 
14582   }
14583   fprintf(out, "master=%d\n", mem3.iMaster);
14584   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14585   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14586   sqlite3_mutex_leave(mem3.mutex);
14587   if( out==stdout ){
14588     fflush(stdout);
14589   }else{
14590     fclose(out);
14591   }
14592 #else
14593   UNUSED_PARAMETER(zFilename);
14594 #endif
14595 }
14596
14597 /*
14598 ** This routine is the only routine in this file with external 
14599 ** linkage.
14600 **
14601 ** Populate the low-level memory allocation function pointers in
14602 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14603 ** arguments specify the block of memory to manage.
14604 **
14605 ** This routine is only called by sqlite3_config(), and therefore
14606 ** is not required to be threadsafe (it is not).
14607 */
14608 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14609   static const sqlite3_mem_methods mempoolMethods = {
14610      memsys3Malloc,
14611      memsys3Free,
14612      memsys3Realloc,
14613      memsys3Size,
14614      memsys3Roundup,
14615      memsys3Init,
14616      memsys3Shutdown,
14617      0
14618   };
14619   return &mempoolMethods;
14620 }
14621
14622 #endif /* SQLITE_ENABLE_MEMSYS3 */
14623
14624 /************** End of mem3.c ************************************************/
14625 /************** Begin file mem5.c ********************************************/
14626 /*
14627 ** 2007 October 14
14628 **
14629 ** The author disclaims copyright to this source code.  In place of
14630 ** a legal notice, here is a blessing:
14631 **
14632 **    May you do good and not evil.
14633 **    May you find forgiveness for yourself and forgive others.
14634 **    May you share freely, never taking more than you give.
14635 **
14636 *************************************************************************
14637 ** This file contains the C functions that implement a memory
14638 ** allocation subsystem for use by SQLite. 
14639 **
14640 ** This version of the memory allocation subsystem omits all
14641 ** use of malloc(). The application gives SQLite a block of memory
14642 ** before calling sqlite3_initialize() from which allocations
14643 ** are made and returned by the xMalloc() and xRealloc() 
14644 ** implementations. Once sqlite3_initialize() has been called,
14645 ** the amount of memory available to SQLite is fixed and cannot
14646 ** be changed.
14647 **
14648 ** This version of the memory allocation subsystem is included
14649 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14650 **
14651 ** This memory allocator uses the following algorithm:
14652 **
14653 **   1.  All memory allocations sizes are rounded up to a power of 2.
14654 **
14655 **   2.  If two adjacent free blocks are the halves of a larger block,
14656 **       then the two blocks are coalesed into the single larger block.
14657 **
14658 **   3.  New memory is allocated from the first available free block.
14659 **
14660 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
14661 ** Concerning Dynamic Storage Allocation". Journal of the Association for
14662 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
14663 ** 
14664 ** Let n be the size of the largest allocation divided by the minimum
14665 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
14666 ** be the maximum amount of memory ever outstanding at one time.  Let
14667 ** N be the total amount of memory available for allocation.  Robson
14668 ** proved that this memory allocator will never breakdown due to 
14669 ** fragmentation as long as the following constraint holds:
14670 **
14671 **      N >=  M*(1 + log2(n)/2) - n + 1
14672 **
14673 ** The sqlite3_status() logic tracks the maximum values of n and M so
14674 ** that an application can, at any time, verify this constraint.
14675 */
14676
14677 /*
14678 ** This version of the memory allocator is used only when 
14679 ** SQLITE_ENABLE_MEMSYS5 is defined.
14680 */
14681 #ifdef SQLITE_ENABLE_MEMSYS5
14682
14683 /*
14684 ** A minimum allocation is an instance of the following structure.
14685 ** Larger allocations are an array of these structures where the
14686 ** size of the array is a power of 2.
14687 **
14688 ** The size of this object must be a power of two.  That fact is
14689 ** verified in memsys5Init().
14690 */
14691 typedef struct Mem5Link Mem5Link;
14692 struct Mem5Link {
14693   int next;       /* Index of next free chunk */
14694   int prev;       /* Index of previous free chunk */
14695 };
14696
14697 /*
14698 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
14699 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
14700 ** it is not actually possible to reach this limit.
14701 */
14702 #define LOGMAX 30
14703
14704 /*
14705 ** Masks used for mem5.aCtrl[] elements.
14706 */
14707 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
14708 #define CTRL_FREE     0x20    /* True if not checked out */
14709
14710 /*
14711 ** All of the static variables used by this module are collected
14712 ** into a single structure named "mem5".  This is to keep the
14713 ** static variables organized and to reduce namespace pollution
14714 ** when this module is combined with other in the amalgamation.
14715 */
14716 static SQLITE_WSD struct Mem5Global {
14717   /*
14718   ** Memory available for allocation
14719   */
14720   int szAtom;      /* Smallest possible allocation in bytes */
14721   int nBlock;      /* Number of szAtom sized blocks in zPool */
14722   u8 *zPool;       /* Memory available to be allocated */
14723   
14724   /*
14725   ** Mutex to control access to the memory allocation subsystem.
14726   */
14727   sqlite3_mutex *mutex;
14728
14729   /*
14730   ** Performance statistics
14731   */
14732   u64 nAlloc;         /* Total number of calls to malloc */
14733   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14734   u64 totalExcess;    /* Total internal fragmentation */
14735   u32 currentOut;     /* Current checkout, including internal fragmentation */
14736   u32 currentCount;   /* Current number of distinct checkouts */
14737   u32 maxOut;         /* Maximum instantaneous currentOut */
14738   u32 maxCount;       /* Maximum instantaneous currentCount */
14739   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14740   
14741   /*
14742   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
14743   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
14744   ** and so forth.
14745   */
14746   int aiFreelist[LOGMAX+1];
14747
14748   /*
14749   ** Space for tracking which blocks are checked out and the size
14750   ** of each block.  One byte per block.
14751   */
14752   u8 *aCtrl;
14753
14754 } mem5 = { 0 };
14755
14756 /*
14757 ** Access the static variable through a macro for SQLITE_OMIT_WSD
14758 */
14759 #define mem5 GLOBAL(struct Mem5Global, mem5)
14760
14761 /*
14762 ** Assuming mem5.zPool is divided up into an array of Mem5Link
14763 ** structures, return a pointer to the idx-th such lik.
14764 */
14765 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
14766
14767 /*
14768 ** Unlink the chunk at mem5.aPool[i] from list it is currently
14769 ** on.  It should be found on mem5.aiFreelist[iLogsize].
14770 */
14771 static void memsys5Unlink(int i, int iLogsize){
14772   int next, prev;
14773   assert( i>=0 && i<mem5.nBlock );
14774   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14775   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14776
14777   next = MEM5LINK(i)->next;
14778   prev = MEM5LINK(i)->prev;
14779   if( prev<0 ){
14780     mem5.aiFreelist[iLogsize] = next;
14781   }else{
14782     MEM5LINK(prev)->next = next;
14783   }
14784   if( next>=0 ){
14785     MEM5LINK(next)->prev = prev;
14786   }
14787 }
14788
14789 /*
14790 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14791 ** free list.
14792 */
14793 static void memsys5Link(int i, int iLogsize){
14794   int x;
14795   assert( sqlite3_mutex_held(mem5.mutex) );
14796   assert( i>=0 && i<mem5.nBlock );
14797   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14798   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14799
14800   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14801   MEM5LINK(i)->prev = -1;
14802   if( x>=0 ){
14803     assert( x<mem5.nBlock );
14804     MEM5LINK(x)->prev = i;
14805   }
14806   mem5.aiFreelist[iLogsize] = i;
14807 }
14808
14809 /*
14810 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14811 ** will already be held (obtained by code in malloc.c) if
14812 ** sqlite3GlobalConfig.bMemStat is true.
14813 */
14814 static void memsys5Enter(void){
14815   sqlite3_mutex_enter(mem5.mutex);
14816 }
14817 static void memsys5Leave(void){
14818   sqlite3_mutex_leave(mem5.mutex);
14819 }
14820
14821 /*
14822 ** Return the size of an outstanding allocation, in bytes.  The
14823 ** size returned omits the 8-byte header overhead.  This only
14824 ** works for chunks that are currently checked out.
14825 */
14826 static int memsys5Size(void *p){
14827   int iSize = 0;
14828   if( p ){
14829     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14830     assert( i>=0 && i<mem5.nBlock );
14831     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14832   }
14833   return iSize;
14834 }
14835
14836 /*
14837 ** Find the first entry on the freelist iLogsize.  Unlink that
14838 ** entry and return its index. 
14839 */
14840 static int memsys5UnlinkFirst(int iLogsize){
14841   int i;
14842   int iFirst;
14843
14844   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14845   i = iFirst = mem5.aiFreelist[iLogsize];
14846   assert( iFirst>=0 );
14847   while( i>0 ){
14848     if( i<iFirst ) iFirst = i;
14849     i = MEM5LINK(i)->next;
14850   }
14851   memsys5Unlink(iFirst, iLogsize);
14852   return iFirst;
14853 }
14854
14855 /*
14856 ** Return a block of memory of at least nBytes in size.
14857 ** Return NULL if unable.  Return NULL if nBytes==0.
14858 **
14859 ** The caller guarantees that nByte positive.
14860 **
14861 ** The caller has obtained a mutex prior to invoking this
14862 ** routine so there is never any chance that two or more
14863 ** threads can be in this routine at the same time.
14864 */
14865 static void *memsys5MallocUnsafe(int nByte){
14866   int i;           /* Index of a mem5.aPool[] slot */
14867   int iBin;        /* Index into mem5.aiFreelist[] */
14868   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14869   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14870
14871   /* nByte must be a positive */
14872   assert( nByte>0 );
14873
14874   /* Keep track of the maximum allocation request.  Even unfulfilled
14875   ** requests are counted */
14876   if( (u32)nByte>mem5.maxRequest ){
14877     mem5.maxRequest = nByte;
14878   }
14879
14880   /* Abort if the requested allocation size is larger than the largest
14881   ** power of two that we can represent using 32-bit signed integers.
14882   */
14883   if( nByte > 0x40000000 ){
14884     return 0;
14885   }
14886
14887   /* Round nByte up to the next valid power of two */
14888   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14889
14890   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14891   ** block.  If not, then split a block of the next larger power of
14892   ** two in order to create a new free block of size iLogsize.
14893   */
14894   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14895   if( iBin>LOGMAX ){
14896     testcase( sqlite3GlobalConfig.xLog!=0 );
14897     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14898     return 0;
14899   }
14900   i = memsys5UnlinkFirst(iBin);
14901   while( iBin>iLogsize ){
14902     int newSize;
14903
14904     iBin--;
14905     newSize = 1 << iBin;
14906     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14907     memsys5Link(i+newSize, iBin);
14908   }
14909   mem5.aCtrl[i] = iLogsize;
14910
14911   /* Update allocator performance statistics. */
14912   mem5.nAlloc++;
14913   mem5.totalAlloc += iFullSz;
14914   mem5.totalExcess += iFullSz - nByte;
14915   mem5.currentCount++;
14916   mem5.currentOut += iFullSz;
14917   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14918   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14919
14920   /* Return a pointer to the allocated memory. */
14921   return (void*)&mem5.zPool[i*mem5.szAtom];
14922 }
14923
14924 /*
14925 ** Free an outstanding memory allocation.
14926 */
14927 static void memsys5FreeUnsafe(void *pOld){
14928   u32 size, iLogsize;
14929   int iBlock;
14930
14931   /* Set iBlock to the index of the block pointed to by pOld in 
14932   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14933   */
14934   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14935
14936   /* Check that the pointer pOld points to a valid, non-free block. */
14937   assert( iBlock>=0 && iBlock<mem5.nBlock );
14938   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14939   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14940
14941   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14942   size = 1<<iLogsize;
14943   assert( iBlock+size-1<(u32)mem5.nBlock );
14944
14945   mem5.aCtrl[iBlock] |= CTRL_FREE;
14946   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14947   assert( mem5.currentCount>0 );
14948   assert( mem5.currentOut>=(size*mem5.szAtom) );
14949   mem5.currentCount--;
14950   mem5.currentOut -= size*mem5.szAtom;
14951   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14952   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14953
14954   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14955   while( ALWAYS(iLogsize<LOGMAX) ){
14956     int iBuddy;
14957     if( (iBlock>>iLogsize) & 1 ){
14958       iBuddy = iBlock - size;
14959     }else{
14960       iBuddy = iBlock + size;
14961     }
14962     assert( iBuddy>=0 );
14963     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14964     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14965     memsys5Unlink(iBuddy, iLogsize);
14966     iLogsize++;
14967     if( iBuddy<iBlock ){
14968       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14969       mem5.aCtrl[iBlock] = 0;
14970       iBlock = iBuddy;
14971     }else{
14972       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14973       mem5.aCtrl[iBuddy] = 0;
14974     }
14975     size *= 2;
14976   }
14977   memsys5Link(iBlock, iLogsize);
14978 }
14979
14980 /*
14981 ** Allocate nBytes of memory
14982 */
14983 static void *memsys5Malloc(int nBytes){
14984   sqlite3_int64 *p = 0;
14985   if( nBytes>0 ){
14986     memsys5Enter();
14987     p = memsys5MallocUnsafe(nBytes);
14988     memsys5Leave();
14989   }
14990   return (void*)p; 
14991 }
14992
14993 /*
14994 ** Free memory.
14995 **
14996 ** The outer layer memory allocator prevents this routine from
14997 ** being called with pPrior==0.
14998 */
14999 static void memsys5Free(void *pPrior){
15000   assert( pPrior!=0 );
15001   memsys5Enter();
15002   memsys5FreeUnsafe(pPrior);
15003   memsys5Leave();  
15004 }
15005
15006 /*
15007 ** Change the size of an existing memory allocation.
15008 **
15009 ** The outer layer memory allocator prevents this routine from
15010 ** being called with pPrior==0.  
15011 **
15012 ** nBytes is always a value obtained from a prior call to
15013 ** memsys5Round().  Hence nBytes is always a non-negative power
15014 ** of two.  If nBytes==0 that means that an oversize allocation
15015 ** (an allocation larger than 0x40000000) was requested and this
15016 ** routine should return 0 without freeing pPrior.
15017 */
15018 static void *memsys5Realloc(void *pPrior, int nBytes){
15019   int nOld;
15020   void *p;
15021   assert( pPrior!=0 );
15022   assert( (nBytes&(nBytes-1))==0 );
15023   assert( nBytes>=0 );
15024   if( nBytes==0 ){
15025     return 0;
15026   }
15027   nOld = memsys5Size(pPrior);
15028   if( nBytes<=nOld ){
15029     return pPrior;
15030   }
15031   memsys5Enter();
15032   p = memsys5MallocUnsafe(nBytes);
15033   if( p ){
15034     memcpy(p, pPrior, nOld);
15035     memsys5FreeUnsafe(pPrior);
15036   }
15037   memsys5Leave();
15038   return p;
15039 }
15040
15041 /*
15042 ** Round up a request size to the next valid allocation size.  If
15043 ** the allocation is too large to be handled by this allocation system,
15044 ** return 0.
15045 **
15046 ** All allocations must be a power of two and must be expressed by a
15047 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15048 ** or 1073741824 bytes.
15049 */
15050 static int memsys5Roundup(int n){
15051   int iFullSz;
15052   if( n > 0x40000000 ) return 0;
15053   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15054   return iFullSz;
15055 }
15056
15057 /*
15058 ** Return the ceiling of the logarithm base 2 of iValue.
15059 **
15060 ** Examples:   memsys5Log(1) -> 0
15061 **             memsys5Log(2) -> 1
15062 **             memsys5Log(4) -> 2
15063 **             memsys5Log(5) -> 3
15064 **             memsys5Log(8) -> 3
15065 **             memsys5Log(9) -> 4
15066 */
15067 static int memsys5Log(int iValue){
15068   int iLog;
15069   for(iLog=0; (1<<iLog)<iValue; iLog++);
15070   return iLog;
15071 }
15072
15073 /*
15074 ** Initialize the memory allocator.
15075 **
15076 ** This routine is not threadsafe.  The caller must be holding a mutex
15077 ** to prevent multiple threads from entering at the same time.
15078 */
15079 static int memsys5Init(void *NotUsed){
15080   int ii;            /* Loop counter */
15081   int nByte;         /* Number of bytes of memory available to this allocator */
15082   u8 *zByte;         /* Memory usable by this allocator */
15083   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15084   int iOffset;       /* An offset into mem5.aCtrl[] */
15085
15086   UNUSED_PARAMETER(NotUsed);
15087
15088   /* For the purposes of this routine, disable the mutex */
15089   mem5.mutex = 0;
15090
15091   /* The size of a Mem5Link object must be a power of two.  Verify that
15092   ** this is case.
15093   */
15094   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15095
15096   nByte = sqlite3GlobalConfig.nHeap;
15097   zByte = (u8*)sqlite3GlobalConfig.pHeap;
15098   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15099
15100   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15101   mem5.szAtom = (1<<nMinLog);
15102   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15103     mem5.szAtom = mem5.szAtom << 1;
15104   }
15105
15106   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15107   mem5.zPool = zByte;
15108   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15109
15110   for(ii=0; ii<=LOGMAX; ii++){
15111     mem5.aiFreelist[ii] = -1;
15112   }
15113
15114   iOffset = 0;
15115   for(ii=LOGMAX; ii>=0; ii--){
15116     int nAlloc = (1<<ii);
15117     if( (iOffset+nAlloc)<=mem5.nBlock ){
15118       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15119       memsys5Link(iOffset, ii);
15120       iOffset += nAlloc;
15121     }
15122     assert((iOffset+nAlloc)>mem5.nBlock);
15123   }
15124
15125   /* If a mutex is required for normal operation, allocate one */
15126   if( sqlite3GlobalConfig.bMemstat==0 ){
15127     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15128   }
15129
15130   return SQLITE_OK;
15131 }
15132
15133 /*
15134 ** Deinitialize this module.
15135 */
15136 static void memsys5Shutdown(void *NotUsed){
15137   UNUSED_PARAMETER(NotUsed);
15138   mem5.mutex = 0;
15139   return;
15140 }
15141
15142 #ifdef SQLITE_TEST
15143 /*
15144 ** Open the file indicated and write a log of all unfreed memory 
15145 ** allocations into that log.
15146 */
15147 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15148   FILE *out;
15149   int i, j, n;
15150   int nMinLog;
15151
15152   if( zFilename==0 || zFilename[0]==0 ){
15153     out = stdout;
15154   }else{
15155     out = fopen(zFilename, "w");
15156     if( out==0 ){
15157       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15158                       zFilename);
15159       return;
15160     }
15161   }
15162   memsys5Enter();
15163   nMinLog = memsys5Log(mem5.szAtom);
15164   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15165     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15166     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15167   }
15168   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15169   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15170   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15171   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15172   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15173   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15174   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15175   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15176   memsys5Leave();
15177   if( out==stdout ){
15178     fflush(stdout);
15179   }else{
15180     fclose(out);
15181   }
15182 }
15183 #endif
15184
15185 /*
15186 ** This routine is the only routine in this file with external 
15187 ** linkage. It returns a pointer to a static sqlite3_mem_methods
15188 ** struct populated with the memsys5 methods.
15189 */
15190 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15191   static const sqlite3_mem_methods memsys5Methods = {
15192      memsys5Malloc,
15193      memsys5Free,
15194      memsys5Realloc,
15195      memsys5Size,
15196      memsys5Roundup,
15197      memsys5Init,
15198      memsys5Shutdown,
15199      0
15200   };
15201   return &memsys5Methods;
15202 }
15203
15204 #endif /* SQLITE_ENABLE_MEMSYS5 */
15205
15206 /************** End of mem5.c ************************************************/
15207 /************** Begin file mutex.c *******************************************/
15208 /*
15209 ** 2007 August 14
15210 **
15211 ** The author disclaims copyright to this source code.  In place of
15212 ** a legal notice, here is a blessing:
15213 **
15214 **    May you do good and not evil.
15215 **    May you find forgiveness for yourself and forgive others.
15216 **    May you share freely, never taking more than you give.
15217 **
15218 *************************************************************************
15219 ** This file contains the C functions that implement mutexes.
15220 **
15221 ** This file contains code that is common across all mutex implementations.
15222 */
15223
15224 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
15225 /*
15226 ** For debugging purposes, record when the mutex subsystem is initialized
15227 ** and uninitialized so that we can assert() if there is an attempt to
15228 ** allocate a mutex while the system is uninitialized.
15229 */
15230 static SQLITE_WSD int mutexIsInit = 0;
15231 #endif /* SQLITE_DEBUG */
15232
15233
15234 #ifndef SQLITE_MUTEX_OMIT
15235 /*
15236 ** Initialize the mutex system.
15237 */
15238 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
15239   int rc = SQLITE_OK;
15240   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15241     /* If the xMutexAlloc method has not been set, then the user did not
15242     ** install a mutex implementation via sqlite3_config() prior to 
15243     ** sqlite3_initialize() being called. This block copies pointers to
15244     ** the default implementation into the sqlite3GlobalConfig structure.
15245     */
15246     sqlite3_mutex_methods const *pFrom;
15247     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
15248
15249     if( sqlite3GlobalConfig.bCoreMutex ){
15250       pFrom = sqlite3DefaultMutex();
15251     }else{
15252       pFrom = sqlite3NoopMutex();
15253     }
15254     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
15255     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
15256            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
15257     pTo->xMutexAlloc = pFrom->xMutexAlloc;
15258   }
15259   rc = sqlite3GlobalConfig.mutex.xMutexInit();
15260
15261 #ifdef SQLITE_DEBUG
15262   GLOBAL(int, mutexIsInit) = 1;
15263 #endif
15264
15265   return rc;
15266 }
15267
15268 /*
15269 ** Shutdown the mutex system. This call frees resources allocated by
15270 ** sqlite3MutexInit().
15271 */
15272 SQLITE_PRIVATE int sqlite3MutexEnd(void){
15273   int rc = SQLITE_OK;
15274   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15275     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15276   }
15277
15278 #ifdef SQLITE_DEBUG
15279   GLOBAL(int, mutexIsInit) = 0;
15280 #endif
15281
15282   return rc;
15283 }
15284
15285 /*
15286 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15287 */
15288 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15289 #ifndef SQLITE_OMIT_AUTOINIT
15290   if( sqlite3_initialize() ) return 0;
15291 #endif
15292   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15293 }
15294
15295 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15296   if( !sqlite3GlobalConfig.bCoreMutex ){
15297     return 0;
15298   }
15299   assert( GLOBAL(int, mutexIsInit) );
15300   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15301 }
15302
15303 /*
15304 ** Free a dynamic mutex.
15305 */
15306 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15307   if( p ){
15308     sqlite3GlobalConfig.mutex.xMutexFree(p);
15309   }
15310 }
15311
15312 /*
15313 ** Obtain the mutex p. If some other thread already has the mutex, block
15314 ** until it can be obtained.
15315 */
15316 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15317   if( p ){
15318     sqlite3GlobalConfig.mutex.xMutexEnter(p);
15319   }
15320 }
15321
15322 /*
15323 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15324 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15325 */
15326 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15327   int rc = SQLITE_OK;
15328   if( p ){
15329     return sqlite3GlobalConfig.mutex.xMutexTry(p);
15330   }
15331   return rc;
15332 }
15333
15334 /*
15335 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
15336 ** entered by the same thread.  The behavior is undefined if the mutex 
15337 ** is not currently entered. If a NULL pointer is passed as an argument
15338 ** this function is a no-op.
15339 */
15340 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15341   if( p ){
15342     sqlite3GlobalConfig.mutex.xMutexLeave(p);
15343   }
15344 }
15345
15346 #ifndef NDEBUG
15347 /*
15348 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15349 ** intended for use inside assert() statements.
15350 */
15351 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15352   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15353 }
15354 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15355   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15356 }
15357 #endif
15358
15359 #endif /* SQLITE_MUTEX_OMIT */
15360
15361 /************** End of mutex.c ***********************************************/
15362 /************** Begin file mutex_noop.c **************************************/
15363 /*
15364 ** 2008 October 07
15365 **
15366 ** The author disclaims copyright to this source code.  In place of
15367 ** a legal notice, here is a blessing:
15368 **
15369 **    May you do good and not evil.
15370 **    May you find forgiveness for yourself and forgive others.
15371 **    May you share freely, never taking more than you give.
15372 **
15373 *************************************************************************
15374 ** This file contains the C functions that implement mutexes.
15375 **
15376 ** This implementation in this file does not provide any mutual
15377 ** exclusion and is thus suitable for use only in applications
15378 ** that use SQLite in a single thread.  The routines defined
15379 ** here are place-holders.  Applications can substitute working
15380 ** mutex routines at start-time using the
15381 **
15382 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15383 **
15384 ** interface.
15385 **
15386 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
15387 ** that does error checking on mutexes to make sure they are being
15388 ** called correctly.
15389 */
15390
15391 #ifndef SQLITE_MUTEX_OMIT
15392
15393 #ifndef SQLITE_DEBUG
15394 /*
15395 ** Stub routines for all mutex methods.
15396 **
15397 ** This routines provide no mutual exclusion or error checking.
15398 */
15399 static int noopMutexInit(void){ return SQLITE_OK; }
15400 static int noopMutexEnd(void){ return SQLITE_OK; }
15401 static sqlite3_mutex *noopMutexAlloc(int id){ 
15402   UNUSED_PARAMETER(id);
15403   return (sqlite3_mutex*)8; 
15404 }
15405 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15406 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15407 static int noopMutexTry(sqlite3_mutex *p){
15408   UNUSED_PARAMETER(p);
15409   return SQLITE_OK;
15410 }
15411 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15412
15413 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15414   static const sqlite3_mutex_methods sMutex = {
15415     noopMutexInit,
15416     noopMutexEnd,
15417     noopMutexAlloc,
15418     noopMutexFree,
15419     noopMutexEnter,
15420     noopMutexTry,
15421     noopMutexLeave,
15422
15423     0,
15424     0,
15425   };
15426
15427   return &sMutex;
15428 }
15429 #endif /* !SQLITE_DEBUG */
15430
15431 #ifdef SQLITE_DEBUG
15432 /*
15433 ** In this implementation, error checking is provided for testing
15434 ** and debugging purposes.  The mutexes still do not provide any
15435 ** mutual exclusion.
15436 */
15437
15438 /*
15439 ** The mutex object
15440 */
15441 typedef struct sqlite3_debug_mutex {
15442   int id;     /* The mutex type */
15443   int cnt;    /* Number of entries without a matching leave */
15444 } sqlite3_debug_mutex;
15445
15446 /*
15447 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15448 ** intended for use inside assert() statements.
15449 */
15450 static int debugMutexHeld(sqlite3_mutex *pX){
15451   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15452   return p==0 || p->cnt>0;
15453 }
15454 static int debugMutexNotheld(sqlite3_mutex *pX){
15455   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15456   return p==0 || p->cnt==0;
15457 }
15458
15459 /*
15460 ** Initialize and deinitialize the mutex subsystem.
15461 */
15462 static int debugMutexInit(void){ return SQLITE_OK; }
15463 static int debugMutexEnd(void){ return SQLITE_OK; }
15464
15465 /*
15466 ** The sqlite3_mutex_alloc() routine allocates a new
15467 ** mutex and returns a pointer to it.  If it returns NULL
15468 ** that means that a mutex could not be allocated. 
15469 */
15470 static sqlite3_mutex *debugMutexAlloc(int id){
15471   static sqlite3_debug_mutex aStatic[6];
15472   sqlite3_debug_mutex *pNew = 0;
15473   switch( id ){
15474     case SQLITE_MUTEX_FAST:
15475     case SQLITE_MUTEX_RECURSIVE: {
15476       pNew = sqlite3Malloc(sizeof(*pNew));
15477       if( pNew ){
15478         pNew->id = id;
15479         pNew->cnt = 0;
15480       }
15481       break;
15482     }
15483     default: {
15484       assert( id-2 >= 0 );
15485       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15486       pNew = &aStatic[id-2];
15487       pNew->id = id;
15488       break;
15489     }
15490   }
15491   return (sqlite3_mutex*)pNew;
15492 }
15493
15494 /*
15495 ** This routine deallocates a previously allocated mutex.
15496 */
15497 static void debugMutexFree(sqlite3_mutex *pX){
15498   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15499   assert( p->cnt==0 );
15500   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15501   sqlite3_free(p);
15502 }
15503
15504 /*
15505 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15506 ** to enter a mutex.  If another thread is already within the mutex,
15507 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15508 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15509 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15510 ** be entered multiple times by the same thread.  In such cases the,
15511 ** mutex must be exited an equal number of times before another thread
15512 ** can enter.  If the same thread tries to enter any other kind of mutex
15513 ** more than once, the behavior is undefined.
15514 */
15515 static void debugMutexEnter(sqlite3_mutex *pX){
15516   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15517   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15518   p->cnt++;
15519 }
15520 static int debugMutexTry(sqlite3_mutex *pX){
15521   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15522   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15523   p->cnt++;
15524   return SQLITE_OK;
15525 }
15526
15527 /*
15528 ** The sqlite3_mutex_leave() routine exits a mutex that was
15529 ** previously entered by the same thread.  The behavior
15530 ** is undefined if the mutex is not currently entered or
15531 ** is not currently allocated.  SQLite will never do either.
15532 */
15533 static void debugMutexLeave(sqlite3_mutex *pX){
15534   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15535   assert( debugMutexHeld(pX) );
15536   p->cnt--;
15537   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15538 }
15539
15540 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15541   static const sqlite3_mutex_methods sMutex = {
15542     debugMutexInit,
15543     debugMutexEnd,
15544     debugMutexAlloc,
15545     debugMutexFree,
15546     debugMutexEnter,
15547     debugMutexTry,
15548     debugMutexLeave,
15549
15550     debugMutexHeld,
15551     debugMutexNotheld
15552   };
15553
15554   return &sMutex;
15555 }
15556 #endif /* SQLITE_DEBUG */
15557
15558 /*
15559 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
15560 ** is used regardless of the run-time threadsafety setting.
15561 */
15562 #ifdef SQLITE_MUTEX_NOOP
15563 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15564   return sqlite3NoopMutex();
15565 }
15566 #endif /* SQLITE_MUTEX_NOOP */
15567 #endif /* SQLITE_MUTEX_OMIT */
15568
15569 /************** End of mutex_noop.c ******************************************/
15570 /************** Begin file mutex_os2.c ***************************************/
15571 /*
15572 ** 2007 August 28
15573 **
15574 ** The author disclaims copyright to this source code.  In place of
15575 ** a legal notice, here is a blessing:
15576 **
15577 **    May you do good and not evil.
15578 **    May you find forgiveness for yourself and forgive others.
15579 **    May you share freely, never taking more than you give.
15580 **
15581 *************************************************************************
15582 ** This file contains the C functions that implement mutexes for OS/2
15583 */
15584
15585 /*
15586 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15587 ** See the mutex.h file for details.
15588 */
15589 #ifdef SQLITE_MUTEX_OS2
15590
15591 /********************** OS/2 Mutex Implementation **********************
15592 **
15593 ** This implementation of mutexes is built using the OS/2 API.
15594 */
15595
15596 /*
15597 ** The mutex object
15598 ** Each recursive mutex is an instance of the following structure.
15599 */
15600 struct sqlite3_mutex {
15601   HMTX mutex;       /* Mutex controlling the lock */
15602   int  id;          /* Mutex type */
15603   int  nRef;        /* Number of references */
15604   TID  owner;       /* Thread holding this mutex */
15605 };
15606
15607 #define OS2_MUTEX_INITIALIZER   0,0,0,0
15608
15609 /*
15610 ** Initialize and deinitialize the mutex subsystem.
15611 */
15612 static int os2MutexInit(void){ return SQLITE_OK; }
15613 static int os2MutexEnd(void){ return SQLITE_OK; }
15614
15615 /*
15616 ** The sqlite3_mutex_alloc() routine allocates a new
15617 ** mutex and returns a pointer to it.  If it returns NULL
15618 ** that means that a mutex could not be allocated. 
15619 ** SQLite will unwind its stack and return an error.  The argument
15620 ** to sqlite3_mutex_alloc() is one of these integer constants:
15621 **
15622 ** <ul>
15623 ** <li>  SQLITE_MUTEX_FAST               0
15624 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15625 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15626 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15627 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15628 ** </ul>
15629 **
15630 ** The first two constants cause sqlite3_mutex_alloc() to create
15631 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15632 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15633 ** The mutex implementation does not need to make a distinction
15634 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15635 ** not want to.  But SQLite will only request a recursive mutex in
15636 ** cases where it really needs one.  If a faster non-recursive mutex
15637 ** implementation is available on the host platform, the mutex subsystem
15638 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15639 **
15640 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15641 ** a pointer to a static preexisting mutex.  Three static mutexes are
15642 ** used by the current version of SQLite.  Future versions of SQLite
15643 ** may add additional static mutexes.  Static mutexes are for internal
15644 ** use by SQLite only.  Applications that use SQLite mutexes should
15645 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15646 ** SQLITE_MUTEX_RECURSIVE.
15647 **
15648 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15649 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15650 ** returns a different mutex on every call.  But for the static
15651 ** mutex types, the same mutex is returned on every call that has
15652 ** the same type number.
15653 */
15654 static sqlite3_mutex *os2MutexAlloc(int iType){
15655   sqlite3_mutex *p = NULL;
15656   switch( iType ){
15657     case SQLITE_MUTEX_FAST:
15658     case SQLITE_MUTEX_RECURSIVE: {
15659       p = sqlite3MallocZero( sizeof(*p) );
15660       if( p ){
15661         p->id = iType;
15662         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15663           sqlite3_free( p );
15664           p = NULL;
15665         }
15666       }
15667       break;
15668     }
15669     default: {
15670       static volatile int isInit = 0;
15671       static sqlite3_mutex staticMutexes[] = {
15672         { OS2_MUTEX_INITIALIZER, },
15673         { OS2_MUTEX_INITIALIZER, },
15674         { OS2_MUTEX_INITIALIZER, },
15675         { OS2_MUTEX_INITIALIZER, },
15676         { OS2_MUTEX_INITIALIZER, },
15677         { OS2_MUTEX_INITIALIZER, },
15678       };
15679       if ( !isInit ){
15680         APIRET rc;
15681         PTIB ptib;
15682         PPIB ppib;
15683         HMTX mutex;
15684         char name[32];
15685         DosGetInfoBlocks( &ptib, &ppib );
15686         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15687                           ppib->pib_ulpid );
15688         while( !isInit ){
15689           mutex = 0;
15690           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15691           if( rc == NO_ERROR ){
15692             unsigned int i;
15693             if( !isInit ){
15694               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15695                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15696               }
15697               isInit = 1;
15698             }
15699             DosCloseMutexSem( mutex );
15700           }else if( rc == ERROR_DUPLICATE_NAME ){
15701             DosSleep( 1 );
15702           }else{
15703             return p;
15704           }
15705         }
15706       }
15707       assert( iType-2 >= 0 );
15708       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15709       p = &staticMutexes[iType-2];
15710       p->id = iType;
15711       break;
15712     }
15713   }
15714   return p;
15715 }
15716
15717
15718 /*
15719 ** This routine deallocates a previously allocated mutex.
15720 ** SQLite is careful to deallocate every mutex that it allocates.
15721 */
15722 static void os2MutexFree(sqlite3_mutex *p){
15723   if( p==0 ) return;
15724   assert( p->nRef==0 );
15725   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15726   DosCloseMutexSem( p->mutex );
15727   sqlite3_free( p );
15728 }
15729
15730 #ifdef SQLITE_DEBUG
15731 /*
15732 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15733 ** intended for use inside assert() statements.
15734 */
15735 static int os2MutexHeld(sqlite3_mutex *p){
15736   TID tid;
15737   PID pid;
15738   ULONG ulCount;
15739   PTIB ptib;
15740   if( p!=0 ) {
15741     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15742   } else {
15743     DosGetInfoBlocks(&ptib, NULL);
15744     tid = ptib->tib_ptib2->tib2_ultid;
15745   }
15746   return p==0 || (p->nRef!=0 && p->owner==tid);
15747 }
15748 static int os2MutexNotheld(sqlite3_mutex *p){
15749   TID tid;
15750   PID pid;
15751   ULONG ulCount;
15752   PTIB ptib;
15753   if( p!= 0 ) {
15754     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15755   } else {
15756     DosGetInfoBlocks(&ptib, NULL);
15757     tid = ptib->tib_ptib2->tib2_ultid;
15758   }
15759   return p==0 || p->nRef==0 || p->owner!=tid;
15760 }
15761 #endif
15762
15763 /*
15764 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15765 ** to enter a mutex.  If another thread is already within the mutex,
15766 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15767 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15768 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15769 ** be entered multiple times by the same thread.  In such cases the,
15770 ** mutex must be exited an equal number of times before another thread
15771 ** can enter.  If the same thread tries to enter any other kind of mutex
15772 ** more than once, the behavior is undefined.
15773 */
15774 static void os2MutexEnter(sqlite3_mutex *p){
15775   TID tid;
15776   PID holder1;
15777   ULONG holder2;
15778   if( p==0 ) return;
15779   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15780   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15781   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15782   p->owner = tid;
15783   p->nRef++;
15784 }
15785 static int os2MutexTry(sqlite3_mutex *p){
15786   int rc;
15787   TID tid;
15788   PID holder1;
15789   ULONG holder2;
15790   if( p==0 ) return SQLITE_OK;
15791   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15792   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15793     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15794     p->owner = tid;
15795     p->nRef++;
15796     rc = SQLITE_OK;
15797   } else {
15798     rc = SQLITE_BUSY;
15799   }
15800
15801   return rc;
15802 }
15803
15804 /*
15805 ** The sqlite3_mutex_leave() routine exits a mutex that was
15806 ** previously entered by the same thread.  The behavior
15807 ** is undefined if the mutex is not currently entered or
15808 ** is not currently allocated.  SQLite will never do either.
15809 */
15810 static void os2MutexLeave(sqlite3_mutex *p){
15811   TID tid;
15812   PID holder1;
15813   ULONG holder2;
15814   if( p==0 ) return;
15815   assert( p->nRef>0 );
15816   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15817   assert( p->owner==tid );
15818   p->nRef--;
15819   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15820   DosReleaseMutexSem(p->mutex);
15821 }
15822
15823 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15824   static const sqlite3_mutex_methods sMutex = {
15825     os2MutexInit,
15826     os2MutexEnd,
15827     os2MutexAlloc,
15828     os2MutexFree,
15829     os2MutexEnter,
15830     os2MutexTry,
15831     os2MutexLeave,
15832 #ifdef SQLITE_DEBUG
15833     os2MutexHeld,
15834     os2MutexNotheld
15835 #endif
15836   };
15837
15838   return &sMutex;
15839 }
15840 #endif /* SQLITE_MUTEX_OS2 */
15841
15842 /************** End of mutex_os2.c *******************************************/
15843 /************** Begin file mutex_unix.c **************************************/
15844 /*
15845 ** 2007 August 28
15846 **
15847 ** The author disclaims copyright to this source code.  In place of
15848 ** a legal notice, here is a blessing:
15849 **
15850 **    May you do good and not evil.
15851 **    May you find forgiveness for yourself and forgive others.
15852 **    May you share freely, never taking more than you give.
15853 **
15854 *************************************************************************
15855 ** This file contains the C functions that implement mutexes for pthreads
15856 */
15857
15858 /*
15859 ** The code in this file is only used if we are compiling threadsafe
15860 ** under unix with pthreads.
15861 **
15862 ** Note that this implementation requires a version of pthreads that
15863 ** supports recursive mutexes.
15864 */
15865 #ifdef SQLITE_MUTEX_PTHREADS
15866
15867 #include <pthread.h>
15868
15869 /*
15870 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
15871 ** are necessary under two condidtions:  (1) Debug builds and (2) using
15872 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
15873 */
15874 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
15875 # define SQLITE_MUTEX_NREF 1
15876 #else
15877 # define SQLITE_MUTEX_NREF 0
15878 #endif
15879
15880 /*
15881 ** Each recursive mutex is an instance of the following structure.
15882 */
15883 struct sqlite3_mutex {
15884   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15885 #if SQLITE_MUTEX_NREF
15886   int id;                    /* Mutex type */
15887   volatile int nRef;         /* Number of entrances */
15888   volatile pthread_t owner;  /* Thread that is within this mutex */
15889   int trace;                 /* True to trace changes */
15890 #endif
15891 };
15892 #if SQLITE_MUTEX_NREF
15893 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15894 #else
15895 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
15896 #endif
15897
15898 /*
15899 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15900 ** intended for use only inside assert() statements.  On some platforms,
15901 ** there might be race conditions that can cause these routines to
15902 ** deliver incorrect results.  In particular, if pthread_equal() is
15903 ** not an atomic operation, then these routines might delivery
15904 ** incorrect results.  On most platforms, pthread_equal() is a 
15905 ** comparison of two integers and is therefore atomic.  But we are
15906 ** told that HPUX is not such a platform.  If so, then these routines
15907 ** will not always work correctly on HPUX.
15908 **
15909 ** On those platforms where pthread_equal() is not atomic, SQLite
15910 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15911 ** make sure no assert() statements are evaluated and hence these
15912 ** routines are never called.
15913 */
15914 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15915 static int pthreadMutexHeld(sqlite3_mutex *p){
15916   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15917 }
15918 static int pthreadMutexNotheld(sqlite3_mutex *p){
15919   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15920 }
15921 #endif
15922
15923 /*
15924 ** Initialize and deinitialize the mutex subsystem.
15925 */
15926 static int pthreadMutexInit(void){ return SQLITE_OK; }
15927 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15928
15929 /*
15930 ** The sqlite3_mutex_alloc() routine allocates a new
15931 ** mutex and returns a pointer to it.  If it returns NULL
15932 ** that means that a mutex could not be allocated.  SQLite
15933 ** will unwind its stack and return an error.  The argument
15934 ** to sqlite3_mutex_alloc() is one of these integer constants:
15935 **
15936 ** <ul>
15937 ** <li>  SQLITE_MUTEX_FAST
15938 ** <li>  SQLITE_MUTEX_RECURSIVE
15939 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15940 ** <li>  SQLITE_MUTEX_STATIC_MEM
15941 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15942 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15943 ** <li>  SQLITE_MUTEX_STATIC_LRU
15944 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15945 ** </ul>
15946 **
15947 ** The first two constants cause sqlite3_mutex_alloc() to create
15948 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15949 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15950 ** The mutex implementation does not need to make a distinction
15951 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15952 ** not want to.  But SQLite will only request a recursive mutex in
15953 ** cases where it really needs one.  If a faster non-recursive mutex
15954 ** implementation is available on the host platform, the mutex subsystem
15955 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15956 **
15957 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15958 ** a pointer to a static preexisting mutex.  Six static mutexes are
15959 ** used by the current version of SQLite.  Future versions of SQLite
15960 ** may add additional static mutexes.  Static mutexes are for internal
15961 ** use by SQLite only.  Applications that use SQLite mutexes should
15962 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15963 ** SQLITE_MUTEX_RECURSIVE.
15964 **
15965 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15966 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15967 ** returns a different mutex on every call.  But for the static 
15968 ** mutex types, the same mutex is returned on every call that has
15969 ** the same type number.
15970 */
15971 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15972   static sqlite3_mutex staticMutexes[] = {
15973     SQLITE3_MUTEX_INITIALIZER,
15974     SQLITE3_MUTEX_INITIALIZER,
15975     SQLITE3_MUTEX_INITIALIZER,
15976     SQLITE3_MUTEX_INITIALIZER,
15977     SQLITE3_MUTEX_INITIALIZER,
15978     SQLITE3_MUTEX_INITIALIZER
15979   };
15980   sqlite3_mutex *p;
15981   switch( iType ){
15982     case SQLITE_MUTEX_RECURSIVE: {
15983       p = sqlite3MallocZero( sizeof(*p) );
15984       if( p ){
15985 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15986         /* If recursive mutexes are not available, we will have to
15987         ** build our own.  See below. */
15988         pthread_mutex_init(&p->mutex, 0);
15989 #else
15990         /* Use a recursive mutex if it is available */
15991         pthread_mutexattr_t recursiveAttr;
15992         pthread_mutexattr_init(&recursiveAttr);
15993         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15994         pthread_mutex_init(&p->mutex, &recursiveAttr);
15995         pthread_mutexattr_destroy(&recursiveAttr);
15996 #endif
15997 #if SQLITE_MUTEX_NREF
15998         p->id = iType;
15999 #endif
16000       }
16001       break;
16002     }
16003     case SQLITE_MUTEX_FAST: {
16004       p = sqlite3MallocZero( sizeof(*p) );
16005       if( p ){
16006 #if SQLITE_MUTEX_NREF
16007         p->id = iType;
16008 #endif
16009         pthread_mutex_init(&p->mutex, 0);
16010       }
16011       break;
16012     }
16013     default: {
16014       assert( iType-2 >= 0 );
16015       assert( iType-2 < ArraySize(staticMutexes) );
16016       p = &staticMutexes[iType-2];
16017 #if SQLITE_MUTEX_NREF
16018       p->id = iType;
16019 #endif
16020       break;
16021     }
16022   }
16023   return p;
16024 }
16025
16026
16027 /*
16028 ** This routine deallocates a previously
16029 ** allocated mutex.  SQLite is careful to deallocate every
16030 ** mutex that it allocates.
16031 */
16032 static void pthreadMutexFree(sqlite3_mutex *p){
16033   assert( p->nRef==0 );
16034   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16035   pthread_mutex_destroy(&p->mutex);
16036   sqlite3_free(p);
16037 }
16038
16039 /*
16040 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16041 ** to enter a mutex.  If another thread is already within the mutex,
16042 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16043 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16044 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16045 ** be entered multiple times by the same thread.  In such cases the,
16046 ** mutex must be exited an equal number of times before another thread
16047 ** can enter.  If the same thread tries to enter any other kind of mutex
16048 ** more than once, the behavior is undefined.
16049 */
16050 static void pthreadMutexEnter(sqlite3_mutex *p){
16051   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16052
16053 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16054   /* If recursive mutexes are not available, then we have to grow
16055   ** our own.  This implementation assumes that pthread_equal()
16056   ** is atomic - that it cannot be deceived into thinking self
16057   ** and p->owner are equal if p->owner changes between two values
16058   ** that are not equal to self while the comparison is taking place.
16059   ** This implementation also assumes a coherent cache - that 
16060   ** separate processes cannot read different values from the same
16061   ** address at the same time.  If either of these two conditions
16062   ** are not met, then the mutexes will fail and problems will result.
16063   */
16064   {
16065     pthread_t self = pthread_self();
16066     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16067       p->nRef++;
16068     }else{
16069       pthread_mutex_lock(&p->mutex);
16070       assert( p->nRef==0 );
16071       p->owner = self;
16072       p->nRef = 1;
16073     }
16074   }
16075 #else
16076   /* Use the built-in recursive mutexes if they are available.
16077   */
16078   pthread_mutex_lock(&p->mutex);
16079 #if SQLITE_MUTEX_NREF
16080   p->owner = pthread_self();
16081   p->nRef++;
16082 #endif
16083 #endif
16084
16085 #ifdef SQLITE_DEBUG
16086   if( p->trace ){
16087     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16088   }
16089 #endif
16090 }
16091 static int pthreadMutexTry(sqlite3_mutex *p){
16092   int rc;
16093   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16094
16095 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16096   /* If recursive mutexes are not available, then we have to grow
16097   ** our own.  This implementation assumes that pthread_equal()
16098   ** is atomic - that it cannot be deceived into thinking self
16099   ** and p->owner are equal if p->owner changes between two values
16100   ** that are not equal to self while the comparison is taking place.
16101   ** This implementation also assumes a coherent cache - that 
16102   ** separate processes cannot read different values from the same
16103   ** address at the same time.  If either of these two conditions
16104   ** are not met, then the mutexes will fail and problems will result.
16105   */
16106   {
16107     pthread_t self = pthread_self();
16108     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16109       p->nRef++;
16110       rc = SQLITE_OK;
16111     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16112       assert( p->nRef==0 );
16113       p->owner = self;
16114       p->nRef = 1;
16115       rc = SQLITE_OK;
16116     }else{
16117       rc = SQLITE_BUSY;
16118     }
16119   }
16120 #else
16121   /* Use the built-in recursive mutexes if they are available.
16122   */
16123   if( pthread_mutex_trylock(&p->mutex)==0 ){
16124 #if SQLITE_MUTEX_NREF
16125     p->owner = pthread_self();
16126     p->nRef++;
16127 #endif
16128     rc = SQLITE_OK;
16129   }else{
16130     rc = SQLITE_BUSY;
16131   }
16132 #endif
16133
16134 #ifdef SQLITE_DEBUG
16135   if( rc==SQLITE_OK && p->trace ){
16136     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16137   }
16138 #endif
16139   return rc;
16140 }
16141
16142 /*
16143 ** The sqlite3_mutex_leave() routine exits a mutex that was
16144 ** previously entered by the same thread.  The behavior
16145 ** is undefined if the mutex is not currently entered or
16146 ** is not currently allocated.  SQLite will never do either.
16147 */
16148 static void pthreadMutexLeave(sqlite3_mutex *p){
16149   assert( pthreadMutexHeld(p) );
16150 #if SQLITE_MUTEX_NREF
16151   p->nRef--;
16152 #endif
16153   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16154
16155 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16156   if( p->nRef==0 ){
16157     pthread_mutex_unlock(&p->mutex);
16158   }
16159 #else
16160   pthread_mutex_unlock(&p->mutex);
16161 #endif
16162
16163 #ifdef SQLITE_DEBUG
16164   if( p->trace ){
16165     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16166   }
16167 #endif
16168 }
16169
16170 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16171   static const sqlite3_mutex_methods sMutex = {
16172     pthreadMutexInit,
16173     pthreadMutexEnd,
16174     pthreadMutexAlloc,
16175     pthreadMutexFree,
16176     pthreadMutexEnter,
16177     pthreadMutexTry,
16178     pthreadMutexLeave,
16179 #ifdef SQLITE_DEBUG
16180     pthreadMutexHeld,
16181     pthreadMutexNotheld
16182 #else
16183     0,
16184     0
16185 #endif
16186   };
16187
16188   return &sMutex;
16189 }
16190
16191 #endif /* SQLITE_MUTEX_PTHREAD */
16192
16193 /************** End of mutex_unix.c ******************************************/
16194 /************** Begin file mutex_w32.c ***************************************/
16195 /*
16196 ** 2007 August 14
16197 **
16198 ** The author disclaims copyright to this source code.  In place of
16199 ** a legal notice, here is a blessing:
16200 **
16201 **    May you do good and not evil.
16202 **    May you find forgiveness for yourself and forgive others.
16203 **    May you share freely, never taking more than you give.
16204 **
16205 *************************************************************************
16206 ** This file contains the C functions that implement mutexes for win32
16207 */
16208
16209 /*
16210 ** The code in this file is only used if we are compiling multithreaded
16211 ** on a win32 system.
16212 */
16213 #ifdef SQLITE_MUTEX_W32
16214
16215 /*
16216 ** Each recursive mutex is an instance of the following structure.
16217 */
16218 struct sqlite3_mutex {
16219   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16220   int id;                    /* Mutex type */
16221 #ifdef SQLITE_DEBUG
16222   volatile int nRef;         /* Number of enterances */
16223   volatile DWORD owner;      /* Thread holding this mutex */
16224   int trace;                 /* True to trace changes */
16225 #endif
16226 };
16227 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
16228 #ifdef SQLITE_DEBUG
16229 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
16230 #else
16231 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
16232 #endif
16233
16234 /*
16235 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16236 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16237 **
16238 ** Here is an interesting observation:  Win95, Win98, and WinME lack
16239 ** the LockFileEx() API.  But we can still statically link against that
16240 ** API as long as we don't call it win running Win95/98/ME.  A call to
16241 ** this routine is used to determine if the host is Win95/98/ME or
16242 ** WinNT/2K/XP so that we will know whether or not we can safely call
16243 ** the LockFileEx() API.
16244 **
16245 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16246 ** which is only available if your application was compiled with 
16247 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16248 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
16249 ** this out as well.
16250 */
16251 #if 0
16252 #if SQLITE_OS_WINCE
16253 # define mutexIsNT()  (1)
16254 #else
16255   static int mutexIsNT(void){
16256     static int osType = 0;
16257     if( osType==0 ){
16258       OSVERSIONINFO sInfo;
16259       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16260       GetVersionEx(&sInfo);
16261       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16262     }
16263     return osType==2;
16264   }
16265 #endif /* SQLITE_OS_WINCE */
16266 #endif
16267
16268 #ifdef SQLITE_DEBUG
16269 /*
16270 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16271 ** intended for use only inside assert() statements.
16272 */
16273 static int winMutexHeld(sqlite3_mutex *p){
16274   return p->nRef!=0 && p->owner==GetCurrentThreadId();
16275 }
16276 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
16277   return p->nRef==0 || p->owner!=tid;
16278 }
16279 static int winMutexNotheld(sqlite3_mutex *p){
16280   DWORD tid = GetCurrentThreadId(); 
16281   return winMutexNotheld2(p, tid);
16282 }
16283 #endif
16284
16285
16286 /*
16287 ** Initialize and deinitialize the mutex subsystem.
16288 */
16289 static sqlite3_mutex winMutex_staticMutexes[6] = {
16290   SQLITE3_MUTEX_INITIALIZER,
16291   SQLITE3_MUTEX_INITIALIZER,
16292   SQLITE3_MUTEX_INITIALIZER,
16293   SQLITE3_MUTEX_INITIALIZER,
16294   SQLITE3_MUTEX_INITIALIZER,
16295   SQLITE3_MUTEX_INITIALIZER
16296 };
16297 static int winMutex_isInit = 0;
16298 /* As winMutexInit() and winMutexEnd() are called as part
16299 ** of the sqlite3_initialize and sqlite3_shutdown()
16300 ** processing, the "interlocked" magic is probably not
16301 ** strictly necessary.
16302 */
16303 static long winMutex_lock = 0;
16304
16305 static int winMutexInit(void){ 
16306   /* The first to increment to 1 does actual initialization */
16307   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
16308     int i;
16309     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16310       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
16311     }
16312     winMutex_isInit = 1;
16313   }else{
16314     /* Someone else is in the process of initing the static mutexes */
16315     while( !winMutex_isInit ){
16316       Sleep(1);
16317     }
16318   }
16319   return SQLITE_OK; 
16320 }
16321
16322 static int winMutexEnd(void){ 
16323   /* The first to decrement to 0 does actual shutdown 
16324   ** (which should be the last to shutdown.) */
16325   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
16326     if( winMutex_isInit==1 ){
16327       int i;
16328       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16329         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
16330       }
16331       winMutex_isInit = 0;
16332     }
16333   }
16334   return SQLITE_OK; 
16335 }
16336
16337 /*
16338 ** The sqlite3_mutex_alloc() routine allocates a new
16339 ** mutex and returns a pointer to it.  If it returns NULL
16340 ** that means that a mutex could not be allocated.  SQLite
16341 ** will unwind its stack and return an error.  The argument
16342 ** to sqlite3_mutex_alloc() is one of these integer constants:
16343 **
16344 ** <ul>
16345 ** <li>  SQLITE_MUTEX_FAST
16346 ** <li>  SQLITE_MUTEX_RECURSIVE
16347 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16348 ** <li>  SQLITE_MUTEX_STATIC_MEM
16349 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16350 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16351 ** <li>  SQLITE_MUTEX_STATIC_LRU
16352 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16353 ** </ul>
16354 **
16355 ** The first two constants cause sqlite3_mutex_alloc() to create
16356 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16357 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16358 ** The mutex implementation does not need to make a distinction
16359 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16360 ** not want to.  But SQLite will only request a recursive mutex in
16361 ** cases where it really needs one.  If a faster non-recursive mutex
16362 ** implementation is available on the host platform, the mutex subsystem
16363 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16364 **
16365 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16366 ** a pointer to a static preexisting mutex.  Six static mutexes are
16367 ** used by the current version of SQLite.  Future versions of SQLite
16368 ** may add additional static mutexes.  Static mutexes are for internal
16369 ** use by SQLite only.  Applications that use SQLite mutexes should
16370 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16371 ** SQLITE_MUTEX_RECURSIVE.
16372 **
16373 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16374 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16375 ** returns a different mutex on every call.  But for the static 
16376 ** mutex types, the same mutex is returned on every call that has
16377 ** the same type number.
16378 */
16379 static sqlite3_mutex *winMutexAlloc(int iType){
16380   sqlite3_mutex *p;
16381
16382   switch( iType ){
16383     case SQLITE_MUTEX_FAST:
16384     case SQLITE_MUTEX_RECURSIVE: {
16385       p = sqlite3MallocZero( sizeof(*p) );
16386       if( p ){  
16387 #ifdef SQLITE_DEBUG
16388         p->id = iType;
16389 #endif
16390         InitializeCriticalSection(&p->mutex);
16391       }
16392       break;
16393     }
16394     default: {
16395       assert( winMutex_isInit==1 );
16396       assert( iType-2 >= 0 );
16397       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
16398       p = &winMutex_staticMutexes[iType-2];
16399 #ifdef SQLITE_DEBUG
16400       p->id = iType;
16401 #endif
16402       break;
16403     }
16404   }
16405   return p;
16406 }
16407
16408
16409 /*
16410 ** This routine deallocates a previously
16411 ** allocated mutex.  SQLite is careful to deallocate every
16412 ** mutex that it allocates.
16413 */
16414 static void winMutexFree(sqlite3_mutex *p){
16415   assert( p );
16416   assert( p->nRef==0 );
16417   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16418   DeleteCriticalSection(&p->mutex);
16419   sqlite3_free(p);
16420 }
16421
16422 /*
16423 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16424 ** to enter a mutex.  If another thread is already within the mutex,
16425 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16426 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16427 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16428 ** be entered multiple times by the same thread.  In such cases the,
16429 ** mutex must be exited an equal number of times before another thread
16430 ** can enter.  If the same thread tries to enter any other kind of mutex
16431 ** more than once, the behavior is undefined.
16432 */
16433 static void winMutexEnter(sqlite3_mutex *p){
16434 #ifdef SQLITE_DEBUG
16435   DWORD tid = GetCurrentThreadId(); 
16436   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16437 #endif
16438   EnterCriticalSection(&p->mutex);
16439 #ifdef SQLITE_DEBUG
16440   p->owner = tid; 
16441   p->nRef++;
16442   if( p->trace ){
16443     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16444   }
16445 #endif
16446 }
16447 static int winMutexTry(sqlite3_mutex *p){
16448 #ifndef NDEBUG
16449   DWORD tid = GetCurrentThreadId(); 
16450 #endif
16451   int rc = SQLITE_BUSY;
16452   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16453   /*
16454   ** The sqlite3_mutex_try() routine is very rarely used, and when it
16455   ** is used it is merely an optimization.  So it is OK for it to always
16456   ** fail.  
16457   **
16458   ** The TryEnterCriticalSection() interface is only available on WinNT.
16459   ** And some windows compilers complain if you try to use it without
16460   ** first doing some #defines that prevent SQLite from building on Win98.
16461   ** For that reason, we will omit this optimization for now.  See
16462   ** ticket #2685.
16463   */
16464 #if 0
16465   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16466     p->owner = tid;
16467     p->nRef++;
16468     rc = SQLITE_OK;
16469   }
16470 #else
16471   UNUSED_PARAMETER(p);
16472 #endif
16473 #ifdef SQLITE_DEBUG
16474   if( rc==SQLITE_OK && p->trace ){
16475     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16476   }
16477 #endif
16478   return rc;
16479 }
16480
16481 /*
16482 ** The sqlite3_mutex_leave() routine exits a mutex that was
16483 ** previously entered by the same thread.  The behavior
16484 ** is undefined if the mutex is not currently entered or
16485 ** is not currently allocated.  SQLite will never do either.
16486 */
16487 static void winMutexLeave(sqlite3_mutex *p){
16488 #ifndef NDEBUG
16489   DWORD tid = GetCurrentThreadId();
16490   assert( p->nRef>0 );
16491   assert( p->owner==tid );
16492   p->nRef--;
16493   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16494 #endif
16495   LeaveCriticalSection(&p->mutex);
16496 #ifdef SQLITE_DEBUG
16497   if( p->trace ){
16498     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16499   }
16500 #endif
16501 }
16502
16503 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16504   static const sqlite3_mutex_methods sMutex = {
16505     winMutexInit,
16506     winMutexEnd,
16507     winMutexAlloc,
16508     winMutexFree,
16509     winMutexEnter,
16510     winMutexTry,
16511     winMutexLeave,
16512 #ifdef SQLITE_DEBUG
16513     winMutexHeld,
16514     winMutexNotheld
16515 #else
16516     0,
16517     0
16518 #endif
16519   };
16520
16521   return &sMutex;
16522 }
16523 #endif /* SQLITE_MUTEX_W32 */
16524
16525 /************** End of mutex_w32.c *******************************************/
16526 /************** Begin file malloc.c ******************************************/
16527 /*
16528 ** 2001 September 15
16529 **
16530 ** The author disclaims copyright to this source code.  In place of
16531 ** a legal notice, here is a blessing:
16532 **
16533 **    May you do good and not evil.
16534 **    May you find forgiveness for yourself and forgive others.
16535 **    May you share freely, never taking more than you give.
16536 **
16537 *************************************************************************
16538 **
16539 ** Memory allocation functions used throughout sqlite.
16540 */
16541
16542 /*
16543 ** This routine runs when the memory allocator sees that the
16544 ** total memory allocation is about to exceed the soft heap
16545 ** limit.
16546 */
16547 static void softHeapLimitEnforcer(
16548   void *NotUsed, 
16549   sqlite3_int64 NotUsed2,
16550   int allocSize
16551 ){
16552   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16553   sqlite3_release_memory(allocSize);
16554 }
16555
16556 /*
16557 ** Set the soft heap-size limit for the library. Passing a zero or 
16558 ** negative value indicates no limit.
16559 */
16560 SQLITE_API void sqlite3_soft_heap_limit(int n){
16561   sqlite3_uint64 iLimit;
16562   int overage;
16563   if( n<0 ){
16564     iLimit = 0;
16565   }else{
16566     iLimit = n;
16567   }
16568 #ifndef SQLITE_OMIT_AUTOINIT
16569   sqlite3_initialize();
16570 #endif
16571   if( iLimit>0 ){
16572     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16573   }else{
16574     sqlite3MemoryAlarm(0, 0, 0);
16575   }
16576   overage = (int)(sqlite3_memory_used() - (i64)n);
16577   if( overage>0 ){
16578     sqlite3_release_memory(overage);
16579   }
16580 }
16581
16582 /*
16583 ** Attempt to release up to n bytes of non-essential memory currently
16584 ** held by SQLite. An example of non-essential memory is memory used to
16585 ** cache database pages that are not currently in use.
16586 */
16587 SQLITE_API int sqlite3_release_memory(int n){
16588 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16589   int nRet = 0;
16590   nRet += sqlite3PcacheReleaseMemory(n-nRet);
16591   return nRet;
16592 #else
16593   UNUSED_PARAMETER(n);
16594   return SQLITE_OK;
16595 #endif
16596 }
16597
16598 /*
16599 ** State information local to the memory allocation subsystem.
16600 */
16601 static SQLITE_WSD struct Mem0Global {
16602   /* Number of free pages for scratch and page-cache memory */
16603   u32 nScratchFree;
16604   u32 nPageFree;
16605
16606   sqlite3_mutex *mutex;         /* Mutex to serialize access */
16607
16608   /*
16609   ** The alarm callback and its arguments.  The mem0.mutex lock will
16610   ** be held while the callback is running.  Recursive calls into
16611   ** the memory subsystem are allowed, but no new callbacks will be
16612   ** issued.
16613   */
16614   sqlite3_int64 alarmThreshold;
16615   void (*alarmCallback)(void*, sqlite3_int64,int);
16616   void *alarmArg;
16617
16618   /*
16619   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16620   ** sqlite3GlobalConfig.pPage to a block of memory that records
16621   ** which pages are available.
16622   */
16623   u32 *aScratchFree;
16624   u32 *aPageFree;
16625 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
16626
16627 #define mem0 GLOBAL(struct Mem0Global, mem0)
16628
16629 /*
16630 ** Initialize the memory allocation subsystem.
16631 */
16632 SQLITE_PRIVATE int sqlite3MallocInit(void){
16633   if( sqlite3GlobalConfig.m.xMalloc==0 ){
16634     sqlite3MemSetDefault();
16635   }
16636   memset(&mem0, 0, sizeof(mem0));
16637   if( sqlite3GlobalConfig.bCoreMutex ){
16638     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16639   }
16640   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16641       && sqlite3GlobalConfig.nScratch>=0 ){
16642     int i;
16643     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
16644     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16645                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16646     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16647     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16648   }else{
16649     sqlite3GlobalConfig.pScratch = 0;
16650     sqlite3GlobalConfig.szScratch = 0;
16651   }
16652   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16653       && sqlite3GlobalConfig.nPage>=1 ){
16654     int i;
16655     int overhead;
16656     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
16657     int n = sqlite3GlobalConfig.nPage;
16658     overhead = (4*n + sz - 1)/sz;
16659     sqlite3GlobalConfig.nPage -= overhead;
16660     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16661                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16662     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16663     mem0.nPageFree = sqlite3GlobalConfig.nPage;
16664   }else{
16665     sqlite3GlobalConfig.pPage = 0;
16666     sqlite3GlobalConfig.szPage = 0;
16667   }
16668   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16669 }
16670
16671 /*
16672 ** Deinitialize the memory allocation subsystem.
16673 */
16674 SQLITE_PRIVATE void sqlite3MallocEnd(void){
16675   if( sqlite3GlobalConfig.m.xShutdown ){
16676     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16677   }
16678   memset(&mem0, 0, sizeof(mem0));
16679 }
16680
16681 /*
16682 ** Return the amount of memory currently checked out.
16683 */
16684 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16685   int n, mx;
16686   sqlite3_int64 res;
16687   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16688   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16689   return res;
16690 }
16691
16692 /*
16693 ** Return the maximum amount of memory that has ever been
16694 ** checked out since either the beginning of this process
16695 ** or since the most recent reset.
16696 */
16697 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16698   int n, mx;
16699   sqlite3_int64 res;
16700   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16701   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16702   return res;
16703 }
16704
16705 /*
16706 ** Change the alarm callback
16707 */
16708 SQLITE_PRIVATE int sqlite3MemoryAlarm(
16709   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16710   void *pArg,
16711   sqlite3_int64 iThreshold
16712 ){
16713   sqlite3_mutex_enter(mem0.mutex);
16714   mem0.alarmCallback = xCallback;
16715   mem0.alarmArg = pArg;
16716   mem0.alarmThreshold = iThreshold;
16717   sqlite3_mutex_leave(mem0.mutex);
16718   return SQLITE_OK;
16719 }
16720
16721 #ifndef SQLITE_OMIT_DEPRECATED
16722 /*
16723 ** Deprecated external interface.  Internal/core SQLite code
16724 ** should call sqlite3MemoryAlarm.
16725 */
16726 SQLITE_API int sqlite3_memory_alarm(
16727   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16728   void *pArg,
16729   sqlite3_int64 iThreshold
16730 ){
16731   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16732 }
16733 #endif
16734
16735 /*
16736 ** Trigger the alarm 
16737 */
16738 static void sqlite3MallocAlarm(int nByte){
16739   void (*xCallback)(void*,sqlite3_int64,int);
16740   sqlite3_int64 nowUsed;
16741   void *pArg;
16742   if( mem0.alarmCallback==0 ) return;
16743   xCallback = mem0.alarmCallback;
16744   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16745   pArg = mem0.alarmArg;
16746   mem0.alarmCallback = 0;
16747   sqlite3_mutex_leave(mem0.mutex);
16748   xCallback(pArg, nowUsed, nByte);
16749   sqlite3_mutex_enter(mem0.mutex);
16750   mem0.alarmCallback = xCallback;
16751   mem0.alarmArg = pArg;
16752 }
16753
16754 /*
16755 ** Do a memory allocation with statistics and alarms.  Assume the
16756 ** lock is already held.
16757 */
16758 static int mallocWithAlarm(int n, void **pp){
16759   int nFull;
16760   void *p;
16761   assert( sqlite3_mutex_held(mem0.mutex) );
16762   nFull = sqlite3GlobalConfig.m.xRoundup(n);
16763   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16764   if( mem0.alarmCallback!=0 ){
16765     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16766     if( nUsed+nFull >= mem0.alarmThreshold ){
16767       sqlite3MallocAlarm(nFull);
16768     }
16769   }
16770   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16771   if( p==0 && mem0.alarmCallback ){
16772     sqlite3MallocAlarm(nFull);
16773     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16774   }
16775   if( p ){
16776     nFull = sqlite3MallocSize(p);
16777     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16778   }
16779   *pp = p;
16780   return nFull;
16781 }
16782
16783 /*
16784 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16785 ** assumes the memory subsystem has already been initialized.
16786 */
16787 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16788   void *p;
16789   if( n<=0 || n>=0x7fffff00 ){
16790     /* A memory allocation of a number of bytes which is near the maximum
16791     ** signed integer value might cause an integer overflow inside of the
16792     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
16793     ** 255 bytes of overhead.  SQLite itself will never use anything near
16794     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
16795     p = 0;
16796   }else if( sqlite3GlobalConfig.bMemstat ){
16797     sqlite3_mutex_enter(mem0.mutex);
16798     mallocWithAlarm(n, &p);
16799     sqlite3_mutex_leave(mem0.mutex);
16800   }else{
16801     p = sqlite3GlobalConfig.m.xMalloc(n);
16802   }
16803   return p;
16804 }
16805
16806 /*
16807 ** This version of the memory allocation is for use by the application.
16808 ** First make sure the memory subsystem is initialized, then do the
16809 ** allocation.
16810 */
16811 SQLITE_API void *sqlite3_malloc(int n){
16812 #ifndef SQLITE_OMIT_AUTOINIT
16813   if( sqlite3_initialize() ) return 0;
16814 #endif
16815   return sqlite3Malloc(n);
16816 }
16817
16818 /*
16819 ** Each thread may only have a single outstanding allocation from
16820 ** xScratchMalloc().  We verify this constraint in the single-threaded
16821 ** case by setting scratchAllocOut to 1 when an allocation
16822 ** is outstanding clearing it when the allocation is freed.
16823 */
16824 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16825 static int scratchAllocOut = 0;
16826 #endif
16827
16828
16829 /*
16830 ** Allocate memory that is to be used and released right away.
16831 ** This routine is similar to alloca() in that it is not intended
16832 ** for situations where the memory might be held long-term.  This
16833 ** routine is intended to get memory to old large transient data
16834 ** structures that would not normally fit on the stack of an
16835 ** embedded processor.
16836 */
16837 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16838   void *p;
16839   assert( n>0 );
16840
16841 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16842   /* Verify that no more than two scratch allocation per thread
16843   ** is outstanding at one time.  (This is only checked in the
16844   ** single-threaded case since checking in the multi-threaded case
16845   ** would be much more complicated.) */
16846   assert( scratchAllocOut<=1 );
16847 #endif
16848
16849   if( sqlite3GlobalConfig.szScratch<n ){
16850     goto scratch_overflow;
16851   }else{  
16852     sqlite3_mutex_enter(mem0.mutex);
16853     if( mem0.nScratchFree==0 ){
16854       sqlite3_mutex_leave(mem0.mutex);
16855       goto scratch_overflow;
16856     }else{
16857       int i;
16858       i = mem0.aScratchFree[--mem0.nScratchFree];
16859       i *= sqlite3GlobalConfig.szScratch;
16860       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16861       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16862       sqlite3_mutex_leave(mem0.mutex);
16863       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16864       assert(  (((u8*)p - (u8*)0) & 7)==0 );
16865     }
16866   }
16867 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16868   scratchAllocOut = p!=0;
16869 #endif
16870
16871   return p;
16872
16873 scratch_overflow:
16874   if( sqlite3GlobalConfig.bMemstat ){
16875     sqlite3_mutex_enter(mem0.mutex);
16876     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16877     n = mallocWithAlarm(n, &p);
16878     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16879     sqlite3_mutex_leave(mem0.mutex);
16880   }else{
16881     p = sqlite3GlobalConfig.m.xMalloc(n);
16882   }
16883   sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
16884 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16885   scratchAllocOut = p!=0;
16886 #endif
16887   return p;    
16888 }
16889 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16890   if( p ){
16891     if( sqlite3GlobalConfig.pScratch==0
16892            || p<sqlite3GlobalConfig.pScratch
16893            || p>=(void*)mem0.aScratchFree ){
16894       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
16895       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16896       if( sqlite3GlobalConfig.bMemstat ){
16897         int iSize = sqlite3MallocSize(p);
16898         sqlite3_mutex_enter(mem0.mutex);
16899         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16900         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16901         sqlite3GlobalConfig.m.xFree(p);
16902         sqlite3_mutex_leave(mem0.mutex);
16903       }else{
16904         sqlite3GlobalConfig.m.xFree(p);
16905       }
16906     }else{
16907       int i;
16908       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16909       i /= sqlite3GlobalConfig.szScratch;
16910       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16911       sqlite3_mutex_enter(mem0.mutex);
16912       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16913       mem0.aScratchFree[mem0.nScratchFree++] = i;
16914       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16915       sqlite3_mutex_leave(mem0.mutex);
16916
16917 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16918     /* Verify that no more than two scratch allocation per thread
16919     ** is outstanding at one time.  (This is only checked in the
16920     ** single-threaded case since checking in the multi-threaded case
16921     ** would be much more complicated.) */
16922     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
16923     scratchAllocOut = 0;
16924 #endif
16925
16926     }
16927   }
16928 }
16929
16930 /*
16931 ** TRUE if p is a lookaside memory allocation from db
16932 */
16933 #ifndef SQLITE_OMIT_LOOKASIDE
16934 static int isLookaside(sqlite3 *db, void *p){
16935   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16936 }
16937 #else
16938 #define isLookaside(A,B) 0
16939 #endif
16940
16941 /*
16942 ** Return the size of a memory allocation previously obtained from
16943 ** sqlite3Malloc() or sqlite3_malloc().
16944 */
16945 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16946   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16947   return sqlite3GlobalConfig.m.xSize(p);
16948 }
16949 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16950   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16951   if( isLookaside(db, p) ){
16952     return db->lookaside.sz;
16953   }else{
16954     assert( sqlite3MemdebugHasType(p,
16955              db ? (MEMTYPE_DB|MEMTYPE_HEAP) : MEMTYPE_HEAP) );
16956     return sqlite3GlobalConfig.m.xSize(p);
16957   }
16958 }
16959
16960 /*
16961 ** Free memory previously obtained from sqlite3Malloc().
16962 */
16963 SQLITE_API void sqlite3_free(void *p){
16964   if( p==0 ) return;
16965   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16966   if( sqlite3GlobalConfig.bMemstat ){
16967     sqlite3_mutex_enter(mem0.mutex);
16968     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16969     sqlite3GlobalConfig.m.xFree(p);
16970     sqlite3_mutex_leave(mem0.mutex);
16971   }else{
16972     sqlite3GlobalConfig.m.xFree(p);
16973   }
16974 }
16975
16976 /*
16977 ** Free memory that might be associated with a particular database
16978 ** connection.
16979 */
16980 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16981   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16982   if( isLookaside(db, p) ){
16983     LookasideSlot *pBuf = (LookasideSlot*)p;
16984     pBuf->pNext = db->lookaside.pFree;
16985     db->lookaside.pFree = pBuf;
16986     db->lookaside.nOut--;
16987   }else{
16988     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
16989     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16990     sqlite3_free(p);
16991   }
16992 }
16993
16994 /*
16995 ** Change the size of an existing memory allocation
16996 */
16997 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16998   int nOld, nNew;
16999   void *pNew;
17000   if( pOld==0 ){
17001     return sqlite3Malloc(nBytes);
17002   }
17003   if( nBytes<=0 ){
17004     sqlite3_free(pOld);
17005     return 0;
17006   }
17007   if( nBytes>=0x7fffff00 ){
17008     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17009     return 0;
17010   }
17011   nOld = sqlite3MallocSize(pOld);
17012   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17013   if( nOld==nNew ){
17014     pNew = pOld;
17015   }else if( sqlite3GlobalConfig.bMemstat ){
17016     sqlite3_mutex_enter(mem0.mutex);
17017     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17018     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
17019           mem0.alarmThreshold ){
17020       sqlite3MallocAlarm(nNew-nOld);
17021     }
17022     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17023     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17024     if( pNew==0 && mem0.alarmCallback ){
17025       sqlite3MallocAlarm(nBytes);
17026       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17027     }
17028     if( pNew ){
17029       nNew = sqlite3MallocSize(pNew);
17030       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17031     }
17032     sqlite3_mutex_leave(mem0.mutex);
17033   }else{
17034     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17035   }
17036   return pNew;
17037 }
17038
17039 /*
17040 ** The public interface to sqlite3Realloc.  Make sure that the memory
17041 ** subsystem is initialized prior to invoking sqliteRealloc.
17042 */
17043 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17044 #ifndef SQLITE_OMIT_AUTOINIT
17045   if( sqlite3_initialize() ) return 0;
17046 #endif
17047   return sqlite3Realloc(pOld, n);
17048 }
17049
17050
17051 /*
17052 ** Allocate and zero memory.
17053 */ 
17054 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17055   void *p = sqlite3Malloc(n);
17056   if( p ){
17057     memset(p, 0, n);
17058   }
17059   return p;
17060 }
17061
17062 /*
17063 ** Allocate and zero memory.  If the allocation fails, make
17064 ** the mallocFailed flag in the connection pointer.
17065 */
17066 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17067   void *p = sqlite3DbMallocRaw(db, n);
17068   if( p ){
17069     memset(p, 0, n);
17070   }
17071   return p;
17072 }
17073
17074 /*
17075 ** Allocate and zero memory.  If the allocation fails, make
17076 ** the mallocFailed flag in the connection pointer.
17077 **
17078 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17079 ** failure on the same database connection) then always return 0.
17080 ** Hence for a particular database connection, once malloc starts
17081 ** failing, it fails consistently until mallocFailed is reset.
17082 ** This is an important assumption.  There are many places in the
17083 ** code that do things like this:
17084 **
17085 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17086 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17087 **         if( b ) a[10] = 9;
17088 **
17089 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17090 ** that all prior mallocs (ex: "a") worked too.
17091 */
17092 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17093   void *p;
17094   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17095 #ifndef SQLITE_OMIT_LOOKASIDE
17096   if( db ){
17097     LookasideSlot *pBuf;
17098     if( db->mallocFailed ){
17099       return 0;
17100     }
17101     if( db->lookaside.bEnabled && n<=db->lookaside.sz
17102          && (pBuf = db->lookaside.pFree)!=0 ){
17103       db->lookaside.pFree = pBuf->pNext;
17104       db->lookaside.nOut++;
17105       if( db->lookaside.nOut>db->lookaside.mxOut ){
17106         db->lookaside.mxOut = db->lookaside.nOut;
17107       }
17108       return (void*)pBuf;
17109     }
17110   }
17111 #else
17112   if( db && db->mallocFailed ){
17113     return 0;
17114   }
17115 #endif
17116   p = sqlite3Malloc(n);
17117   if( !p && db ){
17118     db->mallocFailed = 1;
17119   }
17120   sqlite3MemdebugSetType(p,
17121             (db && db->lookaside.bEnabled) ? MEMTYPE_DB : MEMTYPE_HEAP);
17122   return p;
17123 }
17124
17125 /*
17126 ** Resize the block of memory pointed to by p to n bytes. If the
17127 ** resize fails, set the mallocFailed flag in the connection object.
17128 */
17129 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
17130   void *pNew = 0;
17131   assert( db!=0 );
17132   assert( sqlite3_mutex_held(db->mutex) );
17133   if( db->mallocFailed==0 ){
17134     if( p==0 ){
17135       return sqlite3DbMallocRaw(db, n);
17136     }
17137     if( isLookaside(db, p) ){
17138       if( n<=db->lookaside.sz ){
17139         return p;
17140       }
17141       pNew = sqlite3DbMallocRaw(db, n);
17142       if( pNew ){
17143         memcpy(pNew, p, db->lookaside.sz);
17144         sqlite3DbFree(db, p);
17145       }
17146     }else{
17147       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
17148       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17149       pNew = sqlite3_realloc(p, n);
17150       if( !pNew ){
17151         db->mallocFailed = 1;
17152       }
17153       sqlite3MemdebugSetType(pNew,
17154             db->lookaside.bEnabled ? MEMTYPE_DB : MEMTYPE_HEAP);
17155     }
17156   }
17157   return pNew;
17158 }
17159
17160 /*
17161 ** Attempt to reallocate p.  If the reallocation fails, then free p
17162 ** and set the mallocFailed flag in the database connection.
17163 */
17164 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
17165   void *pNew;
17166   pNew = sqlite3DbRealloc(db, p, n);
17167   if( !pNew ){
17168     sqlite3DbFree(db, p);
17169   }
17170   return pNew;
17171 }
17172
17173 /*
17174 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
17175 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
17176 ** is because when memory debugging is turned on, these two functions are 
17177 ** called via macros that record the current file and line number in the
17178 ** ThreadData structure.
17179 */
17180 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
17181   char *zNew;
17182   size_t n;
17183   if( z==0 ){
17184     return 0;
17185   }
17186   n = sqlite3Strlen30(z) + 1;
17187   assert( (n&0x7fffffff)==n );
17188   zNew = sqlite3DbMallocRaw(db, (int)n);
17189   if( zNew ){
17190     memcpy(zNew, z, n);
17191   }
17192   return zNew;
17193 }
17194 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17195   char *zNew;
17196   if( z==0 ){
17197     return 0;
17198   }
17199   assert( (n&0x7fffffff)==n );
17200   zNew = sqlite3DbMallocRaw(db, n+1);
17201   if( zNew ){
17202     memcpy(zNew, z, n);
17203     zNew[n] = 0;
17204   }
17205   return zNew;
17206 }
17207
17208 /*
17209 ** Create a string from the zFromat argument and the va_list that follows.
17210 ** Store the string in memory obtained from sqliteMalloc() and make *pz
17211 ** point to that string.
17212 */
17213 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17214   va_list ap;
17215   char *z;
17216
17217   va_start(ap, zFormat);
17218   z = sqlite3VMPrintf(db, zFormat, ap);
17219   va_end(ap);
17220   sqlite3DbFree(db, *pz);
17221   *pz = z;
17222 }
17223
17224
17225 /*
17226 ** This function must be called before exiting any API function (i.e. 
17227 ** returning control to the user) that has called sqlite3_malloc or
17228 ** sqlite3_realloc.
17229 **
17230 ** The returned value is normally a copy of the second argument to this
17231 ** function. However, if a malloc() failure has occurred since the previous
17232 ** invocation SQLITE_NOMEM is returned instead. 
17233 **
17234 ** If the first argument, db, is not NULL and a malloc() error has occurred,
17235 ** then the connection error-code (the value returned by sqlite3_errcode())
17236 ** is set to SQLITE_NOMEM.
17237 */
17238 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17239   /* If the db handle is not NULL, then we must hold the connection handle
17240   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
17241   ** is unsafe, as is the call to sqlite3Error().
17242   */
17243   assert( !db || sqlite3_mutex_held(db->mutex) );
17244   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17245     sqlite3Error(db, SQLITE_NOMEM, 0);
17246     db->mallocFailed = 0;
17247     rc = SQLITE_NOMEM;
17248   }
17249   return rc & (db ? db->errMask : 0xff);
17250 }
17251
17252 /************** End of malloc.c **********************************************/
17253 /************** Begin file printf.c ******************************************/
17254 /*
17255 ** The "printf" code that follows dates from the 1980's.  It is in
17256 ** the public domain.  The original comments are included here for
17257 ** completeness.  They are very out-of-date but might be useful as
17258 ** an historical reference.  Most of the "enhancements" have been backed
17259 ** out so that the functionality is now the same as standard printf().
17260 **
17261 **************************************************************************
17262 **
17263 ** The following modules is an enhanced replacement for the "printf" subroutines
17264 ** found in the standard C library.  The following enhancements are
17265 ** supported:
17266 **
17267 **      +  Additional functions.  The standard set of "printf" functions
17268 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17269 **         vsprintf.  This module adds the following:
17270 **
17271 **           *  snprintf -- Works like sprintf, but has an extra argument
17272 **                          which is the size of the buffer written to.
17273 **
17274 **           *  mprintf --  Similar to sprintf.  Writes output to memory
17275 **                          obtained from malloc.
17276 **
17277 **           *  xprintf --  Calls a function to dispose of output.
17278 **
17279 **           *  nprintf --  No output, but returns the number of characters
17280 **                          that would have been output by printf.
17281 **
17282 **           *  A v- version (ex: vsnprintf) of every function is also
17283 **              supplied.
17284 **
17285 **      +  A few extensions to the formatting notation are supported:
17286 **
17287 **           *  The "=" flag (similar to "-") causes the output to be
17288 **              be centered in the appropriately sized field.
17289 **
17290 **           *  The %b field outputs an integer in binary notation.
17291 **
17292 **           *  The %c field now accepts a precision.  The character output
17293 **              is repeated by the number of times the precision specifies.
17294 **
17295 **           *  The %' field works like %c, but takes as its character the
17296 **              next character of the format string, instead of the next
17297 **              argument.  For example,  printf("%.78'-")  prints 78 minus
17298 **              signs, the same as  printf("%.78c",'-').
17299 **
17300 **      +  When compiled using GCC on a SPARC, this version of printf is
17301 **         faster than the library printf for SUN OS 4.1.
17302 **
17303 **      +  All functions are fully reentrant.
17304 **
17305 */
17306
17307 /*
17308 ** Conversion types fall into various categories as defined by the
17309 ** following enumeration.
17310 */
17311 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17312 #define etFLOAT       2 /* Floating point.  %f */
17313 #define etEXP         3 /* Exponentional notation. %e and %E */
17314 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17315 #define etSIZE        5 /* Return number of characters processed so far. %n */
17316 #define etSTRING      6 /* Strings. %s */
17317 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17318 #define etPERCENT     8 /* Percent symbol. %% */
17319 #define etCHARX       9 /* Characters. %c */
17320 /* The rest are extensions, not normally found in printf() */
17321 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17322 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17323                           NULL pointers replaced by SQL NULL.  %Q */
17324 #define etTOKEN      12 /* a pointer to a Token structure */
17325 #define etSRCLIST    13 /* a pointer to a SrcList */
17326 #define etPOINTER    14 /* The %p conversion */
17327 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17328 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17329
17330 #define etINVALID     0 /* Any unrecognized conversion type */
17331
17332
17333 /*
17334 ** An "etByte" is an 8-bit unsigned value.
17335 */
17336 typedef unsigned char etByte;
17337
17338 /*
17339 ** Each builtin conversion character (ex: the 'd' in "%d") is described
17340 ** by an instance of the following structure
17341 */
17342 typedef struct et_info {   /* Information about each format field */
17343   char fmttype;            /* The format field code letter */
17344   etByte base;             /* The base for radix conversion */
17345   etByte flags;            /* One or more of FLAG_ constants below */
17346   etByte type;             /* Conversion paradigm */
17347   etByte charset;          /* Offset into aDigits[] of the digits string */
17348   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17349 } et_info;
17350
17351 /*
17352 ** Allowed values for et_info.flags
17353 */
17354 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
17355 #define FLAG_INTERN  2     /* True if for internal use only */
17356 #define FLAG_STRING  4     /* Allow infinity precision */
17357
17358
17359 /*
17360 ** The following table is searched linearly, so it is good to put the
17361 ** most frequently used conversion types first.
17362 */
17363 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17364 static const char aPrefix[] = "-x0\000X0";
17365 static const et_info fmtinfo[] = {
17366   {  'd', 10, 1, etRADIX,      0,  0 },
17367   {  's',  0, 4, etSTRING,     0,  0 },
17368   {  'g',  0, 1, etGENERIC,    30, 0 },
17369   {  'z',  0, 4, etDYNSTRING,  0,  0 },
17370   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17371   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17372   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17373   {  'c',  0, 0, etCHARX,      0,  0 },
17374   {  'o',  8, 0, etRADIX,      0,  2 },
17375   {  'u', 10, 0, etRADIX,      0,  0 },
17376   {  'x', 16, 0, etRADIX,      16, 1 },
17377   {  'X', 16, 0, etRADIX,      0,  4 },
17378 #ifndef SQLITE_OMIT_FLOATING_POINT
17379   {  'f',  0, 1, etFLOAT,      0,  0 },
17380   {  'e',  0, 1, etEXP,        30, 0 },
17381   {  'E',  0, 1, etEXP,        14, 0 },
17382   {  'G',  0, 1, etGENERIC,    14, 0 },
17383 #endif
17384   {  'i', 10, 1, etRADIX,      0,  0 },
17385   {  'n',  0, 0, etSIZE,       0,  0 },
17386   {  '%',  0, 0, etPERCENT,    0,  0 },
17387   {  'p', 16, 0, etPOINTER,    0,  1 },
17388
17389 /* All the rest have the FLAG_INTERN bit set and are thus for internal
17390 ** use only */
17391   {  'T',  0, 2, etTOKEN,      0,  0 },
17392   {  'S',  0, 2, etSRCLIST,    0,  0 },
17393   {  'r', 10, 3, etORDINAL,    0,  0 },
17394 };
17395
17396 /*
17397 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17398 ** conversions will work.
17399 */
17400 #ifndef SQLITE_OMIT_FLOATING_POINT
17401 /*
17402 ** "*val" is a double such that 0.1 <= *val < 10.0
17403 ** Return the ascii code for the leading digit of *val, then
17404 ** multiply "*val" by 10.0 to renormalize.
17405 **
17406 ** Example:
17407 **     input:     *val = 3.14159
17408 **     output:    *val = 1.4159    function return = '3'
17409 **
17410 ** The counter *cnt is incremented each time.  After counter exceeds
17411 ** 16 (the number of significant digits in a 64-bit float) '0' is
17412 ** always returned.
17413 */
17414 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17415   int digit;
17416   LONGDOUBLE_TYPE d;
17417   if( (*cnt)++ >= 16 ) return '0';
17418   digit = (int)*val;
17419   d = digit;
17420   digit += '0';
17421   *val = (*val - d)*10.0;
17422   return (char)digit;
17423 }
17424 #endif /* SQLITE_OMIT_FLOATING_POINT */
17425
17426 /*
17427 ** Append N space characters to the given string buffer.
17428 */
17429 static void appendSpace(StrAccum *pAccum, int N){
17430   static const char zSpaces[] = "                             ";
17431   while( N>=(int)sizeof(zSpaces)-1 ){
17432     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
17433     N -= sizeof(zSpaces)-1;
17434   }
17435   if( N>0 ){
17436     sqlite3StrAccumAppend(pAccum, zSpaces, N);
17437   }
17438 }
17439
17440 /*
17441 ** On machines with a small stack size, you can redefine the
17442 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
17443 */
17444 #ifndef SQLITE_PRINT_BUF_SIZE
17445 # if defined(SQLITE_SMALL_STACK)
17446 #   define SQLITE_PRINT_BUF_SIZE 50
17447 # else
17448 #   define SQLITE_PRINT_BUF_SIZE 350
17449 # endif
17450 #endif
17451 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17452
17453 /*
17454 ** The root program.  All variations call this core.
17455 **
17456 ** INPUTS:
17457 **   func   This is a pointer to a function taking three arguments
17458 **            1. A pointer to anything.  Same as the "arg" parameter.
17459 **            2. A pointer to the list of characters to be output
17460 **               (Note, this list is NOT null terminated.)
17461 **            3. An integer number of characters to be output.
17462 **               (Note: This number might be zero.)
17463 **
17464 **   arg    This is the pointer to anything which will be passed as the
17465 **          first argument to "func".  Use it for whatever you like.
17466 **
17467 **   fmt    This is the format string, as in the usual print.
17468 **
17469 **   ap     This is a pointer to a list of arguments.  Same as in
17470 **          vfprint.
17471 **
17472 ** OUTPUTS:
17473 **          The return value is the total number of characters sent to
17474 **          the function "func".  Returns -1 on a error.
17475 **
17476 ** Note that the order in which automatic variables are declared below
17477 ** seems to make a big difference in determining how fast this beast
17478 ** will run.
17479 */
17480 SQLITE_PRIVATE void sqlite3VXPrintf(
17481   StrAccum *pAccum,                  /* Accumulate results here */
17482   int useExtended,                   /* Allow extended %-conversions */
17483   const char *fmt,                   /* Format string */
17484   va_list ap                         /* arguments */
17485 ){
17486   int c;                     /* Next character in the format string */
17487   char *bufpt;               /* Pointer to the conversion buffer */
17488   int precision;             /* Precision of the current field */
17489   int length;                /* Length of the field */
17490   int idx;                   /* A general purpose loop counter */
17491   int width;                 /* Width of the current field */
17492   etByte flag_leftjustify;   /* True if "-" flag is present */
17493   etByte flag_plussign;      /* True if "+" flag is present */
17494   etByte flag_blanksign;     /* True if " " flag is present */
17495   etByte flag_alternateform; /* True if "#" flag is present */
17496   etByte flag_altform2;      /* True if "!" flag is present */
17497   etByte flag_zeropad;       /* True if field width constant starts with zero */
17498   etByte flag_long;          /* True if "l" flag is present */
17499   etByte flag_longlong;      /* True if the "ll" flag is present */
17500   etByte done;               /* Loop termination flag */
17501   sqlite_uint64 longvalue;   /* Value for integer types */
17502   LONGDOUBLE_TYPE realvalue; /* Value for real types */
17503   const et_info *infop;      /* Pointer to the appropriate info structure */
17504   char buf[etBUFSIZE];       /* Conversion buffer */
17505   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17506   etByte xtype = 0;          /* Conversion paradigm */
17507   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17508 #ifndef SQLITE_OMIT_FLOATING_POINT
17509   int  exp, e2;              /* exponent of real numbers */
17510   double rounder;            /* Used for rounding floating point values */
17511   etByte flag_dp;            /* True if decimal point should be shown */
17512   etByte flag_rtz;           /* True if trailing zeros should be removed */
17513   etByte flag_exp;           /* True to force display of the exponent */
17514   int nsd;                   /* Number of significant digits returned */
17515 #endif
17516
17517   length = 0;
17518   bufpt = 0;
17519   for(; (c=(*fmt))!=0; ++fmt){
17520     if( c!='%' ){
17521       int amt;
17522       bufpt = (char *)fmt;
17523       amt = 1;
17524       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17525       sqlite3StrAccumAppend(pAccum, bufpt, amt);
17526       if( c==0 ) break;
17527     }
17528     if( (c=(*++fmt))==0 ){
17529       sqlite3StrAccumAppend(pAccum, "%", 1);
17530       break;
17531     }
17532     /* Find out what flags are present */
17533     flag_leftjustify = flag_plussign = flag_blanksign = 
17534      flag_alternateform = flag_altform2 = flag_zeropad = 0;
17535     done = 0;
17536     do{
17537       switch( c ){
17538         case '-':   flag_leftjustify = 1;     break;
17539         case '+':   flag_plussign = 1;        break;
17540         case ' ':   flag_blanksign = 1;       break;
17541         case '#':   flag_alternateform = 1;   break;
17542         case '!':   flag_altform2 = 1;        break;
17543         case '0':   flag_zeropad = 1;         break;
17544         default:    done = 1;                 break;
17545       }
17546     }while( !done && (c=(*++fmt))!=0 );
17547     /* Get the field width */
17548     width = 0;
17549     if( c=='*' ){
17550       width = va_arg(ap,int);
17551       if( width<0 ){
17552         flag_leftjustify = 1;
17553         width = -width;
17554       }
17555       c = *++fmt;
17556     }else{
17557       while( c>='0' && c<='9' ){
17558         width = width*10 + c - '0';
17559         c = *++fmt;
17560       }
17561     }
17562     if( width > etBUFSIZE-10 ){
17563       width = etBUFSIZE-10;
17564     }
17565     /* Get the precision */
17566     if( c=='.' ){
17567       precision = 0;
17568       c = *++fmt;
17569       if( c=='*' ){
17570         precision = va_arg(ap,int);
17571         if( precision<0 ) precision = -precision;
17572         c = *++fmt;
17573       }else{
17574         while( c>='0' && c<='9' ){
17575           precision = precision*10 + c - '0';
17576           c = *++fmt;
17577         }
17578       }
17579     }else{
17580       precision = -1;
17581     }
17582     /* Get the conversion type modifier */
17583     if( c=='l' ){
17584       flag_long = 1;
17585       c = *++fmt;
17586       if( c=='l' ){
17587         flag_longlong = 1;
17588         c = *++fmt;
17589       }else{
17590         flag_longlong = 0;
17591       }
17592     }else{
17593       flag_long = flag_longlong = 0;
17594     }
17595     /* Fetch the info entry for the field */
17596     infop = &fmtinfo[0];
17597     xtype = etINVALID;
17598     for(idx=0; idx<ArraySize(fmtinfo); idx++){
17599       if( c==fmtinfo[idx].fmttype ){
17600         infop = &fmtinfo[idx];
17601         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17602           xtype = infop->type;
17603         }else{
17604           return;
17605         }
17606         break;
17607       }
17608     }
17609     zExtra = 0;
17610
17611
17612     /* Limit the precision to prevent overflowing buf[] during conversion */
17613     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17614       precision = etBUFSIZE-40;
17615     }
17616
17617     /*
17618     ** At this point, variables are initialized as follows:
17619     **
17620     **   flag_alternateform          TRUE if a '#' is present.
17621     **   flag_altform2               TRUE if a '!' is present.
17622     **   flag_plussign               TRUE if a '+' is present.
17623     **   flag_leftjustify            TRUE if a '-' is present or if the
17624     **                               field width was negative.
17625     **   flag_zeropad                TRUE if the width began with 0.
17626     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17627     **                               the conversion character.
17628     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17629     **                               the conversion character.
17630     **   flag_blanksign              TRUE if a ' ' is present.
17631     **   width                       The specified field width.  This is
17632     **                               always non-negative.  Zero is the default.
17633     **   precision                   The specified precision.  The default
17634     **                               is -1.
17635     **   xtype                       The class of the conversion.
17636     **   infop                       Pointer to the appropriate info struct.
17637     */
17638     switch( xtype ){
17639       case etPOINTER:
17640         flag_longlong = sizeof(char*)==sizeof(i64);
17641         flag_long = sizeof(char*)==sizeof(long int);
17642         /* Fall through into the next case */
17643       case etORDINAL:
17644       case etRADIX:
17645         if( infop->flags & FLAG_SIGNED ){
17646           i64 v;
17647           if( flag_longlong ){
17648             v = va_arg(ap,i64);
17649           }else if( flag_long ){
17650             v = va_arg(ap,long int);
17651           }else{
17652             v = va_arg(ap,int);
17653           }
17654           if( v<0 ){
17655             longvalue = -v;
17656             prefix = '-';
17657           }else{
17658             longvalue = v;
17659             if( flag_plussign )        prefix = '+';
17660             else if( flag_blanksign )  prefix = ' ';
17661             else                       prefix = 0;
17662           }
17663         }else{
17664           if( flag_longlong ){
17665             longvalue = va_arg(ap,u64);
17666           }else if( flag_long ){
17667             longvalue = va_arg(ap,unsigned long int);
17668           }else{
17669             longvalue = va_arg(ap,unsigned int);
17670           }
17671           prefix = 0;
17672         }
17673         if( longvalue==0 ) flag_alternateform = 0;
17674         if( flag_zeropad && precision<width-(prefix!=0) ){
17675           precision = width-(prefix!=0);
17676         }
17677         bufpt = &buf[etBUFSIZE-1];
17678         if( xtype==etORDINAL ){
17679           static const char zOrd[] = "thstndrd";
17680           int x = (int)(longvalue % 10);
17681           if( x>=4 || (longvalue/10)%10==1 ){
17682             x = 0;
17683           }
17684           buf[etBUFSIZE-3] = zOrd[x*2];
17685           buf[etBUFSIZE-2] = zOrd[x*2+1];
17686           bufpt -= 2;
17687         }
17688         {
17689           register const char *cset;      /* Use registers for speed */
17690           register int base;
17691           cset = &aDigits[infop->charset];
17692           base = infop->base;
17693           do{                                           /* Convert to ascii */
17694             *(--bufpt) = cset[longvalue%base];
17695             longvalue = longvalue/base;
17696           }while( longvalue>0 );
17697         }
17698         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17699         for(idx=precision-length; idx>0; idx--){
17700           *(--bufpt) = '0';                             /* Zero pad */
17701         }
17702         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17703         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17704           const char *pre;
17705           char x;
17706           pre = &aPrefix[infop->prefix];
17707           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17708         }
17709         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17710         break;
17711       case etFLOAT:
17712       case etEXP:
17713       case etGENERIC:
17714         realvalue = va_arg(ap,double);
17715 #ifdef SQLITE_OMIT_FLOATING_POINT
17716         length = 0;
17717 #else
17718         if( precision<0 ) precision = 6;         /* Set default precision */
17719         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17720         if( realvalue<0.0 ){
17721           realvalue = -realvalue;
17722           prefix = '-';
17723         }else{
17724           if( flag_plussign )          prefix = '+';
17725           else if( flag_blanksign )    prefix = ' ';
17726           else                         prefix = 0;
17727         }
17728         if( xtype==etGENERIC && precision>0 ) precision--;
17729 #if 0
17730         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17731         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17732 #else
17733         /* It makes more sense to use 0.5 */
17734         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17735 #endif
17736         if( xtype==etFLOAT ) realvalue += rounder;
17737         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17738         exp = 0;
17739         if( sqlite3IsNaN((double)realvalue) ){
17740           bufpt = "NaN";
17741           length = 3;
17742           break;
17743         }
17744         if( realvalue>0.0 ){
17745           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17746           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17747           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17748           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17749           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17750           if( exp>350 ){
17751             if( prefix=='-' ){
17752               bufpt = "-Inf";
17753             }else if( prefix=='+' ){
17754               bufpt = "+Inf";
17755             }else{
17756               bufpt = "Inf";
17757             }
17758             length = sqlite3Strlen30(bufpt);
17759             break;
17760           }
17761         }
17762         bufpt = buf;
17763         /*
17764         ** If the field type is etGENERIC, then convert to either etEXP
17765         ** or etFLOAT, as appropriate.
17766         */
17767         flag_exp = xtype==etEXP;
17768         if( xtype!=etFLOAT ){
17769           realvalue += rounder;
17770           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17771         }
17772         if( xtype==etGENERIC ){
17773           flag_rtz = !flag_alternateform;
17774           if( exp<-4 || exp>precision ){
17775             xtype = etEXP;
17776           }else{
17777             precision = precision - exp;
17778             xtype = etFLOAT;
17779           }
17780         }else{
17781           flag_rtz = 0;
17782         }
17783         if( xtype==etEXP ){
17784           e2 = 0;
17785         }else{
17786           e2 = exp;
17787         }
17788         nsd = 0;
17789         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17790         /* The sign in front of the number */
17791         if( prefix ){
17792           *(bufpt++) = prefix;
17793         }
17794         /* Digits prior to the decimal point */
17795         if( e2<0 ){
17796           *(bufpt++) = '0';
17797         }else{
17798           for(; e2>=0; e2--){
17799             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17800           }
17801         }
17802         /* The decimal point */
17803         if( flag_dp ){
17804           *(bufpt++) = '.';
17805         }
17806         /* "0" digits after the decimal point but before the first
17807         ** significant digit of the number */
17808         for(e2++; e2<0; precision--, e2++){
17809           assert( precision>0 );
17810           *(bufpt++) = '0';
17811         }
17812         /* Significant digits after the decimal point */
17813         while( (precision--)>0 ){
17814           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17815         }
17816         /* Remove trailing zeros and the "." if no digits follow the "." */
17817         if( flag_rtz && flag_dp ){
17818           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17819           assert( bufpt>buf );
17820           if( bufpt[-1]=='.' ){
17821             if( flag_altform2 ){
17822               *(bufpt++) = '0';
17823             }else{
17824               *(--bufpt) = 0;
17825             }
17826           }
17827         }
17828         /* Add the "eNNN" suffix */
17829         if( flag_exp || xtype==etEXP ){
17830           *(bufpt++) = aDigits[infop->charset];
17831           if( exp<0 ){
17832             *(bufpt++) = '-'; exp = -exp;
17833           }else{
17834             *(bufpt++) = '+';
17835           }
17836           if( exp>=100 ){
17837             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17838             exp %= 100;
17839           }
17840           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17841           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17842         }
17843         *bufpt = 0;
17844
17845         /* The converted number is in buf[] and zero terminated. Output it.
17846         ** Note that the number is in the usual order, not reversed as with
17847         ** integer conversions. */
17848         length = (int)(bufpt-buf);
17849         bufpt = buf;
17850
17851         /* Special case:  Add leading zeros if the flag_zeropad flag is
17852         ** set and we are not left justified */
17853         if( flag_zeropad && !flag_leftjustify && length < width){
17854           int i;
17855           int nPad = width - length;
17856           for(i=width; i>=nPad; i--){
17857             bufpt[i] = bufpt[i-nPad];
17858           }
17859           i = prefix!=0;
17860           while( nPad-- ) bufpt[i++] = '0';
17861           length = width;
17862         }
17863 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
17864         break;
17865       case etSIZE:
17866         *(va_arg(ap,int*)) = pAccum->nChar;
17867         length = width = 0;
17868         break;
17869       case etPERCENT:
17870         buf[0] = '%';
17871         bufpt = buf;
17872         length = 1;
17873         break;
17874       case etCHARX:
17875         c = va_arg(ap,int);
17876         buf[0] = (char)c;
17877         if( precision>=0 ){
17878           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17879           length = precision;
17880         }else{
17881           length =1;
17882         }
17883         bufpt = buf;
17884         break;
17885       case etSTRING:
17886       case etDYNSTRING:
17887         bufpt = va_arg(ap,char*);
17888         if( bufpt==0 ){
17889           bufpt = "";
17890         }else if( xtype==etDYNSTRING ){
17891           zExtra = bufpt;
17892         }
17893         if( precision>=0 ){
17894           for(length=0; length<precision && bufpt[length]; length++){}
17895         }else{
17896           length = sqlite3Strlen30(bufpt);
17897         }
17898         break;
17899       case etSQLESCAPE:
17900       case etSQLESCAPE2:
17901       case etSQLESCAPE3: {
17902         int i, j, k, n, isnull;
17903         int needQuote;
17904         char ch;
17905         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17906         char *escarg = va_arg(ap,char*);
17907         isnull = escarg==0;
17908         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17909         k = precision;
17910         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
17911           if( ch==q )  n++;
17912         }
17913         needQuote = !isnull && xtype==etSQLESCAPE2;
17914         n += i + 1 + needQuote*2;
17915         if( n>etBUFSIZE ){
17916           bufpt = zExtra = sqlite3Malloc( n );
17917           if( bufpt==0 ){
17918             pAccum->mallocFailed = 1;
17919             return;
17920           }
17921         }else{
17922           bufpt = buf;
17923         }
17924         j = 0;
17925         if( needQuote ) bufpt[j++] = q;
17926         k = i;
17927         for(i=0; i<k; i++){
17928           bufpt[j++] = ch = escarg[i];
17929           if( ch==q ) bufpt[j++] = ch;
17930         }
17931         if( needQuote ) bufpt[j++] = q;
17932         bufpt[j] = 0;
17933         length = j;
17934         /* The precision in %q and %Q means how many input characters to
17935         ** consume, not the length of the output...
17936         ** if( precision>=0 && precision<length ) length = precision; */
17937         break;
17938       }
17939       case etTOKEN: {
17940         Token *pToken = va_arg(ap, Token*);
17941         if( pToken ){
17942           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17943         }
17944         length = width = 0;
17945         break;
17946       }
17947       case etSRCLIST: {
17948         SrcList *pSrc = va_arg(ap, SrcList*);
17949         int k = va_arg(ap, int);
17950         struct SrcList_item *pItem = &pSrc->a[k];
17951         assert( k>=0 && k<pSrc->nSrc );
17952         if( pItem->zDatabase ){
17953           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17954           sqlite3StrAccumAppend(pAccum, ".", 1);
17955         }
17956         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17957         length = width = 0;
17958         break;
17959       }
17960       default: {
17961         assert( xtype==etINVALID );
17962         return;
17963       }
17964     }/* End switch over the format type */
17965     /*
17966     ** The text of the conversion is pointed to by "bufpt" and is
17967     ** "length" characters long.  The field width is "width".  Do
17968     ** the output.
17969     */
17970     if( !flag_leftjustify ){
17971       register int nspace;
17972       nspace = width-length;
17973       if( nspace>0 ){
17974         appendSpace(pAccum, nspace);
17975       }
17976     }
17977     if( length>0 ){
17978       sqlite3StrAccumAppend(pAccum, bufpt, length);
17979     }
17980     if( flag_leftjustify ){
17981       register int nspace;
17982       nspace = width-length;
17983       if( nspace>0 ){
17984         appendSpace(pAccum, nspace);
17985       }
17986     }
17987     if( zExtra ){
17988       sqlite3_free(zExtra);
17989     }
17990   }/* End for loop over the format string */
17991 } /* End of function */
17992
17993 /*
17994 ** Append N bytes of text from z to the StrAccum object.
17995 */
17996 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17997   assert( z!=0 || N==0 );
17998   if( p->tooBig | p->mallocFailed ){
17999     testcase(p->tooBig);
18000     testcase(p->mallocFailed);
18001     return;
18002   }
18003   if( N<0 ){
18004     N = sqlite3Strlen30(z);
18005   }
18006   if( N==0 || NEVER(z==0) ){
18007     return;
18008   }
18009   if( p->nChar+N >= p->nAlloc ){
18010     char *zNew;
18011     if( !p->useMalloc ){
18012       p->tooBig = 1;
18013       N = p->nAlloc - p->nChar - 1;
18014       if( N<=0 ){
18015         return;
18016       }
18017     }else{
18018       i64 szNew = p->nChar;
18019       szNew += N + 1;
18020       if( szNew > p->mxAlloc ){
18021         sqlite3StrAccumReset(p);
18022         p->tooBig = 1;
18023         return;
18024       }else{
18025         p->nAlloc = (int)szNew;
18026       }
18027       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18028       if( zNew ){
18029         memcpy(zNew, p->zText, p->nChar);
18030         sqlite3StrAccumReset(p);
18031         p->zText = zNew;
18032       }else{
18033         p->mallocFailed = 1;
18034         sqlite3StrAccumReset(p);
18035         return;
18036       }
18037     }
18038   }
18039   memcpy(&p->zText[p->nChar], z, N);
18040   p->nChar += N;
18041 }
18042
18043 /*
18044 ** Finish off a string by making sure it is zero-terminated.
18045 ** Return a pointer to the resulting string.  Return a NULL
18046 ** pointer if any kind of error was encountered.
18047 */
18048 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18049   if( p->zText ){
18050     p->zText[p->nChar] = 0;
18051     if( p->useMalloc && p->zText==p->zBase ){
18052       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18053       if( p->zText ){
18054         memcpy(p->zText, p->zBase, p->nChar+1);
18055       }else{
18056         p->mallocFailed = 1;
18057       }
18058     }
18059   }
18060   return p->zText;
18061 }
18062
18063 /*
18064 ** Reset an StrAccum string.  Reclaim all malloced memory.
18065 */
18066 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18067   if( p->zText!=p->zBase ){
18068     sqlite3DbFree(p->db, p->zText);
18069   }
18070   p->zText = 0;
18071 }
18072
18073 /*
18074 ** Initialize a string accumulator
18075 */
18076 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18077   p->zText = p->zBase = zBase;
18078   p->db = 0;
18079   p->nChar = 0;
18080   p->nAlloc = n;
18081   p->mxAlloc = mx;
18082   p->useMalloc = 1;
18083   p->tooBig = 0;
18084   p->mallocFailed = 0;
18085 }
18086
18087 /*
18088 ** Print into memory obtained from sqliteMalloc().  Use the internal
18089 ** %-conversion extensions.
18090 */
18091 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18092   char *z;
18093   char zBase[SQLITE_PRINT_BUF_SIZE];
18094   StrAccum acc;
18095   assert( db!=0 );
18096   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18097                       db->aLimit[SQLITE_LIMIT_LENGTH]);
18098   acc.db = db;
18099   sqlite3VXPrintf(&acc, 1, zFormat, ap);
18100   z = sqlite3StrAccumFinish(&acc);
18101   if( acc.mallocFailed ){
18102     db->mallocFailed = 1;
18103   }
18104   return z;
18105 }
18106
18107 /*
18108 ** Print into memory obtained from sqliteMalloc().  Use the internal
18109 ** %-conversion extensions.
18110 */
18111 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
18112   va_list ap;
18113   char *z;
18114   va_start(ap, zFormat);
18115   z = sqlite3VMPrintf(db, zFormat, ap);
18116   va_end(ap);
18117   return z;
18118 }
18119
18120 /*
18121 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
18122 ** the string and before returnning.  This routine is intended to be used
18123 ** to modify an existing string.  For example:
18124 **
18125 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
18126 **
18127 */
18128 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
18129   va_list ap;
18130   char *z;
18131   va_start(ap, zFormat);
18132   z = sqlite3VMPrintf(db, zFormat, ap);
18133   va_end(ap);
18134   sqlite3DbFree(db, zStr);
18135   return z;
18136 }
18137
18138 /*
18139 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
18140 ** %-conversion extensions.
18141 */
18142 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
18143   char *z;
18144   char zBase[SQLITE_PRINT_BUF_SIZE];
18145   StrAccum acc;
18146 #ifndef SQLITE_OMIT_AUTOINIT
18147   if( sqlite3_initialize() ) return 0;
18148 #endif
18149   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
18150   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18151   z = sqlite3StrAccumFinish(&acc);
18152   return z;
18153 }
18154
18155 /*
18156 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
18157 ** %-conversion extensions.
18158 */
18159 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
18160   va_list ap;
18161   char *z;
18162 #ifndef SQLITE_OMIT_AUTOINIT
18163   if( sqlite3_initialize() ) return 0;
18164 #endif
18165   va_start(ap, zFormat);
18166   z = sqlite3_vmprintf(zFormat, ap);
18167   va_end(ap);
18168   return z;
18169 }
18170
18171 /*
18172 ** sqlite3_snprintf() works like snprintf() except that it ignores the
18173 ** current locale settings.  This is important for SQLite because we
18174 ** are not able to use a "," as the decimal point in place of "." as
18175 ** specified by some locales.
18176 */
18177 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
18178   char *z;
18179   va_list ap;
18180   StrAccum acc;
18181
18182   if( n<=0 ){
18183     return zBuf;
18184   }
18185   sqlite3StrAccumInit(&acc, zBuf, n, 0);
18186   acc.useMalloc = 0;
18187   va_start(ap,zFormat);
18188   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18189   va_end(ap);
18190   z = sqlite3StrAccumFinish(&acc);
18191   return z;
18192 }
18193
18194 /*
18195 ** This is the routine that actually formats the sqlite3_log() message.
18196 ** We house it in a separate routine from sqlite3_log() to avoid using
18197 ** stack space on small-stack systems when logging is disabled.
18198 **
18199 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
18200 ** allocate memory because it might be called while the memory allocator
18201 ** mutex is held.
18202 */
18203 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
18204   StrAccum acc;                          /* String accumulator */
18205   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
18206
18207   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
18208   acc.useMalloc = 0;
18209   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18210   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
18211                            sqlite3StrAccumFinish(&acc));
18212 }
18213
18214 /*
18215 ** Format and write a message to the log if logging is enabled.
18216 */
18217 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
18218   va_list ap;                             /* Vararg list */
18219   if( sqlite3GlobalConfig.xLog ){
18220     va_start(ap, zFormat);
18221     renderLogMsg(iErrCode, zFormat, ap);
18222     va_end(ap);
18223   }
18224 }
18225
18226 #if defined(SQLITE_DEBUG)
18227 /*
18228 ** A version of printf() that understands %lld.  Used for debugging.
18229 ** The printf() built into some versions of windows does not understand %lld
18230 ** and segfaults if you give it a long long int.
18231 */
18232 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
18233   va_list ap;
18234   StrAccum acc;
18235   char zBuf[500];
18236   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
18237   acc.useMalloc = 0;
18238   va_start(ap,zFormat);
18239   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18240   va_end(ap);
18241   sqlite3StrAccumFinish(&acc);
18242   fprintf(stdout,"%s", zBuf);
18243   fflush(stdout);
18244 }
18245 #endif
18246
18247 #ifndef SQLITE_OMIT_TRACE
18248 /*
18249 ** variable-argument wrapper around sqlite3VXPrintf().
18250 */
18251 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
18252   va_list ap;
18253   va_start(ap,zFormat);
18254   sqlite3VXPrintf(p, 1, zFormat, ap);
18255   va_end(ap);
18256 }
18257 #endif
18258
18259 /************** End of printf.c **********************************************/
18260 /************** Begin file random.c ******************************************/
18261 /*
18262 ** 2001 September 15
18263 **
18264 ** The author disclaims copyright to this source code.  In place of
18265 ** a legal notice, here is a blessing:
18266 **
18267 **    May you do good and not evil.
18268 **    May you find forgiveness for yourself and forgive others.
18269 **    May you share freely, never taking more than you give.
18270 **
18271 *************************************************************************
18272 ** This file contains code to implement a pseudo-random number
18273 ** generator (PRNG) for SQLite.
18274 **
18275 ** Random numbers are used by some of the database backends in order
18276 ** to generate random integer keys for tables or random filenames.
18277 */
18278
18279
18280 /* All threads share a single random number generator.
18281 ** This structure is the current state of the generator.
18282 */
18283 static SQLITE_WSD struct sqlite3PrngType {
18284   unsigned char isInit;          /* True if initialized */
18285   unsigned char i, j;            /* State variables */
18286   unsigned char s[256];          /* State variables */
18287 } sqlite3Prng;
18288
18289 /*
18290 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18291 ** must be held while executing this routine.
18292 **
18293 ** Why not just use a library random generator like lrand48() for this?
18294 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
18295 ** good source of random numbers.  The lrand48() library function may
18296 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
18297 ** subtle problems on some systems that could cause problems.  It is hard
18298 ** to know.  To minimize the risk of problems due to bad lrand48()
18299 ** implementations, SQLite uses this random number generator based
18300 ** on RC4, which we know works very well.
18301 **
18302 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
18303 ** randomness any more.  But we will leave this code in all the same.
18304 */
18305 static u8 randomByte(void){
18306   unsigned char t;
18307
18308
18309   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18310   ** state vector.  If writable static data is unsupported on the target,
18311   ** we have to locate the state vector at run-time.  In the more common
18312   ** case where writable static data is supported, wsdPrng can refer directly
18313   ** to the "sqlite3Prng" state vector declared above.
18314   */
18315 #ifdef SQLITE_OMIT_WSD
18316   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18317 # define wsdPrng p[0]
18318 #else
18319 # define wsdPrng sqlite3Prng
18320 #endif
18321
18322
18323   /* Initialize the state of the random number generator once,
18324   ** the first time this routine is called.  The seed value does
18325   ** not need to contain a lot of randomness since we are not
18326   ** trying to do secure encryption or anything like that...
18327   **
18328   ** Nothing in this file or anywhere else in SQLite does any kind of
18329   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18330   ** number generator) not as an encryption device.
18331   */
18332   if( !wsdPrng.isInit ){
18333     int i;
18334     char k[256];
18335     wsdPrng.j = 0;
18336     wsdPrng.i = 0;
18337     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18338     for(i=0; i<256; i++){
18339       wsdPrng.s[i] = (u8)i;
18340     }
18341     for(i=0; i<256; i++){
18342       wsdPrng.j += wsdPrng.s[i] + k[i];
18343       t = wsdPrng.s[wsdPrng.j];
18344       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18345       wsdPrng.s[i] = t;
18346     }
18347     wsdPrng.isInit = 1;
18348   }
18349
18350   /* Generate and return single random byte
18351   */
18352   wsdPrng.i++;
18353   t = wsdPrng.s[wsdPrng.i];
18354   wsdPrng.j += t;
18355   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18356   wsdPrng.s[wsdPrng.j] = t;
18357   t += wsdPrng.s[wsdPrng.i];
18358   return wsdPrng.s[t];
18359 }
18360
18361 /*
18362 ** Return N random bytes.
18363 */
18364 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18365   unsigned char *zBuf = pBuf;
18366 #if SQLITE_THREADSAFE
18367   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18368 #endif
18369   sqlite3_mutex_enter(mutex);
18370   while( N-- ){
18371     *(zBuf++) = randomByte();
18372   }
18373   sqlite3_mutex_leave(mutex);
18374 }
18375
18376 #ifndef SQLITE_OMIT_BUILTIN_TEST
18377 /*
18378 ** For testing purposes, we sometimes want to preserve the state of
18379 ** PRNG and restore the PRNG to its saved state at a later time, or
18380 ** to reset the PRNG to its initial state.  These routines accomplish
18381 ** those tasks.
18382 **
18383 ** The sqlite3_test_control() interface calls these routines to
18384 ** control the PRNG.
18385 */
18386 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18387 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18388   memcpy(
18389     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18390     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18391     sizeof(sqlite3Prng)
18392   );
18393 }
18394 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18395   memcpy(
18396     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18397     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18398     sizeof(sqlite3Prng)
18399   );
18400 }
18401 SQLITE_PRIVATE void sqlite3PrngResetState(void){
18402   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18403 }
18404 #endif /* SQLITE_OMIT_BUILTIN_TEST */
18405
18406 /************** End of random.c **********************************************/
18407 /************** Begin file utf.c *********************************************/
18408 /*
18409 ** 2004 April 13
18410 **
18411 ** The author disclaims copyright to this source code.  In place of
18412 ** a legal notice, here is a blessing:
18413 **
18414 **    May you do good and not evil.
18415 **    May you find forgiveness for yourself and forgive others.
18416 **    May you share freely, never taking more than you give.
18417 **
18418 *************************************************************************
18419 ** This file contains routines used to translate between UTF-8, 
18420 ** UTF-16, UTF-16BE, and UTF-16LE.
18421 **
18422 ** Notes on UTF-8:
18423 **
18424 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
18425 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
18426 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
18427 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
18428 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
18429 **
18430 **
18431 ** Notes on UTF-16:  (with wwww+1==uuuuu)
18432 **
18433 **      Word-0               Word-1          Value
18434 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
18435 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
18436 **
18437 **
18438 ** BOM or Byte Order Mark:
18439 **     0xff 0xfe   little-endian utf-16 follows
18440 **     0xfe 0xff   big-endian utf-16 follows
18441 **
18442 */
18443 /************** Include vdbeInt.h in the middle of utf.c *********************/
18444 /************** Begin file vdbeInt.h *****************************************/
18445 /*
18446 ** 2003 September 6
18447 **
18448 ** The author disclaims copyright to this source code.  In place of
18449 ** a legal notice, here is a blessing:
18450 **
18451 **    May you do good and not evil.
18452 **    May you find forgiveness for yourself and forgive others.
18453 **    May you share freely, never taking more than you give.
18454 **
18455 *************************************************************************
18456 ** This is the header file for information that is private to the
18457 ** VDBE.  This information used to all be at the top of the single
18458 ** source code file "vdbe.c".  When that file became too big (over
18459 ** 6000 lines long) it was split up into several smaller files and
18460 ** this header information was factored out.
18461 */
18462 #ifndef _VDBEINT_H_
18463 #define _VDBEINT_H_
18464
18465 /*
18466 ** SQL is translated into a sequence of instructions to be
18467 ** executed by a virtual machine.  Each instruction is an instance
18468 ** of the following structure.
18469 */
18470 typedef struct VdbeOp Op;
18471
18472 /*
18473 ** Boolean values
18474 */
18475 typedef unsigned char Bool;
18476
18477 /*
18478 ** A cursor is a pointer into a single BTree within a database file.
18479 ** The cursor can seek to a BTree entry with a particular key, or
18480 ** loop over all entries of the Btree.  You can also insert new BTree
18481 ** entries or retrieve the key or data from the entry that the cursor
18482 ** is currently pointing to.
18483 ** 
18484 ** Every cursor that the virtual machine has open is represented by an
18485 ** instance of the following structure.
18486 **
18487 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
18488 ** really a single row that represents the NEW or OLD pseudo-table of
18489 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
18490 ** the rowid is in VdbeCursor.iKey.
18491 */
18492 struct VdbeCursor {
18493   BtCursor *pCursor;    /* The cursor structure of the backend */
18494   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
18495   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
18496   Bool zeroed;          /* True if zeroed out and ready for reuse */
18497   Bool rowidIsValid;    /* True if lastRowid is valid */
18498   Bool atFirst;         /* True if pointing to first entry */
18499   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
18500   Bool nullRow;         /* True if pointing to a row with no data */
18501   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
18502   Bool isTable;         /* True if a table requiring integer keys */
18503   Bool isIndex;         /* True if an index containing keys only - no data */
18504   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
18505   Btree *pBt;           /* Separate file holding temporary table */
18506   int pseudoTableReg;   /* Register holding pseudotable content. */
18507   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
18508   int nField;           /* Number of fields in the header */
18509   i64 seqCount;         /* Sequence counter */
18510   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
18511   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
18512
18513   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
18514   ** OP_IsUnique opcode on this cursor. */
18515   int seekResult;
18516
18517   /* Cached information about the header for the data record that the
18518   ** cursor is currently pointing to.  Only valid if cacheStatus matches
18519   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18520   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
18521   ** the cache is out of date.
18522   **
18523   ** aRow might point to (ephemeral) data for the current row, or it might
18524   ** be NULL.
18525   */
18526   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
18527   int payloadSize;      /* Total number of bytes in the record */
18528   u32 *aType;           /* Type values for all entries in the record */
18529   u32 *aOffset;         /* Cached offsets to the start of each columns data */
18530   u8 *aRow;             /* Data for the current row, if all on one page */
18531 };
18532 typedef struct VdbeCursor VdbeCursor;
18533
18534 /*
18535 ** When a sub-program is executed (OP_Program), a structure of this type
18536 ** is allocated to store the current value of the program counter, as
18537 ** well as the current memory cell array and various other frame specific
18538 ** values stored in the Vdbe struct. When the sub-program is finished, 
18539 ** these values are copied back to the Vdbe from the VdbeFrame structure,
18540 ** restoring the state of the VM to as it was before the sub-program
18541 ** began executing.
18542 **
18543 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
18544 ** is the parent of the current frame, or zero if the current frame
18545 ** is the main Vdbe program.
18546 */
18547 typedef struct VdbeFrame VdbeFrame;
18548 struct VdbeFrame {
18549   Vdbe *v;                /* VM this frame belongs to */
18550   int pc;                 /* Program Counter */
18551   Op *aOp;                /* Program instructions */
18552   int nOp;                /* Size of aOp array */
18553   Mem *aMem;              /* Array of memory cells */
18554   int nMem;               /* Number of entries in aMem */
18555   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
18556   u16 nCursor;            /* Number of entries in apCsr */
18557   void *token;            /* Copy of SubProgram.token */
18558   int nChildMem;          /* Number of memory cells for child frame */
18559   int nChildCsr;          /* Number of cursors for child frame */
18560   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18561   int nChange;            /* Statement changes (Vdbe.nChanges)     */
18562   VdbeFrame *pParent;     /* Parent of this frame */
18563 };
18564
18565 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18566
18567 /*
18568 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
18569 */
18570 #define CACHE_STALE 0
18571
18572 /*
18573 ** Internally, the vdbe manipulates nearly all SQL values as Mem
18574 ** structures. Each Mem struct may cache multiple representations (string,
18575 ** integer etc.) of the same value.  A value (and therefore Mem structure)
18576 ** has the following properties:
18577 **
18578 ** Each value has a manifest type. The manifest type of the value stored
18579 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
18580 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
18581 ** SQLITE_BLOB.
18582 */
18583 struct Mem {
18584   union {
18585     i64 i;              /* Integer value. */
18586     int nZero;          /* Used when bit MEM_Zero is set in flags */
18587     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18588     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18589     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18590   } u;
18591   double r;           /* Real value */
18592   sqlite3 *db;        /* The associated database connection */
18593   char *z;            /* String or BLOB value */
18594   int n;              /* Number of characters in string value, excluding '\0' */
18595   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18596   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18597   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18598   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18599   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18600 };
18601
18602 /* One or more of the following flags are set to indicate the validOK
18603 ** representations of the value stored in the Mem struct.
18604 **
18605 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18606 ** No other flags may be set in this case.
18607 **
18608 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18609 ** Usually this is encoded in the same unicode encoding as the main
18610 ** database (see below for exceptions). If the MEM_Term flag is also
18611 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
18612 ** flags may coexist with the MEM_Str flag.
18613 **
18614 ** Multiple of these values can appear in Mem.flags.  But only one
18615 ** at a time can appear in Mem.type.
18616 */
18617 #define MEM_Null      0x0001   /* Value is NULL */
18618 #define MEM_Str       0x0002   /* Value is a string */
18619 #define MEM_Int       0x0004   /* Value is an integer */
18620 #define MEM_Real      0x0008   /* Value is a real number */
18621 #define MEM_Blob      0x0010   /* Value is a BLOB */
18622 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
18623 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18624 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
18625
18626 /* Whenever Mem contains a valid string or blob representation, one of
18627 ** the following flags must be set to determine the memory management
18628 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18629 ** string is \000 or \u0000 terminated
18630 */
18631 #define MEM_Term      0x0200   /* String rep is nul terminated */
18632 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
18633 #define MEM_Static    0x0800   /* Mem.z points to a static string */
18634 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18635 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18636 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18637
18638 #ifdef SQLITE_OMIT_INCRBLOB
18639   #undef MEM_Zero
18640   #define MEM_Zero 0x0000
18641 #endif
18642
18643
18644 /*
18645 ** Clear any existing type flags from a Mem and replace them with f
18646 */
18647 #define MemSetTypeFlag(p, f) \
18648    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18649
18650
18651 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18652 ** additional information about auxiliary information bound to arguments
18653 ** of the function.  This is used to implement the sqlite3_get_auxdata()
18654 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18655 ** that can be associated with a constant argument to a function.  This
18656 ** allows functions such as "regexp" to compile their constant regular
18657 ** expression argument once and reused the compiled code for multiple
18658 ** invocations.
18659 */
18660 struct VdbeFunc {
18661   FuncDef *pFunc;               /* The definition of the function */
18662   int nAux;                     /* Number of entries allocated for apAux[] */
18663   struct AuxData {
18664     void *pAux;                   /* Aux data for the i-th argument */
18665     void (*xDelete)(void *);      /* Destructor for the aux data */
18666   } apAux[1];                   /* One slot for each function argument */
18667 };
18668
18669 /*
18670 ** The "context" argument for a installable function.  A pointer to an
18671 ** instance of this structure is the first argument to the routines used
18672 ** implement the SQL functions.
18673 **
18674 ** There is a typedef for this structure in sqlite.h.  So all routines,
18675 ** even the public interface to SQLite, can use a pointer to this structure.
18676 ** But this file is the only place where the internal details of this
18677 ** structure are known.
18678 **
18679 ** This structure is defined inside of vdbeInt.h because it uses substructures
18680 ** (Mem) which are only defined there.
18681 */
18682 struct sqlite3_context {
18683   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18684   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18685   Mem s;                /* The return value is stored here */
18686   Mem *pMem;            /* Memory cell used to store aggregate context */
18687   int isError;          /* Error code returned by the function. */
18688   CollSeq *pColl;       /* Collating sequence */
18689 };
18690
18691 /*
18692 ** A Set structure is used for quick testing to see if a value
18693 ** is part of a small set.  Sets are used to implement code like
18694 ** this:
18695 **            x.y IN ('hi','hoo','hum')
18696 */
18697 typedef struct Set Set;
18698 struct Set {
18699   Hash hash;             /* A set is just a hash table */
18700   HashElem *prev;        /* Previously accessed hash elemen */
18701 };
18702
18703 /*
18704 ** An instance of the virtual machine.  This structure contains the complete
18705 ** state of the virtual machine.
18706 **
18707 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18708 ** is really a pointer to an instance of this structure.
18709 **
18710 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18711 ** any virtual table method invocations made by the vdbe program. It is
18712 ** set to 2 for xDestroy method calls and 1 for all other methods. This
18713 ** variable is used for two purposes: to allow xDestroy methods to execute
18714 ** "DROP TABLE" statements and to prevent some nasty side effects of
18715 ** malloc failure when SQLite is invoked recursively by a virtual table 
18716 ** method function.
18717 */
18718 struct Vdbe {
18719   sqlite3 *db;            /* The database connection that owns this statement */
18720   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18721   int nOp;                /* Number of instructions in the program */
18722   int nOpAlloc;           /* Number of slots allocated for aOp[] */
18723   Op *aOp;                /* Space to hold the virtual machine's program */
18724   int nLabel;             /* Number of labels used */
18725   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
18726   int *aLabel;            /* Space to hold the labels */
18727   Mem **apArg;            /* Arguments to currently executing user function */
18728   Mem *aColName;          /* Column names to return */
18729   Mem *pResultSet;        /* Pointer to an array of results */
18730   u16 nResColumn;         /* Number of columns in one row of the result set */
18731   u16 nCursor;            /* Number of slots in apCsr[] */
18732   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18733   u8 errorAction;         /* Recovery action to do in case of an error */
18734   u8 okVar;               /* True if azVar[] has been initialized */
18735   ynVar nVar;             /* Number of entries in aVar[] */
18736   Mem *aVar;              /* Values for the OP_Variable opcode. */
18737   char **azVar;           /* Name of variables */
18738   u32 magic;              /* Magic number for sanity checking */
18739   int nMem;               /* Number of memory locations currently allocated */
18740   Mem *aMem;              /* The memory locations */
18741   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18742   int pc;                 /* The program counter */
18743   int rc;                 /* Value to return */
18744   char *zErrMsg;          /* Error message written here */
18745   u8 explain;             /* True if EXPLAIN present on SQL command */
18746   u8 changeCntOn;         /* True to update the change-counter */
18747   u8 expired;             /* True if the VM needs to be recompiled */
18748   u8 runOnlyOnce;         /* Automatically expire on reset */
18749   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18750   u8 inVtabMethod;        /* See comments above */
18751   u8 usesStmtJournal;     /* True if uses a statement journal */
18752   u8 readOnly;            /* True for read-only statements */
18753   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
18754   int nChange;            /* Number of db changes made since last reset */
18755   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18756   i64 startTime;          /* Time when query started - used for profiling */
18757   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18758   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
18759   char *zSql;             /* Text of the SQL statement that generated this */
18760   void *pFree;            /* Free this when deleting the vdbe */
18761   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18762   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18763   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18764 #ifdef SQLITE_DEBUG
18765   FILE *trace;            /* Write an execution trace here, if not NULL */
18766 #endif
18767   VdbeFrame *pFrame;      /* Parent frame */
18768   int nFrame;             /* Number of frames in pFrame list */
18769   u32 expmask;            /* Binding to these vars invalidates VM */
18770 };
18771
18772 /*
18773 ** The following are allowed values for Vdbe.magic
18774 */
18775 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18776 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18777 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18778 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18779
18780 /*
18781 ** Function prototypes
18782 */
18783 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18784 void sqliteVdbePopStack(Vdbe*,int);
18785 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18786 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18787 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18788 #endif
18789 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18790 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18791 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18792 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18793 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18794
18795 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18796 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18797 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
18798 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18799 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18800 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18801 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18802 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18803 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18804 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18805 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18806 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18807 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18808 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18809 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18810 #ifdef SQLITE_OMIT_FLOATING_POINT
18811 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18812 #else
18813 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18814 #endif
18815 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18816 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18817 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18818 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18819 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18820 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18821 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18822 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18823 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18824 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18825 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18826 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18827 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18828 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18829 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18830 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18831 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18832 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18833 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18834 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18835 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
18836
18837 #ifndef SQLITE_OMIT_FOREIGN_KEY
18838 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18839 #else
18840 # define sqlite3VdbeCheckFk(p,i) 0
18841 #endif
18842
18843 #ifndef SQLITE_OMIT_SHARED_CACHE
18844 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
18845 #else
18846 # define sqlite3VdbeMutexArrayEnter(p)
18847 #endif
18848
18849 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18850 #ifdef SQLITE_DEBUG
18851 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18852 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18853 #endif
18854 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18855
18856 #ifndef SQLITE_OMIT_INCRBLOB
18857 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18858 #else
18859   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18860 #endif
18861
18862 #endif /* !defined(_VDBEINT_H_) */
18863
18864 /************** End of vdbeInt.h *********************************************/
18865 /************** Continuing where we left off in utf.c ************************/
18866
18867 #ifndef SQLITE_AMALGAMATION
18868 /*
18869 ** The following constant value is used by the SQLITE_BIGENDIAN and
18870 ** SQLITE_LITTLEENDIAN macros.
18871 */
18872 SQLITE_PRIVATE const int sqlite3one = 1;
18873 #endif /* SQLITE_AMALGAMATION */
18874
18875 /*
18876 ** This lookup table is used to help decode the first byte of
18877 ** a multi-byte UTF8 character.
18878 */
18879 static const unsigned char sqlite3Utf8Trans1[] = {
18880   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18881   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18882   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18883   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18884   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18885   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18886   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18887   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18888 };
18889
18890
18891 #define WRITE_UTF8(zOut, c) {                          \
18892   if( c<0x00080 ){                                     \
18893     *zOut++ = (u8)(c&0xFF);                            \
18894   }                                                    \
18895   else if( c<0x00800 ){                                \
18896     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
18897     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18898   }                                                    \
18899   else if( c<0x10000 ){                                \
18900     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
18901     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18902     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18903   }else{                                               \
18904     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
18905     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
18906     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18907     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18908   }                                                    \
18909 }
18910
18911 #define WRITE_UTF16LE(zOut, c) {                                    \
18912   if( c<=0xFFFF ){                                                  \
18913     *zOut++ = (u8)(c&0x00FF);                                       \
18914     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18915   }else{                                                            \
18916     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18917     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18918     *zOut++ = (u8)(c&0x00FF);                                       \
18919     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18920   }                                                                 \
18921 }
18922
18923 #define WRITE_UTF16BE(zOut, c) {                                    \
18924   if( c<=0xFFFF ){                                                  \
18925     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18926     *zOut++ = (u8)(c&0x00FF);                                       \
18927   }else{                                                            \
18928     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18929     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18930     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18931     *zOut++ = (u8)(c&0x00FF);                                       \
18932   }                                                                 \
18933 }
18934
18935 #define READ_UTF16LE(zIn, TERM, c){                                   \
18936   c = (*zIn++);                                                       \
18937   c += ((*zIn++)<<8);                                                 \
18938   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18939     int c2 = (*zIn++);                                                \
18940     c2 += ((*zIn++)<<8);                                              \
18941     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18942   }                                                                   \
18943 }
18944
18945 #define READ_UTF16BE(zIn, TERM, c){                                   \
18946   c = ((*zIn++)<<8);                                                  \
18947   c += (*zIn++);                                                      \
18948   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18949     int c2 = ((*zIn++)<<8);                                           \
18950     c2 += (*zIn++);                                                   \
18951     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18952   }                                                                   \
18953 }
18954
18955 /*
18956 ** Translate a single UTF-8 character.  Return the unicode value.
18957 **
18958 ** During translation, assume that the byte that zTerm points
18959 ** is a 0x00.
18960 **
18961 ** Write a pointer to the next unread byte back into *pzNext.
18962 **
18963 ** Notes On Invalid UTF-8:
18964 **
18965 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18966 **     be encoded as a multi-byte character.  Any multi-byte character that
18967 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18968 **
18969 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18970 **     If a multi-byte character attempts to encode a value between
18971 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18972 **
18973 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18974 **     byte of a character are interpreted as single-byte characters
18975 **     and rendered as themselves even though they are technically
18976 **     invalid characters.
18977 **
18978 **  *  This routine accepts an infinite number of different UTF8 encodings
18979 **     for unicode values 0x80 and greater.  It do not change over-length
18980 **     encodings to 0xfffd as some systems recommend.
18981 */
18982 #define READ_UTF8(zIn, zTerm, c)                           \
18983   c = *(zIn++);                                            \
18984   if( c>=0xc0 ){                                           \
18985     c = sqlite3Utf8Trans1[c-0xc0];                         \
18986     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18987       c = (c<<6) + (0x3f & *(zIn++));                      \
18988     }                                                      \
18989     if( c<0x80                                             \
18990         || (c&0xFFFFF800)==0xD800                          \
18991         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18992   }
18993 SQLITE_PRIVATE int sqlite3Utf8Read(
18994   const unsigned char *zIn,       /* First byte of UTF-8 character */
18995   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18996 ){
18997   int c;
18998
18999   /* Same as READ_UTF8() above but without the zTerm parameter.
19000   ** For this routine, we assume the UTF8 string is always zero-terminated.
19001   */
19002   c = *(zIn++);
19003   if( c>=0xc0 ){
19004     c = sqlite3Utf8Trans1[c-0xc0];
19005     while( (*zIn & 0xc0)==0x80 ){
19006       c = (c<<6) + (0x3f & *(zIn++));
19007     }
19008     if( c<0x80
19009         || (c&0xFFFFF800)==0xD800
19010         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19011   }
19012   *pzNext = zIn;
19013   return c;
19014 }
19015
19016
19017
19018
19019 /*
19020 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19021 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19022 */ 
19023 /* #define TRANSLATE_TRACE 1 */
19024
19025 #ifndef SQLITE_OMIT_UTF16
19026 /*
19027 ** This routine transforms the internal text encoding used by pMem to
19028 ** desiredEnc. It is an error if the string is already of the desired
19029 ** encoding, or if *pMem does not contain a string value.
19030 */
19031 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19032   int len;                    /* Maximum length of output string in bytes */
19033   unsigned char *zOut;                  /* Output buffer */
19034   unsigned char *zIn;                   /* Input iterator */
19035   unsigned char *zTerm;                 /* End of input */
19036   unsigned char *z;                     /* Output iterator */
19037   unsigned int c;
19038
19039   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19040   assert( pMem->flags&MEM_Str );
19041   assert( pMem->enc!=desiredEnc );
19042   assert( pMem->enc!=0 );
19043   assert( pMem->n>=0 );
19044
19045 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19046   {
19047     char zBuf[100];
19048     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19049     fprintf(stderr, "INPUT:  %s\n", zBuf);
19050   }
19051 #endif
19052
19053   /* If the translation is between UTF-16 little and big endian, then 
19054   ** all that is required is to swap the byte order. This case is handled
19055   ** differently from the others.
19056   */
19057   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19058     u8 temp;
19059     int rc;
19060     rc = sqlite3VdbeMemMakeWriteable(pMem);
19061     if( rc!=SQLITE_OK ){
19062       assert( rc==SQLITE_NOMEM );
19063       return SQLITE_NOMEM;
19064     }
19065     zIn = (u8*)pMem->z;
19066     zTerm = &zIn[pMem->n&~1];
19067     while( zIn<zTerm ){
19068       temp = *zIn;
19069       *zIn = *(zIn+1);
19070       zIn++;
19071       *zIn++ = temp;
19072     }
19073     pMem->enc = desiredEnc;
19074     goto translate_out;
19075   }
19076
19077   /* Set len to the maximum number of bytes required in the output buffer. */
19078   if( desiredEnc==SQLITE_UTF8 ){
19079     /* When converting from UTF-16, the maximum growth results from
19080     ** translating a 2-byte character to a 4-byte UTF-8 character.
19081     ** A single byte is required for the output string
19082     ** nul-terminator.
19083     */
19084     pMem->n &= ~1;
19085     len = pMem->n * 2 + 1;
19086   }else{
19087     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19088     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19089     ** character. Two bytes are required in the output buffer for the
19090     ** nul-terminator.
19091     */
19092     len = pMem->n * 2 + 2;
19093   }
19094
19095   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19096   ** byte past the end.
19097   **
19098   ** Variable zOut is set to point at the output buffer, space obtained
19099   ** from sqlite3_malloc().
19100   */
19101   zIn = (u8*)pMem->z;
19102   zTerm = &zIn[pMem->n];
19103   zOut = sqlite3DbMallocRaw(pMem->db, len);
19104   if( !zOut ){
19105     return SQLITE_NOMEM;
19106   }
19107   z = zOut;
19108
19109   if( pMem->enc==SQLITE_UTF8 ){
19110     if( desiredEnc==SQLITE_UTF16LE ){
19111       /* UTF-8 -> UTF-16 Little-endian */
19112       while( zIn<zTerm ){
19113         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19114         READ_UTF8(zIn, zTerm, c);
19115         WRITE_UTF16LE(z, c);
19116       }
19117     }else{
19118       assert( desiredEnc==SQLITE_UTF16BE );
19119       /* UTF-8 -> UTF-16 Big-endian */
19120       while( zIn<zTerm ){
19121         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19122         READ_UTF8(zIn, zTerm, c);
19123         WRITE_UTF16BE(z, c);
19124       }
19125     }
19126     pMem->n = (int)(z - zOut);
19127     *z++ = 0;
19128   }else{
19129     assert( desiredEnc==SQLITE_UTF8 );
19130     if( pMem->enc==SQLITE_UTF16LE ){
19131       /* UTF-16 Little-endian -> UTF-8 */
19132       while( zIn<zTerm ){
19133         READ_UTF16LE(zIn, zIn<zTerm, c); 
19134         WRITE_UTF8(z, c);
19135       }
19136     }else{
19137       /* UTF-16 Big-endian -> UTF-8 */
19138       while( zIn<zTerm ){
19139         READ_UTF16BE(zIn, zIn<zTerm, c); 
19140         WRITE_UTF8(z, c);
19141       }
19142     }
19143     pMem->n = (int)(z - zOut);
19144   }
19145   *z = 0;
19146   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19147
19148   sqlite3VdbeMemRelease(pMem);
19149   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19150   pMem->enc = desiredEnc;
19151   pMem->flags |= (MEM_Term|MEM_Dyn);
19152   pMem->z = (char*)zOut;
19153   pMem->zMalloc = pMem->z;
19154
19155 translate_out:
19156 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19157   {
19158     char zBuf[100];
19159     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19160     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19161   }
19162 #endif
19163   return SQLITE_OK;
19164 }
19165
19166 /*
19167 ** This routine checks for a byte-order mark at the beginning of the 
19168 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19169 ** the encoding of the Mem adjusted. This routine does not do any
19170 ** byte-swapping, it just sets Mem.enc appropriately.
19171 **
19172 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19173 ** changed by this function.
19174 */
19175 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19176   int rc = SQLITE_OK;
19177   u8 bom = 0;
19178
19179   assert( pMem->n>=0 );
19180   if( pMem->n>1 ){
19181     u8 b1 = *(u8 *)pMem->z;
19182     u8 b2 = *(((u8 *)pMem->z) + 1);
19183     if( b1==0xFE && b2==0xFF ){
19184       bom = SQLITE_UTF16BE;
19185     }
19186     if( b1==0xFF && b2==0xFE ){
19187       bom = SQLITE_UTF16LE;
19188     }
19189   }
19190   
19191   if( bom ){
19192     rc = sqlite3VdbeMemMakeWriteable(pMem);
19193     if( rc==SQLITE_OK ){
19194       pMem->n -= 2;
19195       memmove(pMem->z, &pMem->z[2], pMem->n);
19196       pMem->z[pMem->n] = '\0';
19197       pMem->z[pMem->n+1] = '\0';
19198       pMem->flags |= MEM_Term;
19199       pMem->enc = bom;
19200     }
19201   }
19202   return rc;
19203 }
19204 #endif /* SQLITE_OMIT_UTF16 */
19205
19206 /*
19207 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19208 ** return the number of unicode characters in pZ up to (but not including)
19209 ** the first 0x00 byte. If nByte is not less than zero, return the
19210 ** number of unicode characters in the first nByte of pZ (or up to 
19211 ** the first 0x00, whichever comes first).
19212 */
19213 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19214   int r = 0;
19215   const u8 *z = (const u8*)zIn;
19216   const u8 *zTerm;
19217   if( nByte>=0 ){
19218     zTerm = &z[nByte];
19219   }else{
19220     zTerm = (const u8*)(-1);
19221   }
19222   assert( z<=zTerm );
19223   while( *z!=0 && z<zTerm ){
19224     SQLITE_SKIP_UTF8(z);
19225     r++;
19226   }
19227   return r;
19228 }
19229
19230 /* This test function is not currently used by the automated test-suite. 
19231 ** Hence it is only available in debug builds.
19232 */
19233 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19234 /*
19235 ** Translate UTF-8 to UTF-8.
19236 **
19237 ** This has the effect of making sure that the string is well-formed
19238 ** UTF-8.  Miscoded characters are removed.
19239 **
19240 ** The translation is done in-place (since it is impossible for the
19241 ** correct UTF-8 encoding to be longer than a malformed encoding).
19242 */
19243 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19244   unsigned char *zOut = zIn;
19245   unsigned char *zStart = zIn;
19246   u32 c;
19247
19248   while( zIn[0] ){
19249     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19250     if( c!=0xfffd ){
19251       WRITE_UTF8(zOut, c);
19252     }
19253   }
19254   *zOut = 0;
19255   return (int)(zOut - zStart);
19256 }
19257 #endif
19258
19259 #ifndef SQLITE_OMIT_UTF16
19260 /*
19261 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19262 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19263 ** be freed by the calling function.
19264 **
19265 ** NULL is returned if there is an allocation error.
19266 */
19267 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19268   Mem m;
19269   memset(&m, 0, sizeof(m));
19270   m.db = db;
19271   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19272   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19273   if( db->mallocFailed ){
19274     sqlite3VdbeMemRelease(&m);
19275     m.z = 0;
19276   }
19277   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19278   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19279   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19280   assert( m.z || db->mallocFailed );
19281   return m.z;
19282 }
19283
19284 /*
19285 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19286 ** enc. A pointer to the new string is returned, and the value of *pnOut
19287 ** is set to the length of the returned string in bytes. The call should
19288 ** arrange to call sqlite3DbFree() on the returned pointer when it is
19289 ** no longer required.
19290 ** 
19291 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19292 ** flag set.
19293 */
19294 #ifdef SQLITE_ENABLE_STAT2
19295 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19296   Mem m;
19297   memset(&m, 0, sizeof(m));
19298   m.db = db;
19299   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19300   if( sqlite3VdbeMemTranslate(&m, enc) ){
19301     assert( db->mallocFailed );
19302     return 0;
19303   }
19304   assert( m.z==m.zMalloc );
19305   *pnOut = m.n;
19306   return m.z;
19307 }
19308 #endif
19309
19310 /*
19311 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19312 ** Return the number of bytes in the first nChar unicode characters
19313 ** in pZ.  nChar must be non-negative.
19314 */
19315 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19316   int c;
19317   unsigned char const *z = zIn;
19318   int n = 0;
19319   
19320   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19321     while( n<nChar ){
19322       READ_UTF16BE(z, 1, c);
19323       n++;
19324     }
19325   }else{
19326     while( n<nChar ){
19327       READ_UTF16LE(z, 1, c);
19328       n++;
19329     }
19330   }
19331   return (int)(z-(unsigned char const *)zIn);
19332 }
19333
19334 #if defined(SQLITE_TEST)
19335 /*
19336 ** This routine is called from the TCL test function "translate_selftest".
19337 ** It checks that the primitives for serializing and deserializing
19338 ** characters in each encoding are inverses of each other.
19339 */
19340 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19341   unsigned int i, t;
19342   unsigned char zBuf[20];
19343   unsigned char *z;
19344   int n;
19345   unsigned int c;
19346
19347   for(i=0; i<0x00110000; i++){
19348     z = zBuf;
19349     WRITE_UTF8(z, i);
19350     n = (int)(z-zBuf);
19351     assert( n>0 && n<=4 );
19352     z[0] = 0;
19353     z = zBuf;
19354     c = sqlite3Utf8Read(z, (const u8**)&z);
19355     t = i;
19356     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19357     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19358     assert( c==t );
19359     assert( (z-zBuf)==n );
19360   }
19361   for(i=0; i<0x00110000; i++){
19362     if( i>=0xD800 && i<0xE000 ) continue;
19363     z = zBuf;
19364     WRITE_UTF16LE(z, i);
19365     n = (int)(z-zBuf);
19366     assert( n>0 && n<=4 );
19367     z[0] = 0;
19368     z = zBuf;
19369     READ_UTF16LE(z, 1, c);
19370     assert( c==i );
19371     assert( (z-zBuf)==n );
19372   }
19373   for(i=0; i<0x00110000; i++){
19374     if( i>=0xD800 && i<0xE000 ) continue;
19375     z = zBuf;
19376     WRITE_UTF16BE(z, i);
19377     n = (int)(z-zBuf);
19378     assert( n>0 && n<=4 );
19379     z[0] = 0;
19380     z = zBuf;
19381     READ_UTF16BE(z, 1, c);
19382     assert( c==i );
19383     assert( (z-zBuf)==n );
19384   }
19385 }
19386 #endif /* SQLITE_TEST */
19387 #endif /* SQLITE_OMIT_UTF16 */
19388
19389 /************** End of utf.c *************************************************/
19390 /************** Begin file util.c ********************************************/
19391 /*
19392 ** 2001 September 15
19393 **
19394 ** The author disclaims copyright to this source code.  In place of
19395 ** a legal notice, here is a blessing:
19396 **
19397 **    May you do good and not evil.
19398 **    May you find forgiveness for yourself and forgive others.
19399 **    May you share freely, never taking more than you give.
19400 **
19401 *************************************************************************
19402 ** Utility functions used throughout sqlite.
19403 **
19404 ** This file contains functions for allocating memory, comparing
19405 ** strings, and stuff like that.
19406 **
19407 */
19408 #ifdef SQLITE_HAVE_ISNAN
19409 # include <math.h>
19410 #endif
19411
19412 /*
19413 ** Routine needed to support the testcase() macro.
19414 */
19415 #ifdef SQLITE_COVERAGE_TEST
19416 SQLITE_PRIVATE void sqlite3Coverage(int x){
19417   static int dummy = 0;
19418   dummy += x;
19419 }
19420 #endif
19421
19422 #ifndef SQLITE_OMIT_FLOATING_POINT
19423 /*
19424 ** Return true if the floating point value is Not a Number (NaN).
19425 **
19426 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19427 ** Otherwise, we have our own implementation that works on most systems.
19428 */
19429 SQLITE_PRIVATE int sqlite3IsNaN(double x){
19430   int rc;   /* The value return */
19431 #if !defined(SQLITE_HAVE_ISNAN)
19432   /*
19433   ** Systems that support the isnan() library function should probably
19434   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19435   ** found that many systems do not have a working isnan() function so
19436   ** this implementation is provided as an alternative.
19437   **
19438   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
19439   ** On the other hand, the use of -ffast-math comes with the following
19440   ** warning:
19441   **
19442   **      This option [-ffast-math] should never be turned on by any
19443   **      -O option since it can result in incorrect output for programs
19444   **      which depend on an exact implementation of IEEE or ISO 
19445   **      rules/specifications for math functions.
19446   **
19447   ** Under MSVC, this NaN test may fail if compiled with a floating-
19448   ** point precision mode other than /fp:precise.  From the MSDN 
19449   ** documentation:
19450   **
19451   **      The compiler [with /fp:precise] will properly handle comparisons 
19452   **      involving NaN. For example, x != x evaluates to true if x is NaN 
19453   **      ...
19454   */
19455 #ifdef __FAST_MATH__
19456 # error SQLite will not work correctly with the -ffast-math option of GCC.
19457 #endif
19458   volatile double y = x;
19459   volatile double z = y;
19460   rc = (y!=z);
19461 #else  /* if defined(SQLITE_HAVE_ISNAN) */
19462   rc = isnan(x);
19463 #endif /* SQLITE_HAVE_ISNAN */
19464   testcase( rc );
19465   return rc;
19466 }
19467 #endif /* SQLITE_OMIT_FLOATING_POINT */
19468
19469 /*
19470 ** Compute a string length that is limited to what can be stored in
19471 ** lower 30 bits of a 32-bit signed integer.
19472 **
19473 ** The value returned will never be negative.  Nor will it ever be greater
19474 ** than the actual length of the string.  For very long strings (greater
19475 ** than 1GiB) the value returned might be less than the true string length.
19476 */
19477 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19478   const char *z2 = z;
19479   if( z==0 ) return 0;
19480   while( *z2 ){ z2++; }
19481   return 0x3fffffff & (int)(z2 - z);
19482 }
19483
19484 /*
19485 ** Set the most recent error code and error string for the sqlite
19486 ** handle "db". The error code is set to "err_code".
19487 **
19488 ** If it is not NULL, string zFormat specifies the format of the
19489 ** error string in the style of the printf functions: The following
19490 ** format characters are allowed:
19491 **
19492 **      %s      Insert a string
19493 **      %z      A string that should be freed after use
19494 **      %d      Insert an integer
19495 **      %T      Insert a token
19496 **      %S      Insert the first element of a SrcList
19497 **
19498 ** zFormat and any string tokens that follow it are assumed to be
19499 ** encoded in UTF-8.
19500 **
19501 ** To clear the most recent error for sqlite handle "db", sqlite3Error
19502 ** should be called with err_code set to SQLITE_OK and zFormat set
19503 ** to NULL.
19504 */
19505 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19506   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19507     db->errCode = err_code;
19508     if( zFormat ){
19509       char *z;
19510       va_list ap;
19511       va_start(ap, zFormat);
19512       z = sqlite3VMPrintf(db, zFormat, ap);
19513       va_end(ap);
19514       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19515     }else{
19516       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19517     }
19518   }
19519 }
19520
19521 /*
19522 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19523 ** The following formatting characters are allowed:
19524 **
19525 **      %s      Insert a string
19526 **      %z      A string that should be freed after use
19527 **      %d      Insert an integer
19528 **      %T      Insert a token
19529 **      %S      Insert the first element of a SrcList
19530 **
19531 ** This function should be used to report any error that occurs whilst
19532 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19533 ** last thing the sqlite3_prepare() function does is copy the error
19534 ** stored by this function into the database handle using sqlite3Error().
19535 ** Function sqlite3Error() should be used during statement execution
19536 ** (sqlite3_step() etc.).
19537 */
19538 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19539   char *zMsg;
19540   va_list ap;
19541   sqlite3 *db = pParse->db;
19542   va_start(ap, zFormat);
19543   zMsg = sqlite3VMPrintf(db, zFormat, ap);
19544   va_end(ap);
19545   if( db->suppressErr ){
19546     sqlite3DbFree(db, zMsg);
19547   }else{
19548     pParse->nErr++;
19549     sqlite3DbFree(db, pParse->zErrMsg);
19550     pParse->zErrMsg = zMsg;
19551     pParse->rc = SQLITE_ERROR;
19552   }
19553 }
19554
19555 /*
19556 ** Convert an SQL-style quoted string into a normal string by removing
19557 ** the quote characters.  The conversion is done in-place.  If the
19558 ** input does not begin with a quote character, then this routine
19559 ** is a no-op.
19560 **
19561 ** The input string must be zero-terminated.  A new zero-terminator
19562 ** is added to the dequoted string.
19563 **
19564 ** The return value is -1 if no dequoting occurs or the length of the
19565 ** dequoted string, exclusive of the zero terminator, if dequoting does
19566 ** occur.
19567 **
19568 ** 2002-Feb-14: This routine is extended to remove MS-Access style
19569 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
19570 ** "a-b-c".
19571 */
19572 SQLITE_PRIVATE int sqlite3Dequote(char *z){
19573   char quote;
19574   int i, j;
19575   if( z==0 ) return -1;
19576   quote = z[0];
19577   switch( quote ){
19578     case '\'':  break;
19579     case '"':   break;
19580     case '`':   break;                /* For MySQL compatibility */
19581     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19582     default:    return -1;
19583   }
19584   for(i=1, j=0; ALWAYS(z[i]); i++){
19585     if( z[i]==quote ){
19586       if( z[i+1]==quote ){
19587         z[j++] = quote;
19588         i++;
19589       }else{
19590         break;
19591       }
19592     }else{
19593       z[j++] = z[i];
19594     }
19595   }
19596   z[j] = 0;
19597   return j;
19598 }
19599
19600 /* Convenient short-hand */
19601 #define UpperToLower sqlite3UpperToLower
19602
19603 /*
19604 ** Some systems have stricmp().  Others have strcasecmp().  Because
19605 ** there is no consistency, we will define our own.
19606 */
19607 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19608   register unsigned char *a, *b;
19609   a = (unsigned char *)zLeft;
19610   b = (unsigned char *)zRight;
19611   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19612   return UpperToLower[*a] - UpperToLower[*b];
19613 }
19614 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
19615   register unsigned char *a, *b;
19616   a = (unsigned char *)zLeft;
19617   b = (unsigned char *)zRight;
19618   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19619   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19620 }
19621
19622 /*
19623 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
19624 ** *realnum unchanged if the string contains any character which is not
19625 ** part of a number.
19626 **
19627 ** If the string is pure numeric, set *realnum to TRUE if the string
19628 ** contains the '.' character or an "E+000" style exponentiation suffix.
19629 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
19630 ** false does not mean that the number can be successfully converted into
19631 ** an integer - it might be too big.
19632 **
19633 ** An empty string is considered non-numeric.
19634 */
19635 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19636   int incr = (enc==SQLITE_UTF8?1:2);
19637   if( enc==SQLITE_UTF16BE ) z++;
19638   if( *z=='-' || *z=='+' ) z += incr;
19639   if( !sqlite3Isdigit(*z) ){
19640     return 0;
19641   }
19642   z += incr;
19643   *realnum = 0;
19644   while( sqlite3Isdigit(*z) ){ z += incr; }
19645 #ifndef SQLITE_OMIT_FLOATING_POINT
19646   if( *z=='.' ){
19647     z += incr;
19648     if( !sqlite3Isdigit(*z) ) return 0;
19649     while( sqlite3Isdigit(*z) ){ z += incr; }
19650     *realnum = 1;
19651   }
19652   if( *z=='e' || *z=='E' ){
19653     z += incr;
19654     if( *z=='+' || *z=='-' ) z += incr;
19655     if( !sqlite3Isdigit(*z) ) return 0;
19656     while( sqlite3Isdigit(*z) ){ z += incr; }
19657     *realnum = 1;
19658   }
19659 #endif
19660   return *z==0;
19661 }
19662
19663 /*
19664 ** The string z[] is an ASCII representation of a real number.
19665 ** Convert this string to a double.
19666 **
19667 ** This routine assumes that z[] really is a valid number.  If it
19668 ** is not, the result is undefined.
19669 **
19670 ** This routine is used instead of the library atof() function because
19671 ** the library atof() might want to use "," as the decimal point instead
19672 ** of "." depending on how locale is set.  But that would cause problems
19673 ** for SQL.  So this routine always uses "." regardless of locale.
19674 */
19675 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19676 #ifndef SQLITE_OMIT_FLOATING_POINT
19677   const char *zBegin = z;
19678   /* sign * significand * (10 ^ (esign * exponent)) */
19679   int sign = 1;   /* sign of significand */
19680   i64 s = 0;      /* significand */
19681   int d = 0;      /* adjust exponent for shifting decimal point */
19682   int esign = 1;  /* sign of exponent */
19683   int e = 0;      /* exponent */
19684   double result;
19685   int nDigits = 0;
19686
19687   /* skip leading spaces */
19688   while( sqlite3Isspace(*z) ) z++;
19689   /* get sign of significand */
19690   if( *z=='-' ){
19691     sign = -1;
19692     z++;
19693   }else if( *z=='+' ){
19694     z++;
19695   }
19696   /* skip leading zeroes */
19697   while( z[0]=='0' ) z++, nDigits++;
19698
19699   /* copy max significant digits to significand */
19700   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19701     s = s*10 + (*z - '0');
19702     z++, nDigits++;
19703   }
19704   /* skip non-significant significand digits
19705   ** (increase exponent by d to shift decimal left) */
19706   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
19707
19708   /* if decimal point is present */
19709   if( *z=='.' ){
19710     z++;
19711     /* copy digits from after decimal to significand
19712     ** (decrease exponent by d to shift decimal right) */
19713     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19714       s = s*10 + (*z - '0');
19715       z++, nDigits++, d--;
19716     }
19717     /* skip non-significant digits */
19718     while( sqlite3Isdigit(*z) ) z++, nDigits++;
19719   }
19720
19721   /* if exponent is present */
19722   if( *z=='e' || *z=='E' ){
19723     z++;
19724     /* get sign of exponent */
19725     if( *z=='-' ){
19726       esign = -1;
19727       z++;
19728     }else if( *z=='+' ){
19729       z++;
19730     }
19731     /* copy digits to exponent */
19732     while( sqlite3Isdigit(*z) ){
19733       e = e*10 + (*z - '0');
19734       z++;
19735     }
19736   }
19737
19738   /* adjust exponent by d, and update sign */
19739   e = (e*esign) + d;
19740   if( e<0 ) {
19741     esign = -1;
19742     e *= -1;
19743   } else {
19744     esign = 1;
19745   }
19746
19747   /* if 0 significand */
19748   if( !s ) {
19749     /* In the IEEE 754 standard, zero is signed.
19750     ** Add the sign if we've seen at least one digit */
19751     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
19752   } else {
19753     /* attempt to reduce exponent */
19754     if( esign>0 ){
19755       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
19756     }else{
19757       while( !(s%10) && e>0 ) e--,s/=10;
19758     }
19759
19760     /* adjust the sign of significand */
19761     s = sign<0 ? -s : s;
19762
19763     /* if exponent, scale significand as appropriate
19764     ** and store in result. */
19765     if( e ){
19766       double scale = 1.0;
19767       /* attempt to handle extremely small/large numbers better */
19768       if( e>307 && e<342 ){
19769         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
19770         if( esign<0 ){
19771           result = s / scale;
19772           result /= 1.0e+308;
19773         }else{
19774           result = s * scale;
19775           result *= 1.0e+308;
19776         }
19777       }else{
19778         /* 1.0e+22 is the largest power of 10 than can be 
19779         ** represented exactly. */
19780         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
19781         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
19782         if( esign<0 ){
19783           result = s / scale;
19784         }else{
19785           result = s * scale;
19786         }
19787       }
19788     } else {
19789       result = (double)s;
19790     }
19791   }
19792
19793   /* store the result */
19794   *pResult = result;
19795
19796   /* return number of characters used */
19797   return (int)(z - zBegin);
19798 #else
19799   return sqlite3Atoi64(z, pResult);
19800 #endif /* SQLITE_OMIT_FLOATING_POINT */
19801 }
19802
19803 /*
19804 ** Compare the 19-character string zNum against the text representation
19805 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19806 ** if zNum is less than, equal to, or greater than the string.
19807 **
19808 ** Unlike memcmp() this routine is guaranteed to return the difference
19809 ** in the values of the last digit if the only difference is in the
19810 ** last digit.  So, for example,
19811 **
19812 **      compare2pow63("9223372036854775800")
19813 **
19814 ** will return -8.
19815 */
19816 static int compare2pow63(const char *zNum){
19817   int c;
19818   c = memcmp(zNum,"922337203685477580",18)*10;
19819   if( c==0 ){
19820     c = zNum[18] - '8';
19821     testcase( c==(-1) );
19822     testcase( c==0 );
19823     testcase( c==(+1) );
19824   }
19825   return c;
19826 }
19827
19828
19829 /*
19830 ** Return TRUE if zNum is a 64-bit signed integer and write
19831 ** the value of the integer into *pNum.  If zNum is not an integer
19832 ** or is an integer that is too large to be expressed with 64 bits,
19833 ** then return false.
19834 **
19835 ** When this routine was originally written it dealt with only
19836 ** 32-bit numbers.  At that time, it was much faster than the
19837 ** atoi() library routine in RedHat 7.2.
19838 */
19839 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19840   i64 v = 0;
19841   int neg;
19842   int i, c;
19843   const char *zStart;
19844   while( sqlite3Isspace(*zNum) ) zNum++;
19845   if( *zNum=='-' ){
19846     neg = 1;
19847     zNum++;
19848   }else if( *zNum=='+' ){
19849     neg = 0;
19850     zNum++;
19851   }else{
19852     neg = 0;
19853   }
19854   zStart = zNum;
19855   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19856   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19857     v = v*10 + c - '0';
19858   }
19859   *pNum = neg ? -v : v;
19860   testcase( i==18 );
19861   testcase( i==19 );
19862   testcase( i==20 );
19863   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19864     /* zNum is empty or contains non-numeric text or is longer
19865     ** than 19 digits (thus guaranting that it is too large) */
19866     return 0;
19867   }else if( i<19 ){
19868     /* Less than 19 digits, so we know that it fits in 64 bits */
19869     return 1;
19870   }else{
19871     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19872     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19873     ** is 2^63. */
19874     return compare2pow63(zNum)<neg;
19875   }
19876 }
19877
19878 /*
19879 ** The string zNum represents an unsigned integer.  The zNum string
19880 ** consists of one or more digit characters and is terminated by
19881 ** a zero character.  Any stray characters in zNum result in undefined
19882 ** behavior.
19883 **
19884 ** If the unsigned integer that zNum represents will fit in a
19885 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19886 **
19887 ** If the negFlag parameter is true, that means that zNum really represents
19888 ** a negative number.  (The leading "-" is omitted from zNum.)  This
19889 ** parameter is needed to determine a boundary case.  A string
19890 ** of "9223373036854775808" returns false if negFlag is false or true
19891 ** if negFlag is true.
19892 **
19893 ** Leading zeros are ignored.
19894 */
19895 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19896   int i;
19897   int neg = 0;
19898
19899   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
19900
19901   if( negFlag ) neg = 1-neg;
19902   while( *zNum=='0' ){
19903     zNum++;   /* Skip leading zeros.  Ticket #2454 */
19904   }
19905   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
19906   testcase( i==18 );
19907   testcase( i==19 );
19908   testcase( i==20 );
19909   if( i<19 ){
19910     /* Guaranteed to fit if less than 19 digits */
19911     return 1;
19912   }else if( i>19 ){
19913     /* Guaranteed to be too big if greater than 19 digits */
19914     return 0;
19915   }else{
19916     /* Compare against 2^63. */
19917     return compare2pow63(zNum)<neg;
19918   }
19919 }
19920
19921 /*
19922 ** If zNum represents an integer that will fit in 32-bits, then set
19923 ** *pValue to that integer and return true.  Otherwise return false.
19924 **
19925 ** Any non-numeric characters that following zNum are ignored.
19926 ** This is different from sqlite3Atoi64() which requires the
19927 ** input number to be zero-terminated.
19928 */
19929 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19930   sqlite_int64 v = 0;
19931   int i, c;
19932   int neg = 0;
19933   if( zNum[0]=='-' ){
19934     neg = 1;
19935     zNum++;
19936   }else if( zNum[0]=='+' ){
19937     zNum++;
19938   }
19939   while( zNum[0]=='0' ) zNum++;
19940   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19941     v = v*10 + c;
19942   }
19943
19944   /* The longest decimal representation of a 32 bit integer is 10 digits:
19945   **
19946   **             1234567890
19947   **     2^31 -> 2147483648
19948   */
19949   testcase( i==10 );
19950   if( i>10 ){
19951     return 0;
19952   }
19953   testcase( v-neg==2147483647 );
19954   if( v-neg>2147483647 ){
19955     return 0;
19956   }
19957   if( neg ){
19958     v = -v;
19959   }
19960   *pValue = (int)v;
19961   return 1;
19962 }
19963
19964 /*
19965 ** The variable-length integer encoding is as follows:
19966 **
19967 ** KEY:
19968 **         A = 0xxxxxxx    7 bits of data and one flag bit
19969 **         B = 1xxxxxxx    7 bits of data and one flag bit
19970 **         C = xxxxxxxx    8 bits of data
19971 **
19972 **  7 bits - A
19973 ** 14 bits - BA
19974 ** 21 bits - BBA
19975 ** 28 bits - BBBA
19976 ** 35 bits - BBBBA
19977 ** 42 bits - BBBBBA
19978 ** 49 bits - BBBBBBA
19979 ** 56 bits - BBBBBBBA
19980 ** 64 bits - BBBBBBBBC
19981 */
19982
19983 /*
19984 ** Write a 64-bit variable-length integer to memory starting at p[0].
19985 ** The length of data write will be between 1 and 9 bytes.  The number
19986 ** of bytes written is returned.
19987 **
19988 ** A variable-length integer consists of the lower 7 bits of each byte
19989 ** for all bytes that have the 8th bit set and one byte with the 8th
19990 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19991 ** 8 bits and is the last byte.
19992 */
19993 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19994   int i, j, n;
19995   u8 buf[10];
19996   if( v & (((u64)0xff000000)<<32) ){
19997     p[8] = (u8)v;
19998     v >>= 8;
19999     for(i=7; i>=0; i--){
20000       p[i] = (u8)((v & 0x7f) | 0x80);
20001       v >>= 7;
20002     }
20003     return 9;
20004   }    
20005   n = 0;
20006   do{
20007     buf[n++] = (u8)((v & 0x7f) | 0x80);
20008     v >>= 7;
20009   }while( v!=0 );
20010   buf[0] &= 0x7f;
20011   assert( n<=9 );
20012   for(i=0, j=n-1; j>=0; j--, i++){
20013     p[i] = buf[j];
20014   }
20015   return n;
20016 }
20017
20018 /*
20019 ** This routine is a faster version of sqlite3PutVarint() that only
20020 ** works for 32-bit positive integers and which is optimized for
20021 ** the common case of small integers.  A MACRO version, putVarint32,
20022 ** is provided which inlines the single-byte case.  All code should use
20023 ** the MACRO version as this function assumes the single-byte case has
20024 ** already been handled.
20025 */
20026 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20027 #ifndef putVarint32
20028   if( (v & ~0x7f)==0 ){
20029     p[0] = v;
20030     return 1;
20031   }
20032 #endif
20033   if( (v & ~0x3fff)==0 ){
20034     p[0] = (u8)((v>>7) | 0x80);
20035     p[1] = (u8)(v & 0x7f);
20036     return 2;
20037   }
20038   return sqlite3PutVarint(p, v);
20039 }
20040
20041 /*
20042 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20043 ** are defined here rather than simply putting the constant expressions
20044 ** inline in order to work around bugs in the RVT compiler.
20045 **
20046 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20047 **
20048 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20049 */
20050 #define SLOT_2_0     0x001fc07f
20051 #define SLOT_4_2_0   0xf01fc07f
20052
20053
20054 /*
20055 ** Read a 64-bit variable-length integer from memory starting at p[0].
20056 ** Return the number of bytes read.  The value is stored in *v.
20057 */
20058 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20059   u32 a,b,s;
20060
20061   a = *p;
20062   /* a: p0 (unmasked) */
20063   if (!(a&0x80))
20064   {
20065     *v = a;
20066     return 1;
20067   }
20068
20069   p++;
20070   b = *p;
20071   /* b: p1 (unmasked) */
20072   if (!(b&0x80))
20073   {
20074     a &= 0x7f;
20075     a = a<<7;
20076     a |= b;
20077     *v = a;
20078     return 2;
20079   }
20080
20081   /* Verify that constants are precomputed correctly */
20082   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20083   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20084
20085   p++;
20086   a = a<<14;
20087   a |= *p;
20088   /* a: p0<<14 | p2 (unmasked) */
20089   if (!(a&0x80))
20090   {
20091     a &= SLOT_2_0;
20092     b &= 0x7f;
20093     b = b<<7;
20094     a |= b;
20095     *v = a;
20096     return 3;
20097   }
20098
20099   /* CSE1 from below */
20100   a &= SLOT_2_0;
20101   p++;
20102   b = b<<14;
20103   b |= *p;
20104   /* b: p1<<14 | p3 (unmasked) */
20105   if (!(b&0x80))
20106   {
20107     b &= SLOT_2_0;
20108     /* moved CSE1 up */
20109     /* a &= (0x7f<<14)|(0x7f); */
20110     a = a<<7;
20111     a |= b;
20112     *v = a;
20113     return 4;
20114   }
20115
20116   /* a: p0<<14 | p2 (masked) */
20117   /* b: p1<<14 | p3 (unmasked) */
20118   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20119   /* moved CSE1 up */
20120   /* a &= (0x7f<<14)|(0x7f); */
20121   b &= SLOT_2_0;
20122   s = a;
20123   /* s: p0<<14 | p2 (masked) */
20124
20125   p++;
20126   a = a<<14;
20127   a |= *p;
20128   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20129   if (!(a&0x80))
20130   {
20131     /* we can skip these cause they were (effectively) done above in calc'ing s */
20132     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20133     /* b &= (0x7f<<14)|(0x7f); */
20134     b = b<<7;
20135     a |= b;
20136     s = s>>18;
20137     *v = ((u64)s)<<32 | a;
20138     return 5;
20139   }
20140
20141   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20142   s = s<<7;
20143   s |= b;
20144   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20145
20146   p++;
20147   b = b<<14;
20148   b |= *p;
20149   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20150   if (!(b&0x80))
20151   {
20152     /* we can skip this cause it was (effectively) done above in calc'ing s */
20153     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20154     a &= SLOT_2_0;
20155     a = a<<7;
20156     a |= b;
20157     s = s>>18;
20158     *v = ((u64)s)<<32 | a;
20159     return 6;
20160   }
20161
20162   p++;
20163   a = a<<14;
20164   a |= *p;
20165   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20166   if (!(a&0x80))
20167   {
20168     a &= SLOT_4_2_0;
20169     b &= SLOT_2_0;
20170     b = b<<7;
20171     a |= b;
20172     s = s>>11;
20173     *v = ((u64)s)<<32 | a;
20174     return 7;
20175   }
20176
20177   /* CSE2 from below */
20178   a &= SLOT_2_0;
20179   p++;
20180   b = b<<14;
20181   b |= *p;
20182   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20183   if (!(b&0x80))
20184   {
20185     b &= SLOT_4_2_0;
20186     /* moved CSE2 up */
20187     /* a &= (0x7f<<14)|(0x7f); */
20188     a = a<<7;
20189     a |= b;
20190     s = s>>4;
20191     *v = ((u64)s)<<32 | a;
20192     return 8;
20193   }
20194
20195   p++;
20196   a = a<<15;
20197   a |= *p;
20198   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20199
20200   /* moved CSE2 up */
20201   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20202   b &= SLOT_2_0;
20203   b = b<<8;
20204   a |= b;
20205
20206   s = s<<4;
20207   b = p[-4];
20208   b &= 0x7f;
20209   b = b>>3;
20210   s |= b;
20211
20212   *v = ((u64)s)<<32 | a;
20213
20214   return 9;
20215 }
20216
20217 /*
20218 ** Read a 32-bit variable-length integer from memory starting at p[0].
20219 ** Return the number of bytes read.  The value is stored in *v.
20220 **
20221 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20222 ** integer, then set *v to 0xffffffff.
20223 **
20224 ** A MACRO version, getVarint32, is provided which inlines the 
20225 ** single-byte case.  All code should use the MACRO version as 
20226 ** this function assumes the single-byte case has already been handled.
20227 */
20228 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20229   u32 a,b;
20230
20231   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20232   ** by the getVarin32() macro */
20233   a = *p;
20234   /* a: p0 (unmasked) */
20235 #ifndef getVarint32
20236   if (!(a&0x80))
20237   {
20238     /* Values between 0 and 127 */
20239     *v = a;
20240     return 1;
20241   }
20242 #endif
20243
20244   /* The 2-byte case */
20245   p++;
20246   b = *p;
20247   /* b: p1 (unmasked) */
20248   if (!(b&0x80))
20249   {
20250     /* Values between 128 and 16383 */
20251     a &= 0x7f;
20252     a = a<<7;
20253     *v = a | b;
20254     return 2;
20255   }
20256
20257   /* The 3-byte case */
20258   p++;
20259   a = a<<14;
20260   a |= *p;
20261   /* a: p0<<14 | p2 (unmasked) */
20262   if (!(a&0x80))
20263   {
20264     /* Values between 16384 and 2097151 */
20265     a &= (0x7f<<14)|(0x7f);
20266     b &= 0x7f;
20267     b = b<<7;
20268     *v = a | b;
20269     return 3;
20270   }
20271
20272   /* A 32-bit varint is used to store size information in btrees.
20273   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20274   ** A 3-byte varint is sufficient, for example, to record the size
20275   ** of a 1048569-byte BLOB or string.
20276   **
20277   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20278   ** rare larger cases can be handled by the slower 64-bit varint
20279   ** routine.
20280   */
20281 #if 1
20282   {
20283     u64 v64;
20284     u8 n;
20285
20286     p -= 2;
20287     n = sqlite3GetVarint(p, &v64);
20288     assert( n>3 && n<=9 );
20289     if( (v64 & SQLITE_MAX_U32)!=v64 ){
20290       *v = 0xffffffff;
20291     }else{
20292       *v = (u32)v64;
20293     }
20294     return n;
20295   }
20296
20297 #else
20298   /* For following code (kept for historical record only) shows an
20299   ** unrolling for the 3- and 4-byte varint cases.  This code is
20300   ** slightly faster, but it is also larger and much harder to test.
20301   */
20302   p++;
20303   b = b<<14;
20304   b |= *p;
20305   /* b: p1<<14 | p3 (unmasked) */
20306   if (!(b&0x80))
20307   {
20308     /* Values between 2097152 and 268435455 */
20309     b &= (0x7f<<14)|(0x7f);
20310     a &= (0x7f<<14)|(0x7f);
20311     a = a<<7;
20312     *v = a | b;
20313     return 4;
20314   }
20315
20316   p++;
20317   a = a<<14;
20318   a |= *p;
20319   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20320   if (!(a&0x80))
20321   {
20322     /* Values  between 268435456 and 34359738367 */
20323     a &= SLOT_4_2_0;
20324     b &= SLOT_4_2_0;
20325     b = b<<7;
20326     *v = a | b;
20327     return 5;
20328   }
20329
20330   /* We can only reach this point when reading a corrupt database
20331   ** file.  In that case we are not in any hurry.  Use the (relatively
20332   ** slow) general-purpose sqlite3GetVarint() routine to extract the
20333   ** value. */
20334   {
20335     u64 v64;
20336     u8 n;
20337
20338     p -= 4;
20339     n = sqlite3GetVarint(p, &v64);
20340     assert( n>5 && n<=9 );
20341     *v = (u32)v64;
20342     return n;
20343   }
20344 #endif
20345 }
20346
20347 /*
20348 ** Return the number of bytes that will be needed to store the given
20349 ** 64-bit integer.
20350 */
20351 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20352   int i = 0;
20353   do{
20354     i++;
20355     v >>= 7;
20356   }while( v!=0 && ALWAYS(i<9) );
20357   return i;
20358 }
20359
20360
20361 /*
20362 ** Read or write a four-byte big-endian integer value.
20363 */
20364 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20365   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20366 }
20367 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20368   p[0] = (u8)(v>>24);
20369   p[1] = (u8)(v>>16);
20370   p[2] = (u8)(v>>8);
20371   p[3] = (u8)v;
20372 }
20373
20374
20375
20376 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20377 /*
20378 ** Translate a single byte of Hex into an integer.
20379 ** This routine only works if h really is a valid hexadecimal
20380 ** character:  0..9a..fA..F
20381 */
20382 static u8 hexToInt(int h){
20383   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20384 #ifdef SQLITE_ASCII
20385   h += 9*(1&(h>>6));
20386 #endif
20387 #ifdef SQLITE_EBCDIC
20388   h += 9*(1&~(h>>4));
20389 #endif
20390   return (u8)(h & 0xf);
20391 }
20392 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20393
20394 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20395 /*
20396 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20397 ** value.  Return a pointer to its binary value.  Space to hold the
20398 ** binary value has been obtained from malloc and must be freed by
20399 ** the calling routine.
20400 */
20401 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20402   char *zBlob;
20403   int i;
20404
20405   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20406   n--;
20407   if( zBlob ){
20408     for(i=0; i<n; i+=2){
20409       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20410     }
20411     zBlob[i/2] = 0;
20412   }
20413   return zBlob;
20414 }
20415 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20416
20417 /*
20418 ** Log an error that is an API call on a connection pointer that should
20419 ** not have been used.  The "type" of connection pointer is given as the
20420 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20421 */
20422 static void logBadConnection(const char *zType){
20423   sqlite3_log(SQLITE_MISUSE, 
20424      "API call with %s database connection pointer",
20425      zType
20426   );
20427 }
20428
20429 /*
20430 ** Check to make sure we have a valid db pointer.  This test is not
20431 ** foolproof but it does provide some measure of protection against
20432 ** misuse of the interface such as passing in db pointers that are
20433 ** NULL or which have been previously closed.  If this routine returns
20434 ** 1 it means that the db pointer is valid and 0 if it should not be
20435 ** dereferenced for any reason.  The calling function should invoke
20436 ** SQLITE_MISUSE immediately.
20437 **
20438 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20439 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20440 ** open properly and is not fit for general use but which can be
20441 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
20442 */
20443 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20444   u32 magic;
20445   if( db==0 ){
20446     logBadConnection("NULL");
20447     return 0;
20448   }
20449   magic = db->magic;
20450   if( magic!=SQLITE_MAGIC_OPEN ){
20451     if( sqlite3SafetyCheckSickOrOk(db) ){
20452       testcase( sqlite3GlobalConfig.xLog!=0 );
20453       logBadConnection("unopened");
20454     }
20455     return 0;
20456   }else{
20457     return 1;
20458   }
20459 }
20460 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20461   u32 magic;
20462   magic = db->magic;
20463   if( magic!=SQLITE_MAGIC_SICK &&
20464       magic!=SQLITE_MAGIC_OPEN &&
20465       magic!=SQLITE_MAGIC_BUSY ){
20466     testcase( sqlite3GlobalConfig.xLog!=0 );
20467     logBadConnection("invalid");
20468     return 0;
20469   }else{
20470     return 1;
20471   }
20472 }
20473
20474 /************** End of util.c ************************************************/
20475 /************** Begin file hash.c ********************************************/
20476 /*
20477 ** 2001 September 22
20478 **
20479 ** The author disclaims copyright to this source code.  In place of
20480 ** a legal notice, here is a blessing:
20481 **
20482 **    May you do good and not evil.
20483 **    May you find forgiveness for yourself and forgive others.
20484 **    May you share freely, never taking more than you give.
20485 **
20486 *************************************************************************
20487 ** This is the implementation of generic hash-tables
20488 ** used in SQLite.
20489 */
20490
20491 /* Turn bulk memory into a hash table object by initializing the
20492 ** fields of the Hash structure.
20493 **
20494 ** "pNew" is a pointer to the hash table that is to be initialized.
20495 */
20496 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20497   assert( pNew!=0 );
20498   pNew->first = 0;
20499   pNew->count = 0;
20500   pNew->htsize = 0;
20501   pNew->ht = 0;
20502 }
20503
20504 /* Remove all entries from a hash table.  Reclaim all memory.
20505 ** Call this routine to delete a hash table or to reset a hash table
20506 ** to the empty state.
20507 */
20508 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20509   HashElem *elem;         /* For looping over all elements of the table */
20510
20511   assert( pH!=0 );
20512   elem = pH->first;
20513   pH->first = 0;
20514   sqlite3_free(pH->ht);
20515   pH->ht = 0;
20516   pH->htsize = 0;
20517   while( elem ){
20518     HashElem *next_elem = elem->next;
20519     sqlite3_free(elem);
20520     elem = next_elem;
20521   }
20522   pH->count = 0;
20523 }
20524
20525 /*
20526 ** The hashing function.
20527 */
20528 static unsigned int strHash(const char *z, int nKey){
20529   int h = 0;
20530   assert( nKey>=0 );
20531   while( nKey > 0  ){
20532     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20533     nKey--;
20534   }
20535   return h;
20536 }
20537
20538
20539 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
20540 ** insert pNew into the pEntry hash bucket.
20541 */
20542 static void insertElement(
20543   Hash *pH,              /* The complete hash table */
20544   struct _ht *pEntry,    /* The entry into which pNew is inserted */
20545   HashElem *pNew         /* The element to be inserted */
20546 ){
20547   HashElem *pHead;       /* First element already in pEntry */
20548   if( pEntry ){
20549     pHead = pEntry->count ? pEntry->chain : 0;
20550     pEntry->count++;
20551     pEntry->chain = pNew;
20552   }else{
20553     pHead = 0;
20554   }
20555   if( pHead ){
20556     pNew->next = pHead;
20557     pNew->prev = pHead->prev;
20558     if( pHead->prev ){ pHead->prev->next = pNew; }
20559     else             { pH->first = pNew; }
20560     pHead->prev = pNew;
20561   }else{
20562     pNew->next = pH->first;
20563     if( pH->first ){ pH->first->prev = pNew; }
20564     pNew->prev = 0;
20565     pH->first = pNew;
20566   }
20567 }
20568
20569
20570 /* Resize the hash table so that it cantains "new_size" buckets.
20571 **
20572 ** The hash table might fail to resize if sqlite3_malloc() fails or
20573 ** if the new size is the same as the prior size.
20574 ** Return TRUE if the resize occurs and false if not.
20575 */
20576 static int rehash(Hash *pH, unsigned int new_size){
20577   struct _ht *new_ht;            /* The new hash table */
20578   HashElem *elem, *next_elem;    /* For looping over existing elements */
20579
20580 #if SQLITE_MALLOC_SOFT_LIMIT>0
20581   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20582     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20583   }
20584   if( new_size==pH->htsize ) return 0;
20585 #endif
20586
20587   /* The inability to allocates space for a larger hash table is
20588   ** a performance hit but it is not a fatal error.  So mark the
20589   ** allocation as a benign.
20590   */
20591   sqlite3BeginBenignMalloc();
20592   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
20593   sqlite3EndBenignMalloc();
20594
20595   if( new_ht==0 ) return 0;
20596   sqlite3_free(pH->ht);
20597   pH->ht = new_ht;
20598   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
20599   memset(new_ht, 0, new_size*sizeof(struct _ht));
20600   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20601     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
20602     next_elem = elem->next;
20603     insertElement(pH, &new_ht[h], elem);
20604   }
20605   return 1;
20606 }
20607
20608 /* This function (for internal use only) locates an element in an
20609 ** hash table that matches the given key.  The hash for this key has
20610 ** already been computed and is passed as the 4th parameter.
20611 */
20612 static HashElem *findElementGivenHash(
20613   const Hash *pH,     /* The pH to be searched */
20614   const char *pKey,   /* The key we are searching for */
20615   int nKey,           /* Bytes in key (not counting zero terminator) */
20616   unsigned int h      /* The hash for this key. */
20617 ){
20618   HashElem *elem;                /* Used to loop thru the element list */
20619   int count;                     /* Number of elements left to test */
20620
20621   if( pH->ht ){
20622     struct _ht *pEntry = &pH->ht[h];
20623     elem = pEntry->chain;
20624     count = pEntry->count;
20625   }else{
20626     elem = pH->first;
20627     count = pH->count;
20628   }
20629   while( count-- && ALWAYS(elem) ){
20630     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
20631       return elem;
20632     }
20633     elem = elem->next;
20634   }
20635   return 0;
20636 }
20637
20638 /* Remove a single entry from the hash table given a pointer to that
20639 ** element and a hash on the element's key.
20640 */
20641 static void removeElementGivenHash(
20642   Hash *pH,         /* The pH containing "elem" */
20643   HashElem* elem,   /* The element to be removed from the pH */
20644   unsigned int h    /* Hash value for the element */
20645 ){
20646   struct _ht *pEntry;
20647   if( elem->prev ){
20648     elem->prev->next = elem->next; 
20649   }else{
20650     pH->first = elem->next;
20651   }
20652   if( elem->next ){
20653     elem->next->prev = elem->prev;
20654   }
20655   if( pH->ht ){
20656     pEntry = &pH->ht[h];
20657     if( pEntry->chain==elem ){
20658       pEntry->chain = elem->next;
20659     }
20660     pEntry->count--;
20661     assert( pEntry->count>=0 );
20662   }
20663   sqlite3_free( elem );
20664   pH->count--;
20665   if( pH->count<=0 ){
20666     assert( pH->first==0 );
20667     assert( pH->count==0 );
20668     sqlite3HashClear(pH);
20669   }
20670 }
20671
20672 /* Attempt to locate an element of the hash table pH with a key
20673 ** that matches pKey,nKey.  Return the data for this element if it is
20674 ** found, or NULL if there is no match.
20675 */
20676 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
20677   HashElem *elem;    /* The element that matches key */
20678   unsigned int h;    /* A hash on key */
20679
20680   assert( pH!=0 );
20681   assert( pKey!=0 );
20682   assert( nKey>=0 );
20683   if( pH->ht ){
20684     h = strHash(pKey, nKey) % pH->htsize;
20685   }else{
20686     h = 0;
20687   }
20688   elem = findElementGivenHash(pH, pKey, nKey, h);
20689   return elem ? elem->data : 0;
20690 }
20691
20692 /* Insert an element into the hash table pH.  The key is pKey,nKey
20693 ** and the data is "data".
20694 **
20695 ** If no element exists with a matching key, then a new
20696 ** element is created and NULL is returned.
20697 **
20698 ** If another element already exists with the same key, then the
20699 ** new data replaces the old data and the old data is returned.
20700 ** The key is not copied in this instance.  If a malloc fails, then
20701 ** the new data is returned and the hash table is unchanged.
20702 **
20703 ** If the "data" parameter to this function is NULL, then the
20704 ** element corresponding to "key" is removed from the hash table.
20705 */
20706 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
20707   unsigned int h;       /* the hash of the key modulo hash table size */
20708   HashElem *elem;       /* Used to loop thru the element list */
20709   HashElem *new_elem;   /* New element added to the pH */
20710
20711   assert( pH!=0 );
20712   assert( pKey!=0 );
20713   assert( nKey>=0 );
20714   if( pH->htsize ){
20715     h = strHash(pKey, nKey) % pH->htsize;
20716   }else{
20717     h = 0;
20718   }
20719   elem = findElementGivenHash(pH,pKey,nKey,h);
20720   if( elem ){
20721     void *old_data = elem->data;
20722     if( data==0 ){
20723       removeElementGivenHash(pH,elem,h);
20724     }else{
20725       elem->data = data;
20726       elem->pKey = pKey;
20727       assert(nKey==elem->nKey);
20728     }
20729     return old_data;
20730   }
20731   if( data==0 ) return 0;
20732   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20733   if( new_elem==0 ) return data;
20734   new_elem->pKey = pKey;
20735   new_elem->nKey = nKey;
20736   new_elem->data = data;
20737   pH->count++;
20738   if( pH->count>=10 && pH->count > 2*pH->htsize ){
20739     if( rehash(pH, pH->count*2) ){
20740       assert( pH->htsize>0 );
20741       h = strHash(pKey, nKey) % pH->htsize;
20742     }
20743   }
20744   if( pH->ht ){
20745     insertElement(pH, &pH->ht[h], new_elem);
20746   }else{
20747     insertElement(pH, 0, new_elem);
20748   }
20749   return 0;
20750 }
20751
20752 /************** End of hash.c ************************************************/
20753 /************** Begin file opcodes.c *****************************************/
20754 /* Automatically generated.  Do not edit */
20755 /* See the mkopcodec.awk script for details. */
20756 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20757 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20758  static const char *const azName[] = { "?",
20759      /*   1 */ "Goto",
20760      /*   2 */ "Gosub",
20761      /*   3 */ "Return",
20762      /*   4 */ "Yield",
20763      /*   5 */ "HaltIfNull",
20764      /*   6 */ "Halt",
20765      /*   7 */ "Integer",
20766      /*   8 */ "Int64",
20767      /*   9 */ "String",
20768      /*  10 */ "Null",
20769      /*  11 */ "Blob",
20770      /*  12 */ "Variable",
20771      /*  13 */ "Move",
20772      /*  14 */ "Copy",
20773      /*  15 */ "SCopy",
20774      /*  16 */ "ResultRow",
20775      /*  17 */ "CollSeq",
20776      /*  18 */ "Function",
20777      /*  19 */ "Not",
20778      /*  20 */ "AddImm",
20779      /*  21 */ "MustBeInt",
20780      /*  22 */ "RealAffinity",
20781      /*  23 */ "Permutation",
20782      /*  24 */ "Compare",
20783      /*  25 */ "Jump",
20784      /*  26 */ "If",
20785      /*  27 */ "IfNot",
20786      /*  28 */ "Column",
20787      /*  29 */ "Affinity",
20788      /*  30 */ "MakeRecord",
20789      /*  31 */ "Count",
20790      /*  32 */ "Savepoint",
20791      /*  33 */ "AutoCommit",
20792      /*  34 */ "Transaction",
20793      /*  35 */ "ReadCookie",
20794      /*  36 */ "SetCookie",
20795      /*  37 */ "VerifyCookie",
20796      /*  38 */ "OpenRead",
20797      /*  39 */ "OpenWrite",
20798      /*  40 */ "OpenAutoindex",
20799      /*  41 */ "OpenEphemeral",
20800      /*  42 */ "OpenPseudo",
20801      /*  43 */ "Close",
20802      /*  44 */ "SeekLt",
20803      /*  45 */ "SeekLe",
20804      /*  46 */ "SeekGe",
20805      /*  47 */ "SeekGt",
20806      /*  48 */ "Seek",
20807      /*  49 */ "NotFound",
20808      /*  50 */ "Found",
20809      /*  51 */ "IsUnique",
20810      /*  52 */ "NotExists",
20811      /*  53 */ "Sequence",
20812      /*  54 */ "NewRowid",
20813      /*  55 */ "Insert",
20814      /*  56 */ "InsertInt",
20815      /*  57 */ "Delete",
20816      /*  58 */ "ResetCount",
20817      /*  59 */ "RowKey",
20818      /*  60 */ "RowData",
20819      /*  61 */ "Rowid",
20820      /*  62 */ "NullRow",
20821      /*  63 */ "Last",
20822      /*  64 */ "Sort",
20823      /*  65 */ "Rewind",
20824      /*  66 */ "Prev",
20825      /*  67 */ "Next",
20826      /*  68 */ "Or",
20827      /*  69 */ "And",
20828      /*  70 */ "IdxInsert",
20829      /*  71 */ "IdxDelete",
20830      /*  72 */ "IdxRowid",
20831      /*  73 */ "IsNull",
20832      /*  74 */ "NotNull",
20833      /*  75 */ "Ne",
20834      /*  76 */ "Eq",
20835      /*  77 */ "Gt",
20836      /*  78 */ "Le",
20837      /*  79 */ "Lt",
20838      /*  80 */ "Ge",
20839      /*  81 */ "IdxLT",
20840      /*  82 */ "BitAnd",
20841      /*  83 */ "BitOr",
20842      /*  84 */ "ShiftLeft",
20843      /*  85 */ "ShiftRight",
20844      /*  86 */ "Add",
20845      /*  87 */ "Subtract",
20846      /*  88 */ "Multiply",
20847      /*  89 */ "Divide",
20848      /*  90 */ "Remainder",
20849      /*  91 */ "Concat",
20850      /*  92 */ "IdxGE",
20851      /*  93 */ "BitNot",
20852      /*  94 */ "String8",
20853      /*  95 */ "Destroy",
20854      /*  96 */ "Clear",
20855      /*  97 */ "CreateIndex",
20856      /*  98 */ "CreateTable",
20857      /*  99 */ "ParseSchema",
20858      /* 100 */ "LoadAnalysis",
20859      /* 101 */ "DropTable",
20860      /* 102 */ "DropIndex",
20861      /* 103 */ "DropTrigger",
20862      /* 104 */ "IntegrityCk",
20863      /* 105 */ "RowSetAdd",
20864      /* 106 */ "RowSetRead",
20865      /* 107 */ "RowSetTest",
20866      /* 108 */ "Program",
20867      /* 109 */ "Param",
20868      /* 110 */ "FkCounter",
20869      /* 111 */ "FkIfZero",
20870      /* 112 */ "MemMax",
20871      /* 113 */ "IfPos",
20872      /* 114 */ "IfNeg",
20873      /* 115 */ "IfZero",
20874      /* 116 */ "AggStep",
20875      /* 117 */ "AggFinal",
20876      /* 118 */ "Checkpoint",
20877      /* 119 */ "JournalMode",
20878      /* 120 */ "Vacuum",
20879      /* 121 */ "IncrVacuum",
20880      /* 122 */ "Expire",
20881      /* 123 */ "TableLock",
20882      /* 124 */ "VBegin",
20883      /* 125 */ "VCreate",
20884      /* 126 */ "VDestroy",
20885      /* 127 */ "VOpen",
20886      /* 128 */ "VFilter",
20887      /* 129 */ "VColumn",
20888      /* 130 */ "Real",
20889      /* 131 */ "VNext",
20890      /* 132 */ "VRename",
20891      /* 133 */ "VUpdate",
20892      /* 134 */ "Pagecount",
20893      /* 135 */ "Trace",
20894      /* 136 */ "Noop",
20895      /* 137 */ "Explain",
20896      /* 138 */ "NotUsed_138",
20897      /* 139 */ "NotUsed_139",
20898      /* 140 */ "NotUsed_140",
20899      /* 141 */ "ToText",
20900      /* 142 */ "ToBlob",
20901      /* 143 */ "ToNumeric",
20902      /* 144 */ "ToInt",
20903      /* 145 */ "ToReal",
20904   };
20905   return azName[i];
20906 }
20907 #endif
20908
20909 /************** End of opcodes.c *********************************************/
20910 /************** Begin file os_os2.c ******************************************/
20911 /*
20912 ** 2006 Feb 14
20913 **
20914 ** The author disclaims copyright to this source code.  In place of
20915 ** a legal notice, here is a blessing:
20916 **
20917 **    May you do good and not evil.
20918 **    May you find forgiveness for yourself and forgive others.
20919 **    May you share freely, never taking more than you give.
20920 **
20921 ******************************************************************************
20922 **
20923 ** This file contains code that is specific to OS/2.
20924 */
20925
20926
20927 #if SQLITE_OS_OS2
20928
20929 /*
20930 ** A Note About Memory Allocation:
20931 **
20932 ** This driver uses malloc()/free() directly rather than going through
20933 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20934 ** are designed for use on embedded systems where memory is scarce and
20935 ** malloc failures happen frequently.  OS/2 does not typically run on
20936 ** embedded systems, and when it does the developers normally have bigger
20937 ** problems to worry about than running out of memory.  So there is not
20938 ** a compelling need to use the wrappers.
20939 **
20940 ** But there is a good reason to not use the wrappers.  If we use the
20941 ** wrappers then we will get simulated malloc() failures within this
20942 ** driver.  And that causes all kinds of problems for our tests.  We
20943 ** could enhance SQLite to deal with simulated malloc failures within
20944 ** the OS driver, but the code to deal with those failure would not
20945 ** be exercised on Linux (which does not need to malloc() in the driver)
20946 ** and so we would have difficulty writing coverage tests for that
20947 ** code.  Better to leave the code out, we think.
20948 **
20949 ** The point of this discussion is as follows:  When creating a new
20950 ** OS layer for an embedded system, if you use this file as an example,
20951 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20952 ** desktops but not so well in embedded systems.
20953 */
20954
20955 /*
20956 ** Macros used to determine whether or not to use threads.
20957 */
20958 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20959 # define SQLITE_OS2_THREADS 1
20960 #endif
20961
20962 /*
20963 ** Include code that is common to all os_*.c files
20964 */
20965 /************** Include os_common.h in the middle of os_os2.c ****************/
20966 /************** Begin file os_common.h ***************************************/
20967 /*
20968 ** 2004 May 22
20969 **
20970 ** The author disclaims copyright to this source code.  In place of
20971 ** a legal notice, here is a blessing:
20972 **
20973 **    May you do good and not evil.
20974 **    May you find forgiveness for yourself and forgive others.
20975 **    May you share freely, never taking more than you give.
20976 **
20977 ******************************************************************************
20978 **
20979 ** This file contains macros and a little bit of code that is common to
20980 ** all of the platform-specific files (os_*.c) and is #included into those
20981 ** files.
20982 **
20983 ** This file should be #included by the os_*.c files only.  It is not a
20984 ** general purpose header file.
20985 */
20986 #ifndef _OS_COMMON_H_
20987 #define _OS_COMMON_H_
20988
20989 /*
20990 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20991 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20992 ** switch.  The following code should catch this problem at compile-time.
20993 */
20994 #ifdef MEMORY_DEBUG
20995 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20996 #endif
20997
20998 #ifdef SQLITE_DEBUG
20999 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21000 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21001 #else
21002 #define OSTRACE(X)
21003 #endif
21004
21005 /*
21006 ** Macros for performance tracing.  Normally turned off.  Only works
21007 ** on i486 hardware.
21008 */
21009 #ifdef SQLITE_PERFORMANCE_TRACE
21010
21011 /* 
21012 ** hwtime.h contains inline assembler code for implementing 
21013 ** high-performance timing routines.
21014 */
21015 /************** Include hwtime.h in the middle of os_common.h ****************/
21016 /************** Begin file hwtime.h ******************************************/
21017 /*
21018 ** 2008 May 27
21019 **
21020 ** The author disclaims copyright to this source code.  In place of
21021 ** a legal notice, here is a blessing:
21022 **
21023 **    May you do good and not evil.
21024 **    May you find forgiveness for yourself and forgive others.
21025 **    May you share freely, never taking more than you give.
21026 **
21027 ******************************************************************************
21028 **
21029 ** This file contains inline asm code for retrieving "high-performance"
21030 ** counters for x86 class CPUs.
21031 */
21032 #ifndef _HWTIME_H_
21033 #define _HWTIME_H_
21034
21035 /*
21036 ** The following routine only works on pentium-class (or newer) processors.
21037 ** It uses the RDTSC opcode to read the cycle count value out of the
21038 ** processor and returns that value.  This can be used for high-res
21039 ** profiling.
21040 */
21041 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21042       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21043
21044   #if defined(__GNUC__)
21045
21046   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21047      unsigned int lo, hi;
21048      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21049      return (sqlite_uint64)hi << 32 | lo;
21050   }
21051
21052   #elif defined(_MSC_VER)
21053
21054   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21055      __asm {
21056         rdtsc
21057         ret       ; return value at EDX:EAX
21058      }
21059   }
21060
21061   #endif
21062
21063 #elif (defined(__GNUC__) && defined(__x86_64__))
21064
21065   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21066       unsigned long val;
21067       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21068       return val;
21069   }
21070  
21071 #elif (defined(__GNUC__) && defined(__ppc__))
21072
21073   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21074       unsigned long long retval;
21075       unsigned long junk;
21076       __asm__ __volatile__ ("\n\
21077           1:      mftbu   %1\n\
21078                   mftb    %L0\n\
21079                   mftbu   %0\n\
21080                   cmpw    %0,%1\n\
21081                   bne     1b"
21082                   : "=r" (retval), "=r" (junk));
21083       return retval;
21084   }
21085
21086 #else
21087
21088   #error Need implementation of sqlite3Hwtime() for your platform.
21089
21090   /*
21091   ** To compile without implementing sqlite3Hwtime() for your platform,
21092   ** you can remove the above #error and use the following
21093   ** stub function.  You will lose timing support for many
21094   ** of the debugging and testing utilities, but it should at
21095   ** least compile and run.
21096   */
21097 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21098
21099 #endif
21100
21101 #endif /* !defined(_HWTIME_H_) */
21102
21103 /************** End of hwtime.h **********************************************/
21104 /************** Continuing where we left off in os_common.h ******************/
21105
21106 static sqlite_uint64 g_start;
21107 static sqlite_uint64 g_elapsed;
21108 #define TIMER_START       g_start=sqlite3Hwtime()
21109 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21110 #define TIMER_ELAPSED     g_elapsed
21111 #else
21112 #define TIMER_START
21113 #define TIMER_END
21114 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21115 #endif
21116
21117 /*
21118 ** If we compile with the SQLITE_TEST macro set, then the following block
21119 ** of code will give us the ability to simulate a disk I/O error.  This
21120 ** is used for testing the I/O recovery logic.
21121 */
21122 #ifdef SQLITE_TEST
21123 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21124 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21125 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21126 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21127 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21128 SQLITE_API int sqlite3_diskfull_pending = 0;
21129 SQLITE_API int sqlite3_diskfull = 0;
21130 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21131 #define SimulateIOError(CODE)  \
21132   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21133        || sqlite3_io_error_pending-- == 1 )  \
21134               { local_ioerr(); CODE; }
21135 static void local_ioerr(){
21136   IOTRACE(("IOERR\n"));
21137   sqlite3_io_error_hit++;
21138   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21139 }
21140 #define SimulateDiskfullError(CODE) \
21141    if( sqlite3_diskfull_pending ){ \
21142      if( sqlite3_diskfull_pending == 1 ){ \
21143        local_ioerr(); \
21144        sqlite3_diskfull = 1; \
21145        sqlite3_io_error_hit = 1; \
21146        CODE; \
21147      }else{ \
21148        sqlite3_diskfull_pending--; \
21149      } \
21150    }
21151 #else
21152 #define SimulateIOErrorBenign(X)
21153 #define SimulateIOError(A)
21154 #define SimulateDiskfullError(A)
21155 #endif
21156
21157 /*
21158 ** When testing, keep a count of the number of open files.
21159 */
21160 #ifdef SQLITE_TEST
21161 SQLITE_API int sqlite3_open_file_count = 0;
21162 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21163 #else
21164 #define OpenCounter(X)
21165 #endif
21166
21167 #endif /* !defined(_OS_COMMON_H_) */
21168
21169 /************** End of os_common.h *******************************************/
21170 /************** Continuing where we left off in os_os2.c *********************/
21171
21172 /*
21173 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
21174 ** protability layer.
21175 */
21176 typedef struct os2File os2File;
21177 struct os2File {
21178   const sqlite3_io_methods *pMethod;  /* Always the first entry */
21179   HFILE h;                  /* Handle for accessing the file */
21180   char* pathToDel;          /* Name of file to delete on close, NULL if not */
21181   unsigned char locktype;   /* Type of lock currently held on this file */
21182 };
21183
21184 #define LOCK_TIMEOUT 10L /* the default locking timeout */
21185
21186 /*****************************************************************************
21187 ** The next group of routines implement the I/O methods specified
21188 ** by the sqlite3_io_methods object.
21189 ******************************************************************************/
21190
21191 /*
21192 ** Close a file.
21193 */
21194 static int os2Close( sqlite3_file *id ){
21195   APIRET rc = NO_ERROR;
21196   os2File *pFile;
21197   if( id && (pFile = (os2File*)id) != 0 ){
21198     OSTRACE(( "CLOSE %d\n", pFile->h ));
21199     rc = DosClose( pFile->h );
21200     pFile->locktype = NO_LOCK;
21201     if( pFile->pathToDel != NULL ){
21202       rc = DosForceDelete( (PSZ)pFile->pathToDel );
21203       free( pFile->pathToDel );
21204       pFile->pathToDel = NULL;
21205     }
21206     id = 0;
21207     OpenCounter( -1 );
21208   }
21209
21210   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21211 }
21212
21213 /*
21214 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21215 ** bytes were read successfully and SQLITE_IOERR if anything goes
21216 ** wrong.
21217 */
21218 static int os2Read(
21219   sqlite3_file *id,               /* File to read from */
21220   void *pBuf,                     /* Write content into this buffer */
21221   int amt,                        /* Number of bytes to read */
21222   sqlite3_int64 offset            /* Begin reading at this offset */
21223 ){
21224   ULONG fileLocation = 0L;
21225   ULONG got;
21226   os2File *pFile = (os2File*)id;
21227   assert( id!=0 );
21228   SimulateIOError( return SQLITE_IOERR_READ );
21229   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21230   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21231     return SQLITE_IOERR;
21232   }
21233   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21234     return SQLITE_IOERR_READ;
21235   }
21236   if( got == (ULONG)amt )
21237     return SQLITE_OK;
21238   else {
21239     /* Unread portions of the input buffer must be zero-filled */
21240     memset(&((char*)pBuf)[got], 0, amt-got);
21241     return SQLITE_IOERR_SHORT_READ;
21242   }
21243 }
21244
21245 /*
21246 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21247 ** or some other error code on failure.
21248 */
21249 static int os2Write(
21250   sqlite3_file *id,               /* File to write into */
21251   const void *pBuf,               /* The bytes to be written */
21252   int amt,                        /* Number of bytes to write */
21253   sqlite3_int64 offset            /* Offset into the file to begin writing at */
21254 ){
21255   ULONG fileLocation = 0L;
21256   APIRET rc = NO_ERROR;
21257   ULONG wrote;
21258   os2File *pFile = (os2File*)id;
21259   assert( id!=0 );
21260   SimulateIOError( return SQLITE_IOERR_WRITE );
21261   SimulateDiskfullError( return SQLITE_FULL );
21262   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21263   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21264     return SQLITE_IOERR;
21265   }
21266   assert( amt>0 );
21267   while( amt > 0 &&
21268          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21269          wrote > 0
21270   ){
21271     amt -= wrote;
21272     pBuf = &((char*)pBuf)[wrote];
21273   }
21274
21275   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21276 }
21277
21278 /*
21279 ** Truncate an open file to a specified size
21280 */
21281 static int os2Truncate( sqlite3_file *id, i64 nByte ){
21282   APIRET rc = NO_ERROR;
21283   os2File *pFile = (os2File*)id;
21284   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21285   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21286   rc = DosSetFileSize( pFile->h, nByte );
21287   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21288 }
21289
21290 #ifdef SQLITE_TEST
21291 /*
21292 ** Count the number of fullsyncs and normal syncs.  This is used to test
21293 ** that syncs and fullsyncs are occuring at the right times.
21294 */
21295 SQLITE_API int sqlite3_sync_count = 0;
21296 SQLITE_API int sqlite3_fullsync_count = 0;
21297 #endif
21298
21299 /*
21300 ** Make sure all writes to a particular file are committed to disk.
21301 */
21302 static int os2Sync( sqlite3_file *id, int flags ){
21303   os2File *pFile = (os2File*)id;
21304   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21305 #ifdef SQLITE_TEST
21306   if( flags & SQLITE_SYNC_FULL){
21307     sqlite3_fullsync_count++;
21308   }
21309   sqlite3_sync_count++;
21310 #endif
21311   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21312   ** no-op
21313   */
21314 #ifdef SQLITE_NO_SYNC
21315   UNUSED_PARAMETER(pFile);
21316   return SQLITE_OK;
21317 #else
21318   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21319 #endif
21320 }
21321
21322 /*
21323 ** Determine the current size of a file in bytes
21324 */
21325 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21326   APIRET rc = NO_ERROR;
21327   FILESTATUS3 fsts3FileInfo;
21328   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21329   assert( id!=0 );
21330   SimulateIOError( return SQLITE_IOERR_FSTAT );
21331   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21332   if( rc == NO_ERROR ){
21333     *pSize = fsts3FileInfo.cbFile;
21334     return SQLITE_OK;
21335   }else{
21336     return SQLITE_IOERR_FSTAT;
21337   }
21338 }
21339
21340 /*
21341 ** Acquire a reader lock.
21342 */
21343 static int getReadLock( os2File *pFile ){
21344   FILELOCK  LockArea,
21345             UnlockArea;
21346   APIRET res;
21347   memset(&LockArea, 0, sizeof(LockArea));
21348   memset(&UnlockArea, 0, sizeof(UnlockArea));
21349   LockArea.lOffset = SHARED_FIRST;
21350   LockArea.lRange = SHARED_SIZE;
21351   UnlockArea.lOffset = 0L;
21352   UnlockArea.lRange = 0L;
21353   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21354   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21355   return res;
21356 }
21357
21358 /*
21359 ** Undo a readlock
21360 */
21361 static int unlockReadLock( os2File *id ){
21362   FILELOCK  LockArea,
21363             UnlockArea;
21364   APIRET res;
21365   memset(&LockArea, 0, sizeof(LockArea));
21366   memset(&UnlockArea, 0, sizeof(UnlockArea));
21367   LockArea.lOffset = 0L;
21368   LockArea.lRange = 0L;
21369   UnlockArea.lOffset = SHARED_FIRST;
21370   UnlockArea.lRange = SHARED_SIZE;
21371   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21372   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21373   return res;
21374 }
21375
21376 /*
21377 ** Lock the file with the lock specified by parameter locktype - one
21378 ** of the following:
21379 **
21380 **     (1) SHARED_LOCK
21381 **     (2) RESERVED_LOCK
21382 **     (3) PENDING_LOCK
21383 **     (4) EXCLUSIVE_LOCK
21384 **
21385 ** Sometimes when requesting one lock state, additional lock states
21386 ** are inserted in between.  The locking might fail on one of the later
21387 ** transitions leaving the lock state different from what it started but
21388 ** still short of its goal.  The following chart shows the allowed
21389 ** transitions and the inserted intermediate states:
21390 **
21391 **    UNLOCKED -> SHARED
21392 **    SHARED -> RESERVED
21393 **    SHARED -> (PENDING) -> EXCLUSIVE
21394 **    RESERVED -> (PENDING) -> EXCLUSIVE
21395 **    PENDING -> EXCLUSIVE
21396 **
21397 ** This routine will only increase a lock.  The os2Unlock() routine
21398 ** erases all locks at once and returns us immediately to locking level 0.
21399 ** It is not possible to lower the locking level one step at a time.  You
21400 ** must go straight to locking level 0.
21401 */
21402 static int os2Lock( sqlite3_file *id, int locktype ){
21403   int rc = SQLITE_OK;       /* Return code from subroutines */
21404   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21405   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21406   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21407   FILELOCK  LockArea,
21408             UnlockArea;
21409   os2File *pFile = (os2File*)id;
21410   memset(&LockArea, 0, sizeof(LockArea));
21411   memset(&UnlockArea, 0, sizeof(UnlockArea));
21412   assert( pFile!=0 );
21413   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21414
21415   /* If there is already a lock of this type or more restrictive on the
21416   ** os2File, do nothing. Don't use the end_lock: exit path, as
21417   ** sqlite3_mutex_enter() hasn't been called yet.
21418   */
21419   if( pFile->locktype>=locktype ){
21420     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21421     return SQLITE_OK;
21422   }
21423
21424   /* Make sure the locking sequence is correct
21425   */
21426   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21427   assert( locktype!=PENDING_LOCK );
21428   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21429
21430   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21431   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21432   ** the PENDING_LOCK byte is temporary.
21433   */
21434   newLocktype = pFile->locktype;
21435   if( pFile->locktype==NO_LOCK
21436       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21437   ){
21438     LockArea.lOffset = PENDING_BYTE;
21439     LockArea.lRange = 1L;
21440     UnlockArea.lOffset = 0L;
21441     UnlockArea.lRange = 0L;
21442
21443     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21444     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21445     if( res == NO_ERROR ){
21446       gotPendingLock = 1;
21447       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21448     }
21449   }
21450
21451   /* Acquire a shared lock
21452   */
21453   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21454     assert( pFile->locktype==NO_LOCK );
21455     res = getReadLock(pFile);
21456     if( res == NO_ERROR ){
21457       newLocktype = SHARED_LOCK;
21458     }
21459     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21460   }
21461
21462   /* Acquire a RESERVED lock
21463   */
21464   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21465     assert( pFile->locktype==SHARED_LOCK );
21466     LockArea.lOffset = RESERVED_BYTE;
21467     LockArea.lRange = 1L;
21468     UnlockArea.lOffset = 0L;
21469     UnlockArea.lRange = 0L;
21470     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21471     if( res == NO_ERROR ){
21472       newLocktype = RESERVED_LOCK;
21473     }
21474     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21475   }
21476
21477   /* Acquire a PENDING lock
21478   */
21479   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21480     newLocktype = PENDING_LOCK;
21481     gotPendingLock = 0;
21482     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21483                pFile->h ));
21484   }
21485
21486   /* Acquire an EXCLUSIVE lock
21487   */
21488   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21489     assert( pFile->locktype>=SHARED_LOCK );
21490     res = unlockReadLock(pFile);
21491     OSTRACE(( "unreadlock = %d\n", res ));
21492     LockArea.lOffset = SHARED_FIRST;
21493     LockArea.lRange = SHARED_SIZE;
21494     UnlockArea.lOffset = 0L;
21495     UnlockArea.lRange = 0L;
21496     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21497     if( res == NO_ERROR ){
21498       newLocktype = EXCLUSIVE_LOCK;
21499     }else{
21500       OSTRACE(( "OS/2 error-code = %d\n", res ));
21501       getReadLock(pFile);
21502     }
21503     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21504   }
21505
21506   /* If we are holding a PENDING lock that ought to be released, then
21507   ** release it now.
21508   */
21509   if( gotPendingLock && locktype==SHARED_LOCK ){
21510     int r;
21511     LockArea.lOffset = 0L;
21512     LockArea.lRange = 0L;
21513     UnlockArea.lOffset = PENDING_BYTE;
21514     UnlockArea.lRange = 1L;
21515     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21516     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21517   }
21518
21519   /* Update the state of the lock has held in the file descriptor then
21520   ** return the appropriate result code.
21521   */
21522   if( res == NO_ERROR ){
21523     rc = SQLITE_OK;
21524   }else{
21525     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21526               locktype, newLocktype ));
21527     rc = SQLITE_BUSY;
21528   }
21529   pFile->locktype = newLocktype;
21530   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21531   return rc;
21532 }
21533
21534 /*
21535 ** This routine checks if there is a RESERVED lock held on the specified
21536 ** file by this or any other process. If such a lock is held, return
21537 ** non-zero, otherwise zero.
21538 */
21539 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21540   int r = 0;
21541   os2File *pFile = (os2File*)id;
21542   assert( pFile!=0 );
21543   if( pFile->locktype>=RESERVED_LOCK ){
21544     r = 1;
21545     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21546   }else{
21547     FILELOCK  LockArea,
21548               UnlockArea;
21549     APIRET rc = NO_ERROR;
21550     memset(&LockArea, 0, sizeof(LockArea));
21551     memset(&UnlockArea, 0, sizeof(UnlockArea));
21552     LockArea.lOffset = RESERVED_BYTE;
21553     LockArea.lRange = 1L;
21554     UnlockArea.lOffset = 0L;
21555     UnlockArea.lRange = 0L;
21556     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21557     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21558     if( rc == NO_ERROR ){
21559       APIRET rcu = NO_ERROR; /* return code for unlocking */
21560       LockArea.lOffset = 0L;
21561       LockArea.lRange = 0L;
21562       UnlockArea.lOffset = RESERVED_BYTE;
21563       UnlockArea.lRange = 1L;
21564       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21565       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
21566     }
21567     r = !(rc == NO_ERROR);
21568     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
21569   }
21570   *pOut = r;
21571   return SQLITE_OK;
21572 }
21573
21574 /*
21575 ** Lower the locking level on file descriptor id to locktype.  locktype
21576 ** must be either NO_LOCK or SHARED_LOCK.
21577 **
21578 ** If the locking level of the file descriptor is already at or below
21579 ** the requested locking level, this routine is a no-op.
21580 **
21581 ** It is not possible for this routine to fail if the second argument
21582 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21583 ** might return SQLITE_IOERR;
21584 */
21585 static int os2Unlock( sqlite3_file *id, int locktype ){
21586   int type;
21587   os2File *pFile = (os2File*)id;
21588   APIRET rc = SQLITE_OK;
21589   APIRET res = NO_ERROR;
21590   FILELOCK  LockArea,
21591             UnlockArea;
21592   memset(&LockArea, 0, sizeof(LockArea));
21593   memset(&UnlockArea, 0, sizeof(UnlockArea));
21594   assert( pFile!=0 );
21595   assert( locktype<=SHARED_LOCK );
21596   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
21597   type = pFile->locktype;
21598   if( type>=EXCLUSIVE_LOCK ){
21599     LockArea.lOffset = 0L;
21600     LockArea.lRange = 0L;
21601     UnlockArea.lOffset = SHARED_FIRST;
21602     UnlockArea.lRange = SHARED_SIZE;
21603     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21604     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
21605     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21606       /* This should never happen.  We should always be able to
21607       ** reacquire the read lock */
21608       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
21609       rc = SQLITE_IOERR_UNLOCK;
21610     }
21611   }
21612   if( type>=RESERVED_LOCK ){
21613     LockArea.lOffset = 0L;
21614     LockArea.lRange = 0L;
21615     UnlockArea.lOffset = RESERVED_BYTE;
21616     UnlockArea.lRange = 1L;
21617     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21618     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
21619   }
21620   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21621     res = unlockReadLock(pFile);
21622     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
21623               pFile->h, type, locktype, res ));
21624   }
21625   if( type>=PENDING_LOCK ){
21626     LockArea.lOffset = 0L;
21627     LockArea.lRange = 0L;
21628     UnlockArea.lOffset = PENDING_BYTE;
21629     UnlockArea.lRange = 1L;
21630     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21631     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
21632   }
21633   pFile->locktype = locktype;
21634   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
21635   return rc;
21636 }
21637
21638 /*
21639 ** Control and query of the open file handle.
21640 */
21641 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21642   switch( op ){
21643     case SQLITE_FCNTL_LOCKSTATE: {
21644       *(int*)pArg = ((os2File*)id)->locktype;
21645       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
21646                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
21647       return SQLITE_OK;
21648     }
21649   }
21650   return SQLITE_ERROR;
21651 }
21652
21653 /*
21654 ** Return the sector size in bytes of the underlying block device for
21655 ** the specified file. This is almost always 512 bytes, but may be
21656 ** larger for some devices.
21657 **
21658 ** SQLite code assumes this function cannot fail. It also assumes that
21659 ** if two files are created in the same file-system directory (i.e.
21660 ** a database and its journal file) that the sector size will be the
21661 ** same for both.
21662 */
21663 static int os2SectorSize(sqlite3_file *id){
21664   return SQLITE_DEFAULT_SECTOR_SIZE;
21665 }
21666
21667 /*
21668 ** Return a vector of device characteristics.
21669 */
21670 static int os2DeviceCharacteristics(sqlite3_file *id){
21671   return 0;
21672 }
21673
21674
21675 /*
21676 ** Character set conversion objects used by conversion routines.
21677 */
21678 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21679 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21680
21681 /*
21682 ** Helper function to initialize the conversion objects from and to UTF-8.
21683 */
21684 static void initUconvObjects( void ){
21685   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21686     ucUtf8 = NULL;
21687   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21688     uclCp = NULL;
21689 }
21690
21691 /*
21692 ** Helper function to free the conversion objects from and to UTF-8.
21693 */
21694 static void freeUconvObjects( void ){
21695   if ( ucUtf8 )
21696     UniFreeUconvObject( ucUtf8 );
21697   if ( uclCp )
21698     UniFreeUconvObject( uclCp );
21699   ucUtf8 = NULL;
21700   uclCp = NULL;
21701 }
21702
21703 /*
21704 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21705 ** The two-step process: first convert the incoming UTF-8 string
21706 ** into UCS-2 and then from UCS-2 to the current codepage.
21707 ** The returned char pointer has to be freed.
21708 */
21709 static char *convertUtf8PathToCp( const char *in ){
21710   UniChar tempPath[CCHMAXPATH];
21711   char *out = (char *)calloc( CCHMAXPATH, 1 );
21712
21713   if( !out )
21714     return NULL;
21715
21716   if( !ucUtf8 || !uclCp )
21717     initUconvObjects();
21718
21719   /* determine string for the conversion of UTF-8 which is CP1208 */
21720   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21721     return out; /* if conversion fails, return the empty string */
21722
21723   /* conversion for current codepage which can be used for paths */
21724   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21725
21726   return out;
21727 }
21728
21729 /*
21730 ** Helper function to convert filenames from local codepage to UTF-8.
21731 ** The two-step process: first convert the incoming codepage-specific
21732 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21733 ** The returned char pointer has to be freed.
21734 **
21735 ** This function is non-static to be able to use this in shell.c and
21736 ** similar applications that take command line arguments.
21737 */
21738 char *convertCpPathToUtf8( const char *in ){
21739   UniChar tempPath[CCHMAXPATH];
21740   char *out = (char *)calloc( CCHMAXPATH, 1 );
21741
21742   if( !out )
21743     return NULL;
21744
21745   if( !ucUtf8 || !uclCp )
21746     initUconvObjects();
21747
21748   /* conversion for current codepage which can be used for paths */
21749   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21750     return out; /* if conversion fails, return the empty string */
21751
21752   /* determine string for the conversion of UTF-8 which is CP1208 */
21753   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21754
21755   return out;
21756 }
21757
21758 /*
21759 ** This vector defines all the methods that can operate on an
21760 ** sqlite3_file for os2.
21761 */
21762 static const sqlite3_io_methods os2IoMethod = {
21763   1,                        /* iVersion */
21764   os2Close,
21765   os2Read,
21766   os2Write,
21767   os2Truncate,
21768   os2Sync,
21769   os2FileSize,
21770   os2Lock,
21771   os2Unlock,
21772   os2CheckReservedLock,
21773   os2FileControl,
21774   os2SectorSize,
21775   os2DeviceCharacteristics
21776 };
21777
21778 /***************************************************************************
21779 ** Here ends the I/O methods that form the sqlite3_io_methods object.
21780 **
21781 ** The next block of code implements the VFS methods.
21782 ****************************************************************************/
21783
21784 /*
21785 ** Create a temporary file name in zBuf.  zBuf must be big enough to
21786 ** hold at pVfs->mxPathname characters.
21787 */
21788 static int getTempname(int nBuf, char *zBuf ){
21789   static const unsigned char zChars[] =
21790     "abcdefghijklmnopqrstuvwxyz"
21791     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21792     "0123456789";
21793   int i, j;
21794   char zTempPathBuf[3];
21795   PSZ zTempPath = (PSZ)&zTempPathBuf;
21796   if( sqlite3_temp_directory ){
21797     zTempPath = sqlite3_temp_directory;
21798   }else{
21799     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21800       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21801         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21802            ULONG ulDriveNum = 0, ulDriveMap = 0;
21803            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21804            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21805         }
21806       }
21807     }
21808   }
21809   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21810    * multiple (back)slashes which causes DosOpen() to fail.              *
21811    * Trailing spaces are not allowed, either.                            */
21812   j = sqlite3Strlen30(zTempPath);
21813   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21814                     || zTempPath[j-1] == ' ' ) ){
21815     j--;
21816   }
21817   zTempPath[j] = '\0';
21818   if( !sqlite3_temp_directory ){
21819     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21820     sqlite3_snprintf( nBuf-30, zBuf,
21821                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21822     free( zTempPathUTF );
21823   }else{
21824     sqlite3_snprintf( nBuf-30, zBuf,
21825                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21826   }
21827   j = sqlite3Strlen30( zBuf );
21828   sqlite3_randomness( 20, &zBuf[j] );
21829   for( i = 0; i < 20; i++, j++ ){
21830     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21831   }
21832   zBuf[j] = 0;
21833   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
21834   return SQLITE_OK;
21835 }
21836
21837
21838 /*
21839 ** Turn a relative pathname into a full pathname.  Write the full
21840 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21841 ** bytes in size.
21842 */
21843 static int os2FullPathname(
21844   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21845   const char *zRelative,      /* Possibly relative input path */
21846   int nFull,                  /* Size of output buffer in bytes */
21847   char *zFull                 /* Output buffer */
21848 ){
21849   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21850   char zFullCp[CCHMAXPATH] = "\0";
21851   char *zFullUTF;
21852   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21853                                 CCHMAXPATH );
21854   free( zRelativeCp );
21855   zFullUTF = convertCpPathToUtf8( zFullCp );
21856   sqlite3_snprintf( nFull, zFull, zFullUTF );
21857   free( zFullUTF );
21858   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21859 }
21860
21861
21862 /*
21863 ** Open a file.
21864 */
21865 static int os2Open(
21866   sqlite3_vfs *pVfs,            /* Not used */
21867   const char *zName,            /* Name of the file */
21868   sqlite3_file *id,             /* Write the SQLite file handle here */
21869   int flags,                    /* Open mode flags */
21870   int *pOutFlags                /* Status return flags */
21871 ){
21872   HFILE h;
21873   ULONG ulFileAttribute = FILE_NORMAL;
21874   ULONG ulOpenFlags = 0;
21875   ULONG ulOpenMode = 0;
21876   os2File *pFile = (os2File*)id;
21877   APIRET rc = NO_ERROR;
21878   ULONG ulAction;
21879   char *zNameCp;
21880   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21881
21882   /* If the second argument to this function is NULL, generate a 
21883   ** temporary file name to use 
21884   */
21885   if( !zName ){
21886     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21887     if( rc!=SQLITE_OK ){
21888       return rc;
21889     }
21890     zName = zTmpname;
21891   }
21892
21893
21894   memset( pFile, 0, sizeof(*pFile) );
21895
21896   OSTRACE(( "OPEN want %d\n", flags ));
21897
21898   if( flags & SQLITE_OPEN_READWRITE ){
21899     ulOpenMode |= OPEN_ACCESS_READWRITE;
21900     OSTRACE(( "OPEN read/write\n" ));
21901   }else{
21902     ulOpenMode |= OPEN_ACCESS_READONLY;
21903     OSTRACE(( "OPEN read only\n" ));
21904   }
21905
21906   if( flags & SQLITE_OPEN_CREATE ){
21907     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21908     OSTRACE(( "OPEN open new/create\n" ));
21909   }else{
21910     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21911     OSTRACE(( "OPEN open existing\n" ));
21912   }
21913
21914   if( flags & SQLITE_OPEN_MAIN_DB ){
21915     ulOpenMode |= OPEN_SHARE_DENYNONE;
21916     OSTRACE(( "OPEN share read/write\n" ));
21917   }else{
21918     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21919     OSTRACE(( "OPEN share read only\n" ));
21920   }
21921
21922   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21923     char pathUtf8[CCHMAXPATH];
21924 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21925     ulFileAttribute = FILE_HIDDEN;
21926 #endif
21927     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21928     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21929     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
21930   }else{
21931     pFile->pathToDel = NULL;
21932     OSTRACE(( "OPEN normal file attribute\n" ));
21933   }
21934
21935   /* always open in random access mode for possibly better speed */
21936   ulOpenMode |= OPEN_FLAGS_RANDOM;
21937   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21938   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21939
21940   zNameCp = convertUtf8PathToCp( zName );
21941   rc = DosOpen( (PSZ)zNameCp,
21942                 &h,
21943                 &ulAction,
21944                 0L,
21945                 ulFileAttribute,
21946                 ulOpenFlags,
21947                 ulOpenMode,
21948                 (PEAOP2)NULL );
21949   free( zNameCp );
21950   if( rc != NO_ERROR ){
21951     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21952               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
21953     if( pFile->pathToDel )
21954       free( pFile->pathToDel );
21955     pFile->pathToDel = NULL;
21956     if( flags & SQLITE_OPEN_READWRITE ){
21957       OSTRACE(( "OPEN %d Invalid handle\n",
21958                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
21959       return os2Open( pVfs, zName, id,
21960                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21961                       pOutFlags );
21962     }else{
21963       return SQLITE_CANTOPEN;
21964     }
21965   }
21966
21967   if( pOutFlags ){
21968     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21969   }
21970
21971   pFile->pMethod = &os2IoMethod;
21972   pFile->h = h;
21973   OpenCounter(+1);
21974   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
21975   return SQLITE_OK;
21976 }
21977
21978 /*
21979 ** Delete the named file.
21980 */
21981 static int os2Delete(
21982   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21983   const char *zFilename,                 /* Name of file to delete */
21984   int syncDir                            /* Not used on os2 */
21985 ){
21986   APIRET rc = NO_ERROR;
21987   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21988   SimulateIOError( return SQLITE_IOERR_DELETE );
21989   rc = DosDelete( (PSZ)zFilenameCp );
21990   free( zFilenameCp );
21991   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
21992   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21993 }
21994
21995 /*
21996 ** Check the existance and status of a file.
21997 */
21998 static int os2Access(
21999   sqlite3_vfs *pVfs,        /* Not used on os2 */
22000   const char *zFilename,    /* Name of file to check */
22001   int flags,                /* Type of test to make on this file */
22002   int *pOut                 /* Write results here */
22003 ){
22004   FILESTATUS3 fsts3ConfigInfo;
22005   APIRET rc = NO_ERROR;
22006   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22007
22008   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22009   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22010                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22011   free( zFilenameCp );
22012   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22013             fsts3ConfigInfo.attrFile, flags, rc ));
22014   switch( flags ){
22015     case SQLITE_ACCESS_READ:
22016     case SQLITE_ACCESS_EXISTS:
22017       rc = (rc == NO_ERROR);
22018       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22019       break;
22020     case SQLITE_ACCESS_READWRITE:
22021       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22022       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22023       break;
22024     default:
22025       assert( !"Invalid flags argument" );
22026   }
22027   *pOut = rc;
22028   return SQLITE_OK;
22029 }
22030
22031
22032 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22033 /*
22034 ** Interfaces for opening a shared library, finding entry points
22035 ** within the shared library, and closing the shared library.
22036 */
22037 /*
22038 ** Interfaces for opening a shared library, finding entry points
22039 ** within the shared library, and closing the shared library.
22040 */
22041 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22042   UCHAR loadErr[256];
22043   HMODULE hmod;
22044   APIRET rc;
22045   char *zFilenameCp = convertUtf8PathToCp(zFilename);
22046   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22047   free(zFilenameCp);
22048   return rc != NO_ERROR ? 0 : (void*)hmod;
22049 }
22050 /*
22051 ** A no-op since the error code is returned on the DosLoadModule call.
22052 ** os2Dlopen returns zero if DosLoadModule is not successful.
22053 */
22054 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22055 /* no-op */
22056 }
22057 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22058   PFN pfn;
22059   APIRET rc;
22060   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22061   if( rc != NO_ERROR ){
22062     /* if the symbol itself was not found, search again for the same
22063      * symbol with an extra underscore, that might be needed depending
22064      * on the calling convention */
22065     char _zSymbol[256] = "_";
22066     strncat(_zSymbol, zSymbol, 255);
22067     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22068   }
22069   return rc != NO_ERROR ? 0 : (void*)pfn;
22070 }
22071 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22072   DosFreeModule((HMODULE)pHandle);
22073 }
22074 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22075   #define os2DlOpen 0
22076   #define os2DlError 0
22077   #define os2DlSym 0
22078   #define os2DlClose 0
22079 #endif
22080
22081
22082 /*
22083 ** Write up to nBuf bytes of randomness into zBuf.
22084 */
22085 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22086   int n = 0;
22087 #if defined(SQLITE_TEST)
22088   n = nBuf;
22089   memset(zBuf, 0, nBuf);
22090 #else
22091   int sizeofULong = sizeof(ULONG);
22092   if( (int)sizeof(DATETIME) <= nBuf - n ){
22093     DATETIME x;
22094     DosGetDateTime(&x);
22095     memcpy(&zBuf[n], &x, sizeof(x));
22096     n += sizeof(x);
22097   }
22098
22099   if( sizeofULong <= nBuf - n ){
22100     PPIB ppib;
22101     DosGetInfoBlocks(NULL, &ppib);
22102     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22103     n += sizeofULong;
22104   }
22105
22106   if( sizeofULong <= nBuf - n ){
22107     PTIB ptib;
22108     DosGetInfoBlocks(&ptib, NULL);
22109     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22110     n += sizeofULong;
22111   }
22112
22113   /* if we still haven't filled the buffer yet the following will */
22114   /* grab everything once instead of making several calls for a single item */
22115   if( sizeofULong <= nBuf - n ){
22116     ULONG ulSysInfo[QSV_MAX];
22117     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22118
22119     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22120     n += sizeofULong;
22121
22122     if( sizeofULong <= nBuf - n ){
22123       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22124       n += sizeofULong;
22125     }
22126     if( sizeofULong <= nBuf - n ){
22127       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22128       n += sizeofULong;
22129     }
22130     if( sizeofULong <= nBuf - n ){
22131       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22132       n += sizeofULong;
22133     }
22134     if( sizeofULong <= nBuf - n ){
22135       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22136       n += sizeofULong;
22137     }
22138   }
22139 #endif
22140
22141   return n;
22142 }
22143
22144 /*
22145 ** Sleep for a little while.  Return the amount of time slept.
22146 ** The argument is the number of microseconds we want to sleep.
22147 ** The return value is the number of microseconds of sleep actually
22148 ** requested from the underlying operating system, a number which
22149 ** might be greater than or equal to the argument, but not less
22150 ** than the argument.
22151 */
22152 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22153   DosSleep( (microsec/1000) );
22154   return microsec;
22155 }
22156
22157 /*
22158 ** The following variable, if set to a non-zero value, becomes the result
22159 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22160 */
22161 #ifdef SQLITE_TEST
22162 SQLITE_API int sqlite3_current_time = 0;
22163 #endif
22164
22165 /*
22166 ** Find the current time (in Universal Coordinated Time).  Write the
22167 ** current time and date as a Julian Day number into *prNow and
22168 ** return 0.  Return 1 if the time and date cannot be found.
22169 */
22170 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22171   double now;
22172   SHORT minute; /* needs to be able to cope with negative timezone offset */
22173   USHORT second, hour,
22174          day, month, year;
22175   DATETIME dt;
22176   DosGetDateTime( &dt );
22177   second = (USHORT)dt.seconds;
22178   minute = (SHORT)dt.minutes + dt.timezone;
22179   hour = (USHORT)dt.hours;
22180   day = (USHORT)dt.day;
22181   month = (USHORT)dt.month;
22182   year = (USHORT)dt.year;
22183
22184   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22185      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22186   /* Calculate the Julian days */
22187   now = day - 32076 +
22188     1461*(year + 4800 + (month - 14)/12)/4 +
22189     367*(month - 2 - (month - 14)/12*12)/12 -
22190     3*((year + 4900 + (month - 14)/12)/100)/4;
22191
22192   /* Add the fractional hours, mins and seconds */
22193   now += (hour + 12.0)/24.0;
22194   now += minute/1440.0;
22195   now += second/86400.0;
22196   *prNow = now;
22197 #ifdef SQLITE_TEST
22198   if( sqlite3_current_time ){
22199     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22200   }
22201 #endif
22202   return 0;
22203 }
22204
22205 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22206   return 0;
22207 }
22208
22209 /*
22210 ** Initialize and deinitialize the operating system interface.
22211 */
22212 SQLITE_API int sqlite3_os_init(void){
22213   static sqlite3_vfs os2Vfs = {
22214     1,                 /* iVersion */
22215     sizeof(os2File),   /* szOsFile */
22216     CCHMAXPATH,        /* mxPathname */
22217     0,                 /* pNext */
22218     "os2",             /* zName */
22219     0,                 /* pAppData */
22220
22221     os2Open,           /* xOpen */
22222     os2Delete,         /* xDelete */
22223     os2Access,         /* xAccess */
22224     os2FullPathname,   /* xFullPathname */
22225     os2DlOpen,         /* xDlOpen */
22226     os2DlError,        /* xDlError */
22227     os2DlSym,          /* xDlSym */
22228     os2DlClose,        /* xDlClose */
22229     os2Randomness,     /* xRandomness */
22230     os2Sleep,          /* xSleep */
22231     os2CurrentTime,    /* xCurrentTime */
22232     os2GetLastError,   /* xGetLastError */
22233   };
22234   sqlite3_vfs_register(&os2Vfs, 1);
22235   initUconvObjects();
22236   return SQLITE_OK;
22237 }
22238 SQLITE_API int sqlite3_os_end(void){
22239   freeUconvObjects();
22240   return SQLITE_OK;
22241 }
22242
22243 #endif /* SQLITE_OS_OS2 */
22244
22245 /************** End of os_os2.c **********************************************/
22246 /************** Begin file os_unix.c *****************************************/
22247 /*
22248 ** 2004 May 22
22249 **
22250 ** The author disclaims copyright to this source code.  In place of
22251 ** a legal notice, here is a blessing:
22252 **
22253 **    May you do good and not evil.
22254 **    May you find forgiveness for yourself and forgive others.
22255 **    May you share freely, never taking more than you give.
22256 **
22257 ******************************************************************************
22258 **
22259 ** This file contains the VFS implementation for unix-like operating systems
22260 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22261 **
22262 ** There are actually several different VFS implementations in this file.
22263 ** The differences are in the way that file locking is done.  The default
22264 ** implementation uses Posix Advisory Locks.  Alternative implementations
22265 ** use flock(), dot-files, various proprietary locking schemas, or simply
22266 ** skip locking all together.
22267 **
22268 ** This source file is organized into divisions where the logic for various
22269 ** subfunctions is contained within the appropriate division.  PLEASE
22270 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22271 ** in the correct division and should be clearly labeled.
22272 **
22273 ** The layout of divisions is as follows:
22274 **
22275 **   *  General-purpose declarations and utility functions.
22276 **   *  Unique file ID logic used by VxWorks.
22277 **   *  Various locking primitive implementations (all except proxy locking):
22278 **      + for Posix Advisory Locks
22279 **      + for no-op locks
22280 **      + for dot-file locks
22281 **      + for flock() locking
22282 **      + for named semaphore locks (VxWorks only)
22283 **      + for AFP filesystem locks (MacOSX only)
22284 **   *  sqlite3_file methods not associated with locking.
22285 **   *  Definitions of sqlite3_io_methods objects for all locking
22286 **      methods plus "finder" functions for each locking method.
22287 **   *  sqlite3_vfs method implementations.
22288 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22289 **   *  Definitions of sqlite3_vfs objects for all locking methods
22290 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22291 */
22292 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22293
22294 /*
22295 ** There are various methods for file locking used for concurrency
22296 ** control:
22297 **
22298 **   1. POSIX locking (the default),
22299 **   2. No locking,
22300 **   3. Dot-file locking,
22301 **   4. flock() locking,
22302 **   5. AFP locking (OSX only),
22303 **   6. Named POSIX semaphores (VXWorks only),
22304 **   7. proxy locking. (OSX only)
22305 **
22306 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22307 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22308 ** selection of the appropriate locking style based on the filesystem
22309 ** where the database is located.  
22310 */
22311 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22312 #  if defined(__APPLE__)
22313 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22314 #  else
22315 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22316 #  endif
22317 #endif
22318
22319 /*
22320 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22321 ** vxworks, or 0 otherwise.
22322 */
22323 #ifndef OS_VXWORKS
22324 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22325 #    define OS_VXWORKS 1
22326 #  else
22327 #    define OS_VXWORKS 0
22328 #  endif
22329 #endif
22330
22331 /*
22332 ** These #defines should enable >2GB file support on Posix if the
22333 ** underlying operating system supports it.  If the OS lacks
22334 ** large file support, these should be no-ops.
22335 **
22336 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22337 ** on the compiler command line.  This is necessary if you are compiling
22338 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22339 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22340 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22341 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22342 ** portability you should omit LFS.
22343 **
22344 ** The previous paragraph was written in 2005.  (This paragraph is written
22345 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22346 ** you should probably leave LFS enabled.  But some embedded platforms might
22347 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22348 */
22349 #ifndef SQLITE_DISABLE_LFS
22350 # define _LARGE_FILE       1
22351 # ifndef _FILE_OFFSET_BITS
22352 #   define _FILE_OFFSET_BITS 64
22353 # endif
22354 # define _LARGEFILE_SOURCE 1
22355 #endif
22356
22357 /*
22358 ** standard include files.
22359 */
22360 #include <sys/types.h>
22361 #include <sys/stat.h>
22362 #include <fcntl.h>
22363 #include <unistd.h>
22364 #include <sys/time.h>
22365 #include <errno.h>
22366 #include <sys/mman.h>
22367
22368 #if SQLITE_ENABLE_LOCKING_STYLE
22369 # include <sys/ioctl.h>
22370 # if OS_VXWORKS
22371 #  include <semaphore.h>
22372 #  include <limits.h>
22373 # else
22374 #  include <sys/file.h>
22375 #  include <sys/param.h>
22376 # endif
22377 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22378
22379 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22380 # include <sys/mount.h>
22381 #endif
22382
22383 /*
22384 ** Allowed values of unixFile.fsFlags
22385 */
22386 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22387
22388 /*
22389 ** If we are to be thread-safe, include the pthreads header and define
22390 ** the SQLITE_UNIX_THREADS macro.
22391 */
22392 #if SQLITE_THREADSAFE
22393 # define SQLITE_UNIX_THREADS 1
22394 #endif
22395
22396 /*
22397 ** Default permissions when creating a new file
22398 */
22399 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22400 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22401 #endif
22402
22403 /*
22404  ** Default permissions when creating auto proxy dir
22405  */
22406 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22407 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22408 #endif
22409
22410 /*
22411 ** Maximum supported path-length.
22412 */
22413 #define MAX_PATHNAME 512
22414
22415 /*
22416 ** Only set the lastErrno if the error code is a real error and not 
22417 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22418 */
22419 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22420
22421 /* Forward references */
22422 typedef struct unixShm unixShm;               /* Connection shared memory */
22423 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22424 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22425 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22426
22427 /*
22428 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22429 ** cannot be closed immediately. In these cases, instances of the following
22430 ** structure are used to store the file descriptor while waiting for an
22431 ** opportunity to either close or reuse it.
22432 */
22433 struct UnixUnusedFd {
22434   int fd;                   /* File descriptor to close */
22435   int flags;                /* Flags this file descriptor was opened with */
22436   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22437 };
22438
22439 /*
22440 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22441 ** VFS implementations.
22442 */
22443 typedef struct unixFile unixFile;
22444 struct unixFile {
22445   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22446   unixInodeInfo *pInode;              /* Info about locks on this inode */
22447   int h;                              /* The file descriptor */
22448   int dirfd;                          /* File descriptor for the directory */
22449   unsigned char eFileLock;            /* The type of lock held on this fd */
22450   int lastErrno;                      /* The unix errno from last I/O error */
22451   void *lockingContext;               /* Locking style specific state */
22452   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22453   int fileFlags;                      /* Miscellanous flags */
22454   const char *zPath;                  /* Name of the file */
22455   unixShm *pShm;                      /* Shared memory segment information */
22456 #if SQLITE_ENABLE_LOCKING_STYLE
22457   int openFlags;                      /* The flags specified at open() */
22458 #endif
22459 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22460   unsigned fsFlags;                   /* cached details from statfs() */
22461 #endif
22462 #if OS_VXWORKS
22463   int isDelete;                       /* Delete on close if true */
22464   struct vxworksFileId *pId;          /* Unique file ID */
22465 #endif
22466 #ifndef NDEBUG
22467   /* The next group of variables are used to track whether or not the
22468   ** transaction counter in bytes 24-27 of database files are updated
22469   ** whenever any part of the database changes.  An assertion fault will
22470   ** occur if a file is updated without also updating the transaction
22471   ** counter.  This test is made to avoid new problems similar to the
22472   ** one described by ticket #3584. 
22473   */
22474   unsigned char transCntrChng;   /* True if the transaction counter changed */
22475   unsigned char dbUpdate;        /* True if any part of database file changed */
22476   unsigned char inNormalWrite;   /* True if in a normal write operation */
22477 #endif
22478 #ifdef SQLITE_TEST
22479   /* In test mode, increase the size of this structure a bit so that 
22480   ** it is larger than the struct CrashFile defined in test6.c.
22481   */
22482   char aPadding[32];
22483 #endif
22484 };
22485
22486 /*
22487 ** The following macros define bits in unixFile.fileFlags
22488 */
22489 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22490
22491 /*
22492 ** Include code that is common to all os_*.c files
22493 */
22494 /************** Include os_common.h in the middle of os_unix.c ***************/
22495 /************** Begin file os_common.h ***************************************/
22496 /*
22497 ** 2004 May 22
22498 **
22499 ** The author disclaims copyright to this source code.  In place of
22500 ** a legal notice, here is a blessing:
22501 **
22502 **    May you do good and not evil.
22503 **    May you find forgiveness for yourself and forgive others.
22504 **    May you share freely, never taking more than you give.
22505 **
22506 ******************************************************************************
22507 **
22508 ** This file contains macros and a little bit of code that is common to
22509 ** all of the platform-specific files (os_*.c) and is #included into those
22510 ** files.
22511 **
22512 ** This file should be #included by the os_*.c files only.  It is not a
22513 ** general purpose header file.
22514 */
22515 #ifndef _OS_COMMON_H_
22516 #define _OS_COMMON_H_
22517
22518 /*
22519 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22520 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22521 ** switch.  The following code should catch this problem at compile-time.
22522 */
22523 #ifdef MEMORY_DEBUG
22524 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22525 #endif
22526
22527 #ifdef SQLITE_DEBUG
22528 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22529 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22530 #else
22531 #define OSTRACE(X)
22532 #endif
22533
22534 /*
22535 ** Macros for performance tracing.  Normally turned off.  Only works
22536 ** on i486 hardware.
22537 */
22538 #ifdef SQLITE_PERFORMANCE_TRACE
22539
22540 /* 
22541 ** hwtime.h contains inline assembler code for implementing 
22542 ** high-performance timing routines.
22543 */
22544 /************** Include hwtime.h in the middle of os_common.h ****************/
22545 /************** Begin file hwtime.h ******************************************/
22546 /*
22547 ** 2008 May 27
22548 **
22549 ** The author disclaims copyright to this source code.  In place of
22550 ** a legal notice, here is a blessing:
22551 **
22552 **    May you do good and not evil.
22553 **    May you find forgiveness for yourself and forgive others.
22554 **    May you share freely, never taking more than you give.
22555 **
22556 ******************************************************************************
22557 **
22558 ** This file contains inline asm code for retrieving "high-performance"
22559 ** counters for x86 class CPUs.
22560 */
22561 #ifndef _HWTIME_H_
22562 #define _HWTIME_H_
22563
22564 /*
22565 ** The following routine only works on pentium-class (or newer) processors.
22566 ** It uses the RDTSC opcode to read the cycle count value out of the
22567 ** processor and returns that value.  This can be used for high-res
22568 ** profiling.
22569 */
22570 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22571       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22572
22573   #if defined(__GNUC__)
22574
22575   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22576      unsigned int lo, hi;
22577      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22578      return (sqlite_uint64)hi << 32 | lo;
22579   }
22580
22581   #elif defined(_MSC_VER)
22582
22583   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22584      __asm {
22585         rdtsc
22586         ret       ; return value at EDX:EAX
22587      }
22588   }
22589
22590   #endif
22591
22592 #elif (defined(__GNUC__) && defined(__x86_64__))
22593
22594   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22595       unsigned long val;
22596       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22597       return val;
22598   }
22599  
22600 #elif (defined(__GNUC__) && defined(__ppc__))
22601
22602   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22603       unsigned long long retval;
22604       unsigned long junk;
22605       __asm__ __volatile__ ("\n\
22606           1:      mftbu   %1\n\
22607                   mftb    %L0\n\
22608                   mftbu   %0\n\
22609                   cmpw    %0,%1\n\
22610                   bne     1b"
22611                   : "=r" (retval), "=r" (junk));
22612       return retval;
22613   }
22614
22615 #else
22616
22617   #error Need implementation of sqlite3Hwtime() for your platform.
22618
22619   /*
22620   ** To compile without implementing sqlite3Hwtime() for your platform,
22621   ** you can remove the above #error and use the following
22622   ** stub function.  You will lose timing support for many
22623   ** of the debugging and testing utilities, but it should at
22624   ** least compile and run.
22625   */
22626 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22627
22628 #endif
22629
22630 #endif /* !defined(_HWTIME_H_) */
22631
22632 /************** End of hwtime.h **********************************************/
22633 /************** Continuing where we left off in os_common.h ******************/
22634
22635 static sqlite_uint64 g_start;
22636 static sqlite_uint64 g_elapsed;
22637 #define TIMER_START       g_start=sqlite3Hwtime()
22638 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22639 #define TIMER_ELAPSED     g_elapsed
22640 #else
22641 #define TIMER_START
22642 #define TIMER_END
22643 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22644 #endif
22645
22646 /*
22647 ** If we compile with the SQLITE_TEST macro set, then the following block
22648 ** of code will give us the ability to simulate a disk I/O error.  This
22649 ** is used for testing the I/O recovery logic.
22650 */
22651 #ifdef SQLITE_TEST
22652 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22653 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22654 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22655 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22656 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22657 SQLITE_API int sqlite3_diskfull_pending = 0;
22658 SQLITE_API int sqlite3_diskfull = 0;
22659 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22660 #define SimulateIOError(CODE)  \
22661   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22662        || sqlite3_io_error_pending-- == 1 )  \
22663               { local_ioerr(); CODE; }
22664 static void local_ioerr(){
22665   IOTRACE(("IOERR\n"));
22666   sqlite3_io_error_hit++;
22667   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22668 }
22669 #define SimulateDiskfullError(CODE) \
22670    if( sqlite3_diskfull_pending ){ \
22671      if( sqlite3_diskfull_pending == 1 ){ \
22672        local_ioerr(); \
22673        sqlite3_diskfull = 1; \
22674        sqlite3_io_error_hit = 1; \
22675        CODE; \
22676      }else{ \
22677        sqlite3_diskfull_pending--; \
22678      } \
22679    }
22680 #else
22681 #define SimulateIOErrorBenign(X)
22682 #define SimulateIOError(A)
22683 #define SimulateDiskfullError(A)
22684 #endif
22685
22686 /*
22687 ** When testing, keep a count of the number of open files.
22688 */
22689 #ifdef SQLITE_TEST
22690 SQLITE_API int sqlite3_open_file_count = 0;
22691 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22692 #else
22693 #define OpenCounter(X)
22694 #endif
22695
22696 #endif /* !defined(_OS_COMMON_H_) */
22697
22698 /************** End of os_common.h *******************************************/
22699 /************** Continuing where we left off in os_unix.c ********************/
22700
22701 /*
22702 ** Define various macros that are missing from some systems.
22703 */
22704 #ifndef O_LARGEFILE
22705 # define O_LARGEFILE 0
22706 #endif
22707 #ifdef SQLITE_DISABLE_LFS
22708 # undef O_LARGEFILE
22709 # define O_LARGEFILE 0
22710 #endif
22711 #ifndef O_NOFOLLOW
22712 # define O_NOFOLLOW 0
22713 #endif
22714 #ifndef O_BINARY
22715 # define O_BINARY 0
22716 #endif
22717
22718 /*
22719 ** The DJGPP compiler environment looks mostly like Unix, but it
22720 ** lacks the fcntl() system call.  So redefine fcntl() to be something
22721 ** that always succeeds.  This means that locking does not occur under
22722 ** DJGPP.  But it is DOS - what did you expect?
22723 */
22724 #ifdef __DJGPP__
22725 # define fcntl(A,B,C) 0
22726 #endif
22727
22728 /*
22729 ** The threadid macro resolves to the thread-id or to 0.  Used for
22730 ** testing and debugging only.
22731 */
22732 #if SQLITE_THREADSAFE
22733 #define threadid pthread_self()
22734 #else
22735 #define threadid 0
22736 #endif
22737
22738
22739 /*
22740 ** Helper functions to obtain and relinquish the global mutex. The
22741 ** global mutex is used to protect the unixInodeInfo and
22742 ** vxworksFileId objects used by this file, all of which may be 
22743 ** shared by multiple threads.
22744 **
22745 ** Function unixMutexHeld() is used to assert() that the global mutex 
22746 ** is held when required. This function is only used as part of assert() 
22747 ** statements. e.g.
22748 **
22749 **   unixEnterMutex()
22750 **     assert( unixMutexHeld() );
22751 **   unixEnterLeave()
22752 */
22753 static void unixEnterMutex(void){
22754   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22755 }
22756 static void unixLeaveMutex(void){
22757   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22758 }
22759 #ifdef SQLITE_DEBUG
22760 static int unixMutexHeld(void) {
22761   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22762 }
22763 #endif
22764
22765
22766 #ifdef SQLITE_DEBUG
22767 /*
22768 ** Helper function for printing out trace information from debugging
22769 ** binaries. This returns the string represetation of the supplied
22770 ** integer lock-type.
22771 */
22772 static const char *azFileLock(int eFileLock){
22773   switch( eFileLock ){
22774     case NO_LOCK: return "NONE";
22775     case SHARED_LOCK: return "SHARED";
22776     case RESERVED_LOCK: return "RESERVED";
22777     case PENDING_LOCK: return "PENDING";
22778     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22779   }
22780   return "ERROR";
22781 }
22782 #endif
22783
22784 #ifdef SQLITE_LOCK_TRACE
22785 /*
22786 ** Print out information about all locking operations.
22787 **
22788 ** This routine is used for troubleshooting locks on multithreaded
22789 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22790 ** command-line option on the compiler.  This code is normally
22791 ** turned off.
22792 */
22793 static int lockTrace(int fd, int op, struct flock *p){
22794   char *zOpName, *zType;
22795   int s;
22796   int savedErrno;
22797   if( op==F_GETLK ){
22798     zOpName = "GETLK";
22799   }else if( op==F_SETLK ){
22800     zOpName = "SETLK";
22801   }else{
22802     s = fcntl(fd, op, p);
22803     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22804     return s;
22805   }
22806   if( p->l_type==F_RDLCK ){
22807     zType = "RDLCK";
22808   }else if( p->l_type==F_WRLCK ){
22809     zType = "WRLCK";
22810   }else if( p->l_type==F_UNLCK ){
22811     zType = "UNLCK";
22812   }else{
22813     assert( 0 );
22814   }
22815   assert( p->l_whence==SEEK_SET );
22816   s = fcntl(fd, op, p);
22817   savedErrno = errno;
22818   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22819      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22820      (int)p->l_pid, s);
22821   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22822     struct flock l2;
22823     l2 = *p;
22824     fcntl(fd, F_GETLK, &l2);
22825     if( l2.l_type==F_RDLCK ){
22826       zType = "RDLCK";
22827     }else if( l2.l_type==F_WRLCK ){
22828       zType = "WRLCK";
22829     }else if( l2.l_type==F_UNLCK ){
22830       zType = "UNLCK";
22831     }else{
22832       assert( 0 );
22833     }
22834     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22835        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22836   }
22837   errno = savedErrno;
22838   return s;
22839 }
22840 #define fcntl lockTrace
22841 #endif /* SQLITE_LOCK_TRACE */
22842
22843
22844
22845 /*
22846 ** This routine translates a standard POSIX errno code into something
22847 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22848 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22849 ** and a variety of "please close the file descriptor NOW" errors into 
22850 ** SQLITE_IOERR
22851 ** 
22852 ** Errors during initialization of locks, or file system support for locks,
22853 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22854 */
22855 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22856   switch (posixError) {
22857   case 0: 
22858     return SQLITE_OK;
22859     
22860   case EAGAIN:
22861   case ETIMEDOUT:
22862   case EBUSY:
22863   case EINTR:
22864   case ENOLCK:  
22865     /* random NFS retry error, unless during file system support 
22866      * introspection, in which it actually means what it says */
22867     return SQLITE_BUSY;
22868     
22869   case EACCES: 
22870     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22871     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22872         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22873         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22874         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22875       return SQLITE_BUSY;
22876     }
22877     /* else fall through */
22878   case EPERM: 
22879     return SQLITE_PERM;
22880     
22881   case EDEADLK:
22882     return SQLITE_IOERR_BLOCKED;
22883     
22884 #if EOPNOTSUPP!=ENOTSUP
22885   case EOPNOTSUPP: 
22886     /* something went terribly awry, unless during file system support 
22887      * introspection, in which it actually means what it says */
22888 #endif
22889 #ifdef ENOTSUP
22890   case ENOTSUP: 
22891     /* invalid fd, unless during file system support introspection, in which 
22892      * it actually means what it says */
22893 #endif
22894   case EIO:
22895   case EBADF:
22896   case EINVAL:
22897   case ENOTCONN:
22898   case ENODEV:
22899   case ENXIO:
22900   case ENOENT:
22901   case ESTALE:
22902   case ENOSYS:
22903     /* these should force the client to close the file and reconnect */
22904     
22905   default: 
22906     return sqliteIOErr;
22907   }
22908 }
22909
22910
22911
22912 /******************************************************************************
22913 ****************** Begin Unique File ID Utility Used By VxWorks ***************
22914 **
22915 ** On most versions of unix, we can get a unique ID for a file by concatenating
22916 ** the device number and the inode number.  But this does not work on VxWorks.
22917 ** On VxWorks, a unique file id must be based on the canonical filename.
22918 **
22919 ** A pointer to an instance of the following structure can be used as a
22920 ** unique file ID in VxWorks.  Each instance of this structure contains
22921 ** a copy of the canonical filename.  There is also a reference count.  
22922 ** The structure is reclaimed when the number of pointers to it drops to
22923 ** zero.
22924 **
22925 ** There are never very many files open at one time and lookups are not
22926 ** a performance-critical path, so it is sufficient to put these
22927 ** structures on a linked list.
22928 */
22929 struct vxworksFileId {
22930   struct vxworksFileId *pNext;  /* Next in a list of them all */
22931   int nRef;                     /* Number of references to this one */
22932   int nName;                    /* Length of the zCanonicalName[] string */
22933   char *zCanonicalName;         /* Canonical filename */
22934 };
22935
22936 #if OS_VXWORKS
22937 /* 
22938 ** All unique filenames are held on a linked list headed by this
22939 ** variable:
22940 */
22941 static struct vxworksFileId *vxworksFileList = 0;
22942
22943 /*
22944 ** Simplify a filename into its canonical form
22945 ** by making the following changes:
22946 **
22947 **  * removing any trailing and duplicate /
22948 **  * convert /./ into just /
22949 **  * convert /A/../ where A is any simple name into just /
22950 **
22951 ** Changes are made in-place.  Return the new name length.
22952 **
22953 ** The original filename is in z[0..n-1].  Return the number of
22954 ** characters in the simplified name.
22955 */
22956 static int vxworksSimplifyName(char *z, int n){
22957   int i, j;
22958   while( n>1 && z[n-1]=='/' ){ n--; }
22959   for(i=j=0; i<n; i++){
22960     if( z[i]=='/' ){
22961       if( z[i+1]=='/' ) continue;
22962       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22963         i += 1;
22964         continue;
22965       }
22966       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22967         while( j>0 && z[j-1]!='/' ){ j--; }
22968         if( j>0 ){ j--; }
22969         i += 2;
22970         continue;
22971       }
22972     }
22973     z[j++] = z[i];
22974   }
22975   z[j] = 0;
22976   return j;
22977 }
22978
22979 /*
22980 ** Find a unique file ID for the given absolute pathname.  Return
22981 ** a pointer to the vxworksFileId object.  This pointer is the unique
22982 ** file ID.
22983 **
22984 ** The nRef field of the vxworksFileId object is incremented before
22985 ** the object is returned.  A new vxworksFileId object is created
22986 ** and added to the global list if necessary.
22987 **
22988 ** If a memory allocation error occurs, return NULL.
22989 */
22990 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22991   struct vxworksFileId *pNew;         /* search key and new file ID */
22992   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22993   int n;                              /* Length of zAbsoluteName string */
22994
22995   assert( zAbsoluteName[0]=='/' );
22996   n = (int)strlen(zAbsoluteName);
22997   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22998   if( pNew==0 ) return 0;
22999   pNew->zCanonicalName = (char*)&pNew[1];
23000   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23001   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23002
23003   /* Search for an existing entry that matching the canonical name.
23004   ** If found, increment the reference count and return a pointer to
23005   ** the existing file ID.
23006   */
23007   unixEnterMutex();
23008   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23009     if( pCandidate->nName==n 
23010      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23011     ){
23012        sqlite3_free(pNew);
23013        pCandidate->nRef++;
23014        unixLeaveMutex();
23015        return pCandidate;
23016     }
23017   }
23018
23019   /* No match was found.  We will make a new file ID */
23020   pNew->nRef = 1;
23021   pNew->nName = n;
23022   pNew->pNext = vxworksFileList;
23023   vxworksFileList = pNew;
23024   unixLeaveMutex();
23025   return pNew;
23026 }
23027
23028 /*
23029 ** Decrement the reference count on a vxworksFileId object.  Free
23030 ** the object when the reference count reaches zero.
23031 */
23032 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23033   unixEnterMutex();
23034   assert( pId->nRef>0 );
23035   pId->nRef--;
23036   if( pId->nRef==0 ){
23037     struct vxworksFileId **pp;
23038     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23039     assert( *pp==pId );
23040     *pp = pId->pNext;
23041     sqlite3_free(pId);
23042   }
23043   unixLeaveMutex();
23044 }
23045 #endif /* OS_VXWORKS */
23046 /*************** End of Unique File ID Utility Used By VxWorks ****************
23047 ******************************************************************************/
23048
23049
23050 /******************************************************************************
23051 *************************** Posix Advisory Locking ****************************
23052 **
23053 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23054 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23055 ** sets or clears a lock, that operation overrides any prior locks set
23056 ** by the same process.  It does not explicitly say so, but this implies
23057 ** that it overrides locks set by the same process using a different
23058 ** file descriptor.  Consider this test case:
23059 **
23060 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23061 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23062 **
23063 ** Suppose ./file1 and ./file2 are really the same file (because
23064 ** one is a hard or symbolic link to the other) then if you set
23065 ** an exclusive lock on fd1, then try to get an exclusive lock
23066 ** on fd2, it works.  I would have expected the second lock to
23067 ** fail since there was already a lock on the file due to fd1.
23068 ** But not so.  Since both locks came from the same process, the
23069 ** second overrides the first, even though they were on different
23070 ** file descriptors opened on different file names.
23071 **
23072 ** This means that we cannot use POSIX locks to synchronize file access
23073 ** among competing threads of the same process.  POSIX locks will work fine
23074 ** to synchronize access for threads in separate processes, but not
23075 ** threads within the same process.
23076 **
23077 ** To work around the problem, SQLite has to manage file locks internally
23078 ** on its own.  Whenever a new database is opened, we have to find the
23079 ** specific inode of the database file (the inode is determined by the
23080 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23081 ** and check for locks already existing on that inode.  When locks are
23082 ** created or removed, we have to look at our own internal record of the
23083 ** locks to see if another thread has previously set a lock on that same
23084 ** inode.
23085 **
23086 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23087 ** For VxWorks, we have to use the alternative unique ID system based on
23088 ** canonical filename and implemented in the previous division.)
23089 **
23090 ** The sqlite3_file structure for POSIX is no longer just an integer file
23091 ** descriptor.  It is now a structure that holds the integer file
23092 ** descriptor and a pointer to a structure that describes the internal
23093 ** locks on the corresponding inode.  There is one locking structure
23094 ** per inode, so if the same inode is opened twice, both unixFile structures
23095 ** point to the same locking structure.  The locking structure keeps
23096 ** a reference count (so we will know when to delete it) and a "cnt"
23097 ** field that tells us its internal lock status.  cnt==0 means the
23098 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23099 ** cnt>0 means there are cnt shared locks on the file.
23100 **
23101 ** Any attempt to lock or unlock a file first checks the locking
23102 ** structure.  The fcntl() system call is only invoked to set a 
23103 ** POSIX lock if the internal lock structure transitions between
23104 ** a locked and an unlocked state.
23105 **
23106 ** But wait:  there are yet more problems with POSIX advisory locks.
23107 **
23108 ** If you close a file descriptor that points to a file that has locks,
23109 ** all locks on that file that are owned by the current process are
23110 ** released.  To work around this problem, each unixInodeInfo object
23111 ** maintains a count of the number of pending locks on tha inode.
23112 ** When an attempt is made to close an unixFile, if there are
23113 ** other unixFile open on the same inode that are holding locks, the call
23114 ** to close() the file descriptor is deferred until all of the locks clear.
23115 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23116 ** be closed and that list is walked (and cleared) when the last lock
23117 ** clears.
23118 **
23119 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23120 **
23121 ** Many older versions of linux use the LinuxThreads library which is
23122 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23123 ** A cannot be modified or overridden by a different thread B.
23124 ** Only thread A can modify the lock.  Locking behavior is correct
23125 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23126 ** on linux - with NPTL a lock created by thread A can override locks
23127 ** in thread B.  But there is no way to know at compile-time which
23128 ** threading library is being used.  So there is no way to know at
23129 ** compile-time whether or not thread A can override locks on thread B.
23130 ** One has to do a run-time check to discover the behavior of the
23131 ** current process.
23132 **
23133 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23134 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23135 ** LinuxThreads provided that (1) there is no more than one connection 
23136 ** per database file in the same process and (2) database connections
23137 ** do not move across threads.
23138 */
23139
23140 /*
23141 ** An instance of the following structure serves as the key used
23142 ** to locate a particular unixInodeInfo object.
23143 */
23144 struct unixFileId {
23145   dev_t dev;                  /* Device number */
23146 #if OS_VXWORKS
23147   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23148 #else
23149   ino_t ino;                  /* Inode number */
23150 #endif
23151 };
23152
23153 /*
23154 ** An instance of the following structure is allocated for each open
23155 ** inode.  Or, on LinuxThreads, there is one of these structures for
23156 ** each inode opened by each thread.
23157 **
23158 ** A single inode can have multiple file descriptors, so each unixFile
23159 ** structure contains a pointer to an instance of this object and this
23160 ** object keeps a count of the number of unixFile pointing to it.
23161 */
23162 struct unixInodeInfo {
23163   struct unixFileId fileId;       /* The lookup key */
23164   int nShared;                    /* Number of SHARED locks held */
23165   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23166   int nRef;                       /* Number of pointers to this structure */
23167   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23168   int nLock;                      /* Number of outstanding file locks */
23169   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23170   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23171   unixInodeInfo *pPrev;           /*    .... doubly linked */
23172 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23173   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23174 #endif
23175 #if OS_VXWORKS
23176   sem_t *pSem;                    /* Named POSIX semaphore */
23177   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23178 #endif
23179 };
23180
23181 /*
23182 ** A lists of all unixInodeInfo objects.
23183 */
23184 static unixInodeInfo *inodeList = 0;
23185
23186 /*
23187 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23188 ** If all such file descriptors are closed without error, the list is
23189 ** cleared and SQLITE_OK returned.
23190 **
23191 ** Otherwise, if an error occurs, then successfully closed file descriptor
23192 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23193 ** not deleted and SQLITE_IOERR_CLOSE returned.
23194 */ 
23195 static int closePendingFds(unixFile *pFile){
23196   int rc = SQLITE_OK;
23197   unixInodeInfo *pInode = pFile->pInode;
23198   UnixUnusedFd *pError = 0;
23199   UnixUnusedFd *p;
23200   UnixUnusedFd *pNext;
23201   for(p=pInode->pUnused; p; p=pNext){
23202     pNext = p->pNext;
23203     if( close(p->fd) ){
23204       pFile->lastErrno = errno;
23205       rc = SQLITE_IOERR_CLOSE;
23206       p->pNext = pError;
23207       pError = p;
23208     }else{
23209       sqlite3_free(p);
23210     }
23211   }
23212   pInode->pUnused = pError;
23213   return rc;
23214 }
23215
23216 /*
23217 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23218 **
23219 ** The mutex entered using the unixEnterMutex() function must be held
23220 ** when this function is called.
23221 */
23222 static void releaseInodeInfo(unixFile *pFile){
23223   unixInodeInfo *pInode = pFile->pInode;
23224   assert( unixMutexHeld() );
23225   if( pInode ){
23226     pInode->nRef--;
23227     if( pInode->nRef==0 ){
23228       assert( pInode->pShmNode==0 );
23229       closePendingFds(pFile);
23230       if( pInode->pPrev ){
23231         assert( pInode->pPrev->pNext==pInode );
23232         pInode->pPrev->pNext = pInode->pNext;
23233       }else{
23234         assert( inodeList==pInode );
23235         inodeList = pInode->pNext;
23236       }
23237       if( pInode->pNext ){
23238         assert( pInode->pNext->pPrev==pInode );
23239         pInode->pNext->pPrev = pInode->pPrev;
23240       }
23241       sqlite3_free(pInode);
23242     }
23243   }
23244 }
23245
23246 /*
23247 ** Given a file descriptor, locate the unixInodeInfo object that
23248 ** describes that file descriptor.  Create a new one if necessary.  The
23249 ** return value might be uninitialized if an error occurs.
23250 **
23251 ** The mutex entered using the unixEnterMutex() function must be held
23252 ** when this function is called.
23253 **
23254 ** Return an appropriate error code.
23255 */
23256 static int findInodeInfo(
23257   unixFile *pFile,               /* Unix file with file desc used in the key */
23258   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23259 ){
23260   int rc;                        /* System call return code */
23261   int fd;                        /* The file descriptor for pFile */
23262   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23263   struct stat statbuf;           /* Low-level file information */
23264   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23265
23266   assert( unixMutexHeld() );
23267
23268   /* Get low-level information about the file that we can used to
23269   ** create a unique name for the file.
23270   */
23271   fd = pFile->h;
23272   rc = fstat(fd, &statbuf);
23273   if( rc!=0 ){
23274     pFile->lastErrno = errno;
23275 #ifdef EOVERFLOW
23276     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23277 #endif
23278     return SQLITE_IOERR;
23279   }
23280
23281 #ifdef __APPLE__
23282   /* On OS X on an msdos filesystem, the inode number is reported
23283   ** incorrectly for zero-size files.  See ticket #3260.  To work
23284   ** around this problem (we consider it a bug in OS X, not SQLite)
23285   ** we always increase the file size to 1 by writing a single byte
23286   ** prior to accessing the inode number.  The one byte written is
23287   ** an ASCII 'S' character which also happens to be the first byte
23288   ** in the header of every SQLite database.  In this way, if there
23289   ** is a race condition such that another thread has already populated
23290   ** the first page of the database, no damage is done.
23291   */
23292   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23293     rc = write(fd, "S", 1);
23294     if( rc!=1 ){
23295       pFile->lastErrno = errno;
23296       return SQLITE_IOERR;
23297     }
23298     rc = fstat(fd, &statbuf);
23299     if( rc!=0 ){
23300       pFile->lastErrno = errno;
23301       return SQLITE_IOERR;
23302     }
23303   }
23304 #endif
23305
23306   memset(&fileId, 0, sizeof(fileId));
23307   fileId.dev = statbuf.st_dev;
23308 #if OS_VXWORKS
23309   fileId.pId = pFile->pId;
23310 #else
23311   fileId.ino = statbuf.st_ino;
23312 #endif
23313   pInode = inodeList;
23314   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23315     pInode = pInode->pNext;
23316   }
23317   if( pInode==0 ){
23318     pInode = sqlite3_malloc( sizeof(*pInode) );
23319     if( pInode==0 ){
23320       return SQLITE_NOMEM;
23321     }
23322     memset(pInode, 0, sizeof(*pInode));
23323     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23324     pInode->nRef = 1;
23325     pInode->pNext = inodeList;
23326     pInode->pPrev = 0;
23327     if( inodeList ) inodeList->pPrev = pInode;
23328     inodeList = pInode;
23329   }else{
23330     pInode->nRef++;
23331   }
23332   *ppInode = pInode;
23333   return SQLITE_OK;
23334 }
23335
23336
23337 /*
23338 ** This routine checks if there is a RESERVED lock held on the specified
23339 ** file by this or any other process. If such a lock is held, set *pResOut
23340 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23341 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23342 */
23343 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23344   int rc = SQLITE_OK;
23345   int reserved = 0;
23346   unixFile *pFile = (unixFile*)id;
23347
23348   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23349
23350   assert( pFile );
23351   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23352
23353   /* Check if a thread in this process holds such a lock */
23354   if( pFile->pInode->eFileLock>SHARED_LOCK ){
23355     reserved = 1;
23356   }
23357
23358   /* Otherwise see if some other process holds it.
23359   */
23360 #ifndef __DJGPP__
23361   if( !reserved ){
23362     struct flock lock;
23363     lock.l_whence = SEEK_SET;
23364     lock.l_start = RESERVED_BYTE;
23365     lock.l_len = 1;
23366     lock.l_type = F_WRLCK;
23367     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23368       int tErrno = errno;
23369       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23370       pFile->lastErrno = tErrno;
23371     } else if( lock.l_type!=F_UNLCK ){
23372       reserved = 1;
23373     }
23374   }
23375 #endif
23376   
23377   unixLeaveMutex();
23378   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23379
23380   *pResOut = reserved;
23381   return rc;
23382 }
23383
23384 /*
23385 ** Lock the file with the lock specified by parameter eFileLock - one
23386 ** of the following:
23387 **
23388 **     (1) SHARED_LOCK
23389 **     (2) RESERVED_LOCK
23390 **     (3) PENDING_LOCK
23391 **     (4) EXCLUSIVE_LOCK
23392 **
23393 ** Sometimes when requesting one lock state, additional lock states
23394 ** are inserted in between.  The locking might fail on one of the later
23395 ** transitions leaving the lock state different from what it started but
23396 ** still short of its goal.  The following chart shows the allowed
23397 ** transitions and the inserted intermediate states:
23398 **
23399 **    UNLOCKED -> SHARED
23400 **    SHARED -> RESERVED
23401 **    SHARED -> (PENDING) -> EXCLUSIVE
23402 **    RESERVED -> (PENDING) -> EXCLUSIVE
23403 **    PENDING -> EXCLUSIVE
23404 **
23405 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23406 ** routine to lower a locking level.
23407 */
23408 static int unixLock(sqlite3_file *id, int eFileLock){
23409   /* The following describes the implementation of the various locks and
23410   ** lock transitions in terms of the POSIX advisory shared and exclusive
23411   ** lock primitives (called read-locks and write-locks below, to avoid
23412   ** confusion with SQLite lock names). The algorithms are complicated
23413   ** slightly in order to be compatible with windows systems simultaneously
23414   ** accessing the same database file, in case that is ever required.
23415   **
23416   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23417   ** byte', each single bytes at well known offsets, and the 'shared byte
23418   ** range', a range of 510 bytes at a well known offset.
23419   **
23420   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23421   ** byte'.  If this is successful, a random byte from the 'shared byte
23422   ** range' is read-locked and the lock on the 'pending byte' released.
23423   **
23424   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23425   ** A RESERVED lock is implemented by grabbing a write-lock on the
23426   ** 'reserved byte'. 
23427   **
23428   ** A process may only obtain a PENDING lock after it has obtained a
23429   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23430   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23431   ** obtained, but existing SHARED locks are allowed to persist. A process
23432   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23433   ** This property is used by the algorithm for rolling back a journal file
23434   ** after a crash.
23435   **
23436   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23437   ** implemented by obtaining a write-lock on the entire 'shared byte
23438   ** range'. Since all other locks require a read-lock on one of the bytes
23439   ** within this range, this ensures that no other locks are held on the
23440   ** database. 
23441   **
23442   ** The reason a single byte cannot be used instead of the 'shared byte
23443   ** range' is that some versions of windows do not support read-locks. By
23444   ** locking a random byte from a range, concurrent SHARED locks may exist
23445   ** even if the locking primitive used is always a write-lock.
23446   */
23447   int rc = SQLITE_OK;
23448   unixFile *pFile = (unixFile*)id;
23449   unixInodeInfo *pInode = pFile->pInode;
23450   struct flock lock;
23451   int s = 0;
23452   int tErrno = 0;
23453
23454   assert( pFile );
23455   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23456       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23457       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23458
23459   /* If there is already a lock of this type or more restrictive on the
23460   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23461   ** unixEnterMutex() hasn't been called yet.
23462   */
23463   if( pFile->eFileLock>=eFileLock ){
23464     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23465             azFileLock(eFileLock)));
23466     return SQLITE_OK;
23467   }
23468
23469   /* Make sure the locking sequence is correct.
23470   **  (1) We never move from unlocked to anything higher than shared lock.
23471   **  (2) SQLite never explicitly requests a pendig lock.
23472   **  (3) A shared lock is always held when a reserve lock is requested.
23473   */
23474   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23475   assert( eFileLock!=PENDING_LOCK );
23476   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23477
23478   /* This mutex is needed because pFile->pInode is shared across threads
23479   */
23480   unixEnterMutex();
23481   pInode = pFile->pInode;
23482
23483   /* If some thread using this PID has a lock via a different unixFile*
23484   ** handle that precludes the requested lock, return BUSY.
23485   */
23486   if( (pFile->eFileLock!=pInode->eFileLock && 
23487           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23488   ){
23489     rc = SQLITE_BUSY;
23490     goto end_lock;
23491   }
23492
23493   /* If a SHARED lock is requested, and some thread using this PID already
23494   ** has a SHARED or RESERVED lock, then increment reference counts and
23495   ** return SQLITE_OK.
23496   */
23497   if( eFileLock==SHARED_LOCK && 
23498       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23499     assert( eFileLock==SHARED_LOCK );
23500     assert( pFile->eFileLock==0 );
23501     assert( pInode->nShared>0 );
23502     pFile->eFileLock = SHARED_LOCK;
23503     pInode->nShared++;
23504     pInode->nLock++;
23505     goto end_lock;
23506   }
23507
23508
23509   /* A PENDING lock is needed before acquiring a SHARED lock and before
23510   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23511   ** be released.
23512   */
23513   lock.l_len = 1L;
23514   lock.l_whence = SEEK_SET;
23515   if( eFileLock==SHARED_LOCK 
23516       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23517   ){
23518     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23519     lock.l_start = PENDING_BYTE;
23520     s = fcntl(pFile->h, F_SETLK, &lock);
23521     if( s==(-1) ){
23522       tErrno = errno;
23523       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23524       if( IS_LOCK_ERROR(rc) ){
23525         pFile->lastErrno = tErrno;
23526       }
23527       goto end_lock;
23528     }
23529   }
23530
23531
23532   /* If control gets to this point, then actually go ahead and make
23533   ** operating system calls for the specified lock.
23534   */
23535   if( eFileLock==SHARED_LOCK ){
23536     assert( pInode->nShared==0 );
23537     assert( pInode->eFileLock==0 );
23538
23539     /* Now get the read-lock */
23540     lock.l_start = SHARED_FIRST;
23541     lock.l_len = SHARED_SIZE;
23542     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23543       tErrno = errno;
23544     }
23545     /* Drop the temporary PENDING lock */
23546     lock.l_start = PENDING_BYTE;
23547     lock.l_len = 1L;
23548     lock.l_type = F_UNLCK;
23549     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23550       if( s != -1 ){
23551         /* This could happen with a network mount */
23552         tErrno = errno; 
23553         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23554         if( IS_LOCK_ERROR(rc) ){
23555           pFile->lastErrno = tErrno;
23556         }
23557         goto end_lock;
23558       }
23559     }
23560     if( s==(-1) ){
23561       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23562       if( IS_LOCK_ERROR(rc) ){
23563         pFile->lastErrno = tErrno;
23564       }
23565     }else{
23566       pFile->eFileLock = SHARED_LOCK;
23567       pInode->nLock++;
23568       pInode->nShared = 1;
23569     }
23570   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
23571     /* We are trying for an exclusive lock but another thread in this
23572     ** same process is still holding a shared lock. */
23573     rc = SQLITE_BUSY;
23574   }else{
23575     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23576     ** assumed that there is a SHARED or greater lock on the file
23577     ** already.
23578     */
23579     assert( 0!=pFile->eFileLock );
23580     lock.l_type = F_WRLCK;
23581     switch( eFileLock ){
23582       case RESERVED_LOCK:
23583         lock.l_start = RESERVED_BYTE;
23584         break;
23585       case EXCLUSIVE_LOCK:
23586         lock.l_start = SHARED_FIRST;
23587         lock.l_len = SHARED_SIZE;
23588         break;
23589       default:
23590         assert(0);
23591     }
23592     s = fcntl(pFile->h, F_SETLK, &lock);
23593     if( s==(-1) ){
23594       tErrno = errno;
23595       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23596       if( IS_LOCK_ERROR(rc) ){
23597         pFile->lastErrno = tErrno;
23598       }
23599     }
23600   }
23601   
23602
23603 #ifndef NDEBUG
23604   /* Set up the transaction-counter change checking flags when
23605   ** transitioning from a SHARED to a RESERVED lock.  The change
23606   ** from SHARED to RESERVED marks the beginning of a normal
23607   ** write operation (not a hot journal rollback).
23608   */
23609   if( rc==SQLITE_OK
23610    && pFile->eFileLock<=SHARED_LOCK
23611    && eFileLock==RESERVED_LOCK
23612   ){
23613     pFile->transCntrChng = 0;
23614     pFile->dbUpdate = 0;
23615     pFile->inNormalWrite = 1;
23616   }
23617 #endif
23618
23619
23620   if( rc==SQLITE_OK ){
23621     pFile->eFileLock = eFileLock;
23622     pInode->eFileLock = eFileLock;
23623   }else if( eFileLock==EXCLUSIVE_LOCK ){
23624     pFile->eFileLock = PENDING_LOCK;
23625     pInode->eFileLock = PENDING_LOCK;
23626   }
23627
23628 end_lock:
23629   unixLeaveMutex();
23630   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
23631       rc==SQLITE_OK ? "ok" : "failed"));
23632   return rc;
23633 }
23634
23635 /*
23636 ** Add the file descriptor used by file handle pFile to the corresponding
23637 ** pUnused list.
23638 */
23639 static void setPendingFd(unixFile *pFile){
23640   unixInodeInfo *pInode = pFile->pInode;
23641   UnixUnusedFd *p = pFile->pUnused;
23642   p->pNext = pInode->pUnused;
23643   pInode->pUnused = p;
23644   pFile->h = -1;
23645   pFile->pUnused = 0;
23646 }
23647
23648 /*
23649 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23650 ** must be either NO_LOCK or SHARED_LOCK.
23651 **
23652 ** If the locking level of the file descriptor is already at or below
23653 ** the requested locking level, this routine is a no-op.
23654 ** 
23655 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
23656 ** the byte range is divided into 2 parts and the first part is unlocked then
23657 ** set to a read lock, then the other part is simply unlocked.  This works 
23658 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
23659 ** remove the write lock on a region when a read lock is set.
23660 */
23661 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
23662   unixFile *pFile = (unixFile*)id;
23663   unixInodeInfo *pInode;
23664   struct flock lock;
23665   int rc = SQLITE_OK;
23666   int h;
23667   int tErrno;                      /* Error code from system call errors */
23668
23669   assert( pFile );
23670   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
23671       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
23672       getpid()));
23673
23674   assert( eFileLock<=SHARED_LOCK );
23675   if( pFile->eFileLock<=eFileLock ){
23676     return SQLITE_OK;
23677   }
23678   unixEnterMutex();
23679   h = pFile->h;
23680   pInode = pFile->pInode;
23681   assert( pInode->nShared!=0 );
23682   if( pFile->eFileLock>SHARED_LOCK ){
23683     assert( pInode->eFileLock==pFile->eFileLock );
23684     SimulateIOErrorBenign(1);
23685     SimulateIOError( h=(-1) )
23686     SimulateIOErrorBenign(0);
23687
23688 #ifndef NDEBUG
23689     /* When reducing a lock such that other processes can start
23690     ** reading the database file again, make sure that the
23691     ** transaction counter was updated if any part of the database
23692     ** file changed.  If the transaction counter is not updated,
23693     ** other connections to the same file might not realize that
23694     ** the file has changed and hence might not know to flush their
23695     ** cache.  The use of a stale cache can lead to database corruption.
23696     */
23697 #if 0
23698     assert( pFile->inNormalWrite==0
23699          || pFile->dbUpdate==0
23700          || pFile->transCntrChng==1 );
23701 #endif
23702     pFile->inNormalWrite = 0;
23703 #endif
23704
23705     /* downgrading to a shared lock on NFS involves clearing the write lock
23706     ** before establishing the readlock - to avoid a race condition we downgrade
23707     ** the lock in 2 blocks, so that part of the range will be covered by a 
23708     ** write lock until the rest is covered by a read lock:
23709     **  1:   [WWWWW]
23710     **  2:   [....W]
23711     **  3:   [RRRRW]
23712     **  4:   [RRRR.]
23713     */
23714     if( eFileLock==SHARED_LOCK ){
23715       if( handleNFSUnlock ){
23716         off_t divSize = SHARED_SIZE - 1;
23717         
23718         lock.l_type = F_UNLCK;
23719         lock.l_whence = SEEK_SET;
23720         lock.l_start = SHARED_FIRST;
23721         lock.l_len = divSize;
23722         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23723           tErrno = errno;
23724           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23725           if( IS_LOCK_ERROR(rc) ){
23726             pFile->lastErrno = tErrno;
23727           }
23728           goto end_unlock;
23729         }
23730         lock.l_type = F_RDLCK;
23731         lock.l_whence = SEEK_SET;
23732         lock.l_start = SHARED_FIRST;
23733         lock.l_len = divSize;
23734         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23735           tErrno = errno;
23736           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23737           if( IS_LOCK_ERROR(rc) ){
23738             pFile->lastErrno = tErrno;
23739           }
23740           goto end_unlock;
23741         }
23742         lock.l_type = F_UNLCK;
23743         lock.l_whence = SEEK_SET;
23744         lock.l_start = SHARED_FIRST+divSize;
23745         lock.l_len = SHARED_SIZE-divSize;
23746         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23747           tErrno = errno;
23748           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23749           if( IS_LOCK_ERROR(rc) ){
23750             pFile->lastErrno = tErrno;
23751           }
23752           goto end_unlock;
23753         }
23754       }else{
23755         lock.l_type = F_RDLCK;
23756         lock.l_whence = SEEK_SET;
23757         lock.l_start = SHARED_FIRST;
23758         lock.l_len = SHARED_SIZE;
23759         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23760           tErrno = errno;
23761           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23762           if( IS_LOCK_ERROR(rc) ){
23763             pFile->lastErrno = tErrno;
23764           }
23765           goto end_unlock;
23766         }
23767       }
23768     }
23769     lock.l_type = F_UNLCK;
23770     lock.l_whence = SEEK_SET;
23771     lock.l_start = PENDING_BYTE;
23772     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23773     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23774       pInode->eFileLock = SHARED_LOCK;
23775     }else{
23776       tErrno = errno;
23777       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23778       if( IS_LOCK_ERROR(rc) ){
23779         pFile->lastErrno = tErrno;
23780       }
23781       goto end_unlock;
23782     }
23783   }
23784   if( eFileLock==NO_LOCK ){
23785     /* Decrement the shared lock counter.  Release the lock using an
23786     ** OS call only when all threads in this same process have released
23787     ** the lock.
23788     */
23789     pInode->nShared--;
23790     if( pInode->nShared==0 ){
23791       lock.l_type = F_UNLCK;
23792       lock.l_whence = SEEK_SET;
23793       lock.l_start = lock.l_len = 0L;
23794       SimulateIOErrorBenign(1);
23795       SimulateIOError( h=(-1) )
23796       SimulateIOErrorBenign(0);
23797       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23798         pInode->eFileLock = NO_LOCK;
23799       }else{
23800         tErrno = errno;
23801         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23802         if( IS_LOCK_ERROR(rc) ){
23803           pFile->lastErrno = tErrno;
23804         }
23805         pInode->eFileLock = NO_LOCK;
23806         pFile->eFileLock = NO_LOCK;
23807       }
23808     }
23809
23810     /* Decrement the count of locks against this same file.  When the
23811     ** count reaches zero, close any other file descriptors whose close
23812     ** was deferred because of outstanding locks.
23813     */
23814     pInode->nLock--;
23815     assert( pInode->nLock>=0 );
23816     if( pInode->nLock==0 ){
23817       int rc2 = closePendingFds(pFile);
23818       if( rc==SQLITE_OK ){
23819         rc = rc2;
23820       }
23821     }
23822   }
23823         
23824 end_unlock:
23825   unixLeaveMutex();
23826   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
23827   return rc;
23828 }
23829
23830 /*
23831 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23832 ** must be either NO_LOCK or SHARED_LOCK.
23833 **
23834 ** If the locking level of the file descriptor is already at or below
23835 ** the requested locking level, this routine is a no-op.
23836 */
23837 static int unixUnlock(sqlite3_file *id, int eFileLock){
23838   return _posixUnlock(id, eFileLock, 0);
23839 }
23840
23841 /*
23842 ** This function performs the parts of the "close file" operation 
23843 ** common to all locking schemes. It closes the directory and file
23844 ** handles, if they are valid, and sets all fields of the unixFile
23845 ** structure to 0.
23846 **
23847 ** It is *not* necessary to hold the mutex when this routine is called,
23848 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
23849 ** vxworksReleaseFileId() routine.
23850 */
23851 static int closeUnixFile(sqlite3_file *id){
23852   unixFile *pFile = (unixFile*)id;
23853   if( pFile ){
23854     if( pFile->dirfd>=0 ){
23855       int err = close(pFile->dirfd);
23856       if( err ){
23857         pFile->lastErrno = errno;
23858         return SQLITE_IOERR_DIR_CLOSE;
23859       }else{
23860         pFile->dirfd=-1;
23861       }
23862     }
23863     if( pFile->h>=0 ){
23864       int err = close(pFile->h);
23865       if( err ){
23866         pFile->lastErrno = errno;
23867         return SQLITE_IOERR_CLOSE;
23868       }
23869     }
23870 #if OS_VXWORKS
23871     if( pFile->pId ){
23872       if( pFile->isDelete ){
23873         unlink(pFile->pId->zCanonicalName);
23874       }
23875       vxworksReleaseFileId(pFile->pId);
23876       pFile->pId = 0;
23877     }
23878 #endif
23879     OSTRACE(("CLOSE   %-3d\n", pFile->h));
23880     OpenCounter(-1);
23881     sqlite3_free(pFile->pUnused);
23882     memset(pFile, 0, sizeof(unixFile));
23883   }
23884   return SQLITE_OK;
23885 }
23886
23887 /*
23888 ** Close a file.
23889 */
23890 static int unixClose(sqlite3_file *id){
23891   int rc = SQLITE_OK;
23892   if( id ){
23893     unixFile *pFile = (unixFile *)id;
23894     unixUnlock(id, NO_LOCK);
23895     unixEnterMutex();
23896     if( pFile->pInode && pFile->pInode->nLock ){
23897       /* If there are outstanding locks, do not actually close the file just
23898       ** yet because that would clear those locks.  Instead, add the file
23899       ** descriptor to pInode->pUnused list.  It will be automatically closed 
23900       ** when the last lock is cleared.
23901       */
23902       setPendingFd(pFile);
23903     }
23904     releaseInodeInfo(pFile);
23905     rc = closeUnixFile(id);
23906     unixLeaveMutex();
23907   }
23908   return rc;
23909 }
23910
23911 /************** End of the posix advisory lock implementation *****************
23912 ******************************************************************************/
23913
23914 /******************************************************************************
23915 ****************************** No-op Locking **********************************
23916 **
23917 ** Of the various locking implementations available, this is by far the
23918 ** simplest:  locking is ignored.  No attempt is made to lock the database
23919 ** file for reading or writing.
23920 **
23921 ** This locking mode is appropriate for use on read-only databases
23922 ** (ex: databases that are burned into CD-ROM, for example.)  It can
23923 ** also be used if the application employs some external mechanism to
23924 ** prevent simultaneous access of the same database by two or more
23925 ** database connections.  But there is a serious risk of database
23926 ** corruption if this locking mode is used in situations where multiple
23927 ** database connections are accessing the same database file at the same
23928 ** time and one or more of those connections are writing.
23929 */
23930
23931 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23932   UNUSED_PARAMETER(NotUsed);
23933   *pResOut = 0;
23934   return SQLITE_OK;
23935 }
23936 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23937   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23938   return SQLITE_OK;
23939 }
23940 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23941   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23942   return SQLITE_OK;
23943 }
23944
23945 /*
23946 ** Close the file.
23947 */
23948 static int nolockClose(sqlite3_file *id) {
23949   return closeUnixFile(id);
23950 }
23951
23952 /******************* End of the no-op lock implementation *********************
23953 ******************************************************************************/
23954
23955 /******************************************************************************
23956 ************************* Begin dot-file Locking ******************************
23957 **
23958 ** The dotfile locking implementation uses the existance of separate lock
23959 ** files in order to control access to the database.  This works on just
23960 ** about every filesystem imaginable.  But there are serious downsides:
23961 **
23962 **    (1)  There is zero concurrency.  A single reader blocks all other
23963 **         connections from reading or writing the database.
23964 **
23965 **    (2)  An application crash or power loss can leave stale lock files
23966 **         sitting around that need to be cleared manually.
23967 **
23968 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
23969 ** other locking strategy is available.
23970 **
23971 ** Dotfile locking works by creating a file in the same directory as the
23972 ** database and with the same name but with a ".lock" extension added.
23973 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23974 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23975 */
23976
23977 /*
23978 ** The file suffix added to the data base filename in order to create the
23979 ** lock file.
23980 */
23981 #define DOTLOCK_SUFFIX ".lock"
23982
23983 /*
23984 ** This routine checks if there is a RESERVED lock held on the specified
23985 ** file by this or any other process. If such a lock is held, set *pResOut
23986 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23987 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23988 **
23989 ** In dotfile locking, either a lock exists or it does not.  So in this
23990 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
23991 ** is held on the file and false if the file is unlocked.
23992 */
23993 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23994   int rc = SQLITE_OK;
23995   int reserved = 0;
23996   unixFile *pFile = (unixFile*)id;
23997
23998   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23999   
24000   assert( pFile );
24001
24002   /* Check if a thread in this process holds such a lock */
24003   if( pFile->eFileLock>SHARED_LOCK ){
24004     /* Either this connection or some other connection in the same process
24005     ** holds a lock on the file.  No need to check further. */
24006     reserved = 1;
24007   }else{
24008     /* The lock is held if and only if the lockfile exists */
24009     const char *zLockFile = (const char*)pFile->lockingContext;
24010     reserved = access(zLockFile, 0)==0;
24011   }
24012   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24013   *pResOut = reserved;
24014   return rc;
24015 }
24016
24017 /*
24018 ** Lock the file with the lock specified by parameter eFileLock - one
24019 ** of the following:
24020 **
24021 **     (1) SHARED_LOCK
24022 **     (2) RESERVED_LOCK
24023 **     (3) PENDING_LOCK
24024 **     (4) EXCLUSIVE_LOCK
24025 **
24026 ** Sometimes when requesting one lock state, additional lock states
24027 ** are inserted in between.  The locking might fail on one of the later
24028 ** transitions leaving the lock state different from what it started but
24029 ** still short of its goal.  The following chart shows the allowed
24030 ** transitions and the inserted intermediate states:
24031 **
24032 **    UNLOCKED -> SHARED
24033 **    SHARED -> RESERVED
24034 **    SHARED -> (PENDING) -> EXCLUSIVE
24035 **    RESERVED -> (PENDING) -> EXCLUSIVE
24036 **    PENDING -> EXCLUSIVE
24037 **
24038 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24039 ** routine to lower a locking level.
24040 **
24041 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24042 ** But we track the other locking levels internally.
24043 */
24044 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24045   unixFile *pFile = (unixFile*)id;
24046   int fd;
24047   char *zLockFile = (char *)pFile->lockingContext;
24048   int rc = SQLITE_OK;
24049
24050
24051   /* If we have any lock, then the lock file already exists.  All we have
24052   ** to do is adjust our internal record of the lock level.
24053   */
24054   if( pFile->eFileLock > NO_LOCK ){
24055     pFile->eFileLock = eFileLock;
24056 #if !OS_VXWORKS
24057     /* Always update the timestamp on the old file */
24058     utimes(zLockFile, NULL);
24059 #endif
24060     return SQLITE_OK;
24061   }
24062   
24063   /* grab an exclusive lock */
24064   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24065   if( fd<0 ){
24066     /* failed to open/create the file, someone else may have stolen the lock */
24067     int tErrno = errno;
24068     if( EEXIST == tErrno ){
24069       rc = SQLITE_BUSY;
24070     } else {
24071       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24072       if( IS_LOCK_ERROR(rc) ){
24073         pFile->lastErrno = tErrno;
24074       }
24075     }
24076     return rc;
24077   } 
24078   if( close(fd) ){
24079     pFile->lastErrno = errno;
24080     rc = SQLITE_IOERR_CLOSE;
24081   }
24082   
24083   /* got it, set the type and return ok */
24084   pFile->eFileLock = eFileLock;
24085   return rc;
24086 }
24087
24088 /*
24089 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24090 ** must be either NO_LOCK or SHARED_LOCK.
24091 **
24092 ** If the locking level of the file descriptor is already at or below
24093 ** the requested locking level, this routine is a no-op.
24094 **
24095 ** When the locking level reaches NO_LOCK, delete the lock file.
24096 */
24097 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24098   unixFile *pFile = (unixFile*)id;
24099   char *zLockFile = (char *)pFile->lockingContext;
24100
24101   assert( pFile );
24102   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24103            pFile->eFileLock, getpid()));
24104   assert( eFileLock<=SHARED_LOCK );
24105   
24106   /* no-op if possible */
24107   if( pFile->eFileLock==eFileLock ){
24108     return SQLITE_OK;
24109   }
24110
24111   /* To downgrade to shared, simply update our internal notion of the
24112   ** lock state.  No need to mess with the file on disk.
24113   */
24114   if( eFileLock==SHARED_LOCK ){
24115     pFile->eFileLock = SHARED_LOCK;
24116     return SQLITE_OK;
24117   }
24118   
24119   /* To fully unlock the database, delete the lock file */
24120   assert( eFileLock==NO_LOCK );
24121   if( unlink(zLockFile) ){
24122     int rc = 0;
24123     int tErrno = errno;
24124     if( ENOENT != tErrno ){
24125       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24126     }
24127     if( IS_LOCK_ERROR(rc) ){
24128       pFile->lastErrno = tErrno;
24129     }
24130     return rc; 
24131   }
24132   pFile->eFileLock = NO_LOCK;
24133   return SQLITE_OK;
24134 }
24135
24136 /*
24137 ** Close a file.  Make sure the lock has been released before closing.
24138 */
24139 static int dotlockClose(sqlite3_file *id) {
24140   int rc;
24141   if( id ){
24142     unixFile *pFile = (unixFile*)id;
24143     dotlockUnlock(id, NO_LOCK);
24144     sqlite3_free(pFile->lockingContext);
24145   }
24146   rc = closeUnixFile(id);
24147   return rc;
24148 }
24149 /****************** End of the dot-file lock implementation *******************
24150 ******************************************************************************/
24151
24152 /******************************************************************************
24153 ************************** Begin flock Locking ********************************
24154 **
24155 ** Use the flock() system call to do file locking.
24156 **
24157 ** flock() locking is like dot-file locking in that the various
24158 ** fine-grain locking levels supported by SQLite are collapsed into
24159 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24160 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24161 ** still works when you do this, but concurrency is reduced since
24162 ** only a single process can be reading the database at a time.
24163 **
24164 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24165 ** compiling for VXWORKS.
24166 */
24167 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24168
24169 /*
24170 ** This routine checks if there is a RESERVED lock held on the specified
24171 ** file by this or any other process. If such a lock is held, set *pResOut
24172 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24173 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24174 */
24175 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24176   int rc = SQLITE_OK;
24177   int reserved = 0;
24178   unixFile *pFile = (unixFile*)id;
24179   
24180   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24181   
24182   assert( pFile );
24183   
24184   /* Check if a thread in this process holds such a lock */
24185   if( pFile->eFileLock>SHARED_LOCK ){
24186     reserved = 1;
24187   }
24188   
24189   /* Otherwise see if some other process holds it. */
24190   if( !reserved ){
24191     /* attempt to get the lock */
24192     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24193     if( !lrc ){
24194       /* got the lock, unlock it */
24195       lrc = flock(pFile->h, LOCK_UN);
24196       if ( lrc ) {
24197         int tErrno = errno;
24198         /* unlock failed with an error */
24199         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24200         if( IS_LOCK_ERROR(lrc) ){
24201           pFile->lastErrno = tErrno;
24202           rc = lrc;
24203         }
24204       }
24205     } else {
24206       int tErrno = errno;
24207       reserved = 1;
24208       /* someone else might have it reserved */
24209       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24210       if( IS_LOCK_ERROR(lrc) ){
24211         pFile->lastErrno = tErrno;
24212         rc = lrc;
24213       }
24214     }
24215   }
24216   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24217
24218 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24219   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24220     rc = SQLITE_OK;
24221     reserved=1;
24222   }
24223 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24224   *pResOut = reserved;
24225   return rc;
24226 }
24227
24228 /*
24229 ** Lock the file with the lock specified by parameter eFileLock - one
24230 ** of the following:
24231 **
24232 **     (1) SHARED_LOCK
24233 **     (2) RESERVED_LOCK
24234 **     (3) PENDING_LOCK
24235 **     (4) EXCLUSIVE_LOCK
24236 **
24237 ** Sometimes when requesting one lock state, additional lock states
24238 ** are inserted in between.  The locking might fail on one of the later
24239 ** transitions leaving the lock state different from what it started but
24240 ** still short of its goal.  The following chart shows the allowed
24241 ** transitions and the inserted intermediate states:
24242 **
24243 **    UNLOCKED -> SHARED
24244 **    SHARED -> RESERVED
24245 **    SHARED -> (PENDING) -> EXCLUSIVE
24246 **    RESERVED -> (PENDING) -> EXCLUSIVE
24247 **    PENDING -> EXCLUSIVE
24248 **
24249 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24250 ** lock states in the sqlite3_file structure, but all locks SHARED or
24251 ** above are really EXCLUSIVE locks and exclude all other processes from
24252 ** access the file.
24253 **
24254 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24255 ** routine to lower a locking level.
24256 */
24257 static int flockLock(sqlite3_file *id, int eFileLock) {
24258   int rc = SQLITE_OK;
24259   unixFile *pFile = (unixFile*)id;
24260
24261   assert( pFile );
24262
24263   /* if we already have a lock, it is exclusive.  
24264   ** Just adjust level and punt on outta here. */
24265   if (pFile->eFileLock > NO_LOCK) {
24266     pFile->eFileLock = eFileLock;
24267     return SQLITE_OK;
24268   }
24269   
24270   /* grab an exclusive lock */
24271   
24272   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24273     int tErrno = errno;
24274     /* didn't get, must be busy */
24275     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24276     if( IS_LOCK_ERROR(rc) ){
24277       pFile->lastErrno = tErrno;
24278     }
24279   } else {
24280     /* got it, set the type and return ok */
24281     pFile->eFileLock = eFileLock;
24282   }
24283   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24284            rc==SQLITE_OK ? "ok" : "failed"));
24285 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24286   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24287     rc = SQLITE_BUSY;
24288   }
24289 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24290   return rc;
24291 }
24292
24293
24294 /*
24295 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24296 ** must be either NO_LOCK or SHARED_LOCK.
24297 **
24298 ** If the locking level of the file descriptor is already at or below
24299 ** the requested locking level, this routine is a no-op.
24300 */
24301 static int flockUnlock(sqlite3_file *id, int eFileLock) {
24302   unixFile *pFile = (unixFile*)id;
24303   
24304   assert( pFile );
24305   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24306            pFile->eFileLock, getpid()));
24307   assert( eFileLock<=SHARED_LOCK );
24308   
24309   /* no-op if possible */
24310   if( pFile->eFileLock==eFileLock ){
24311     return SQLITE_OK;
24312   }
24313   
24314   /* shared can just be set because we always have an exclusive */
24315   if (eFileLock==SHARED_LOCK) {
24316     pFile->eFileLock = eFileLock;
24317     return SQLITE_OK;
24318   }
24319   
24320   /* no, really, unlock. */
24321   int rc = flock(pFile->h, LOCK_UN);
24322   if (rc) {
24323     int r, tErrno = errno;
24324     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24325     if( IS_LOCK_ERROR(r) ){
24326       pFile->lastErrno = tErrno;
24327     }
24328 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24329     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24330       r = SQLITE_BUSY;
24331     }
24332 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24333     
24334     return r;
24335   } else {
24336     pFile->eFileLock = NO_LOCK;
24337     return SQLITE_OK;
24338   }
24339 }
24340
24341 /*
24342 ** Close a file.
24343 */
24344 static int flockClose(sqlite3_file *id) {
24345   if( id ){
24346     flockUnlock(id, NO_LOCK);
24347   }
24348   return closeUnixFile(id);
24349 }
24350
24351 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24352
24353 /******************* End of the flock lock implementation *********************
24354 ******************************************************************************/
24355
24356 /******************************************************************************
24357 ************************ Begin Named Semaphore Locking ************************
24358 **
24359 ** Named semaphore locking is only supported on VxWorks.
24360 **
24361 ** Semaphore locking is like dot-lock and flock in that it really only
24362 ** supports EXCLUSIVE locking.  Only a single process can read or write
24363 ** the database file at a time.  This reduces potential concurrency, but
24364 ** makes the lock implementation much easier.
24365 */
24366 #if OS_VXWORKS
24367
24368 /*
24369 ** This routine checks if there is a RESERVED lock held on the specified
24370 ** file by this or any other process. If such a lock is held, set *pResOut
24371 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24372 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24373 */
24374 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24375   int rc = SQLITE_OK;
24376   int reserved = 0;
24377   unixFile *pFile = (unixFile*)id;
24378
24379   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24380   
24381   assert( pFile );
24382
24383   /* Check if a thread in this process holds such a lock */
24384   if( pFile->eFileLock>SHARED_LOCK ){
24385     reserved = 1;
24386   }
24387   
24388   /* Otherwise see if some other process holds it. */
24389   if( !reserved ){
24390     sem_t *pSem = pFile->pInode->pSem;
24391     struct stat statBuf;
24392
24393     if( sem_trywait(pSem)==-1 ){
24394       int tErrno = errno;
24395       if( EAGAIN != tErrno ){
24396         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24397         pFile->lastErrno = tErrno;
24398       } else {
24399         /* someone else has the lock when we are in NO_LOCK */
24400         reserved = (pFile->eFileLock < SHARED_LOCK);
24401       }
24402     }else{
24403       /* we could have it if we want it */
24404       sem_post(pSem);
24405     }
24406   }
24407   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24408
24409   *pResOut = reserved;
24410   return rc;
24411 }
24412
24413 /*
24414 ** Lock the file with the lock specified by parameter eFileLock - one
24415 ** of the following:
24416 **
24417 **     (1) SHARED_LOCK
24418 **     (2) RESERVED_LOCK
24419 **     (3) PENDING_LOCK
24420 **     (4) EXCLUSIVE_LOCK
24421 **
24422 ** Sometimes when requesting one lock state, additional lock states
24423 ** are inserted in between.  The locking might fail on one of the later
24424 ** transitions leaving the lock state different from what it started but
24425 ** still short of its goal.  The following chart shows the allowed
24426 ** transitions and the inserted intermediate states:
24427 **
24428 **    UNLOCKED -> SHARED
24429 **    SHARED -> RESERVED
24430 **    SHARED -> (PENDING) -> EXCLUSIVE
24431 **    RESERVED -> (PENDING) -> EXCLUSIVE
24432 **    PENDING -> EXCLUSIVE
24433 **
24434 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24435 ** lock states in the sqlite3_file structure, but all locks SHARED or
24436 ** above are really EXCLUSIVE locks and exclude all other processes from
24437 ** access the file.
24438 **
24439 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24440 ** routine to lower a locking level.
24441 */
24442 static int semLock(sqlite3_file *id, int eFileLock) {
24443   unixFile *pFile = (unixFile*)id;
24444   int fd;
24445   sem_t *pSem = pFile->pInode->pSem;
24446   int rc = SQLITE_OK;
24447
24448   /* if we already have a lock, it is exclusive.  
24449   ** Just adjust level and punt on outta here. */
24450   if (pFile->eFileLock > NO_LOCK) {
24451     pFile->eFileLock = eFileLock;
24452     rc = SQLITE_OK;
24453     goto sem_end_lock;
24454   }
24455   
24456   /* lock semaphore now but bail out when already locked. */
24457   if( sem_trywait(pSem)==-1 ){
24458     rc = SQLITE_BUSY;
24459     goto sem_end_lock;
24460   }
24461
24462   /* got it, set the type and return ok */
24463   pFile->eFileLock = eFileLock;
24464
24465  sem_end_lock:
24466   return rc;
24467 }
24468
24469 /*
24470 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24471 ** must be either NO_LOCK or SHARED_LOCK.
24472 **
24473 ** If the locking level of the file descriptor is already at or below
24474 ** the requested locking level, this routine is a no-op.
24475 */
24476 static int semUnlock(sqlite3_file *id, int eFileLock) {
24477   unixFile *pFile = (unixFile*)id;
24478   sem_t *pSem = pFile->pInode->pSem;
24479
24480   assert( pFile );
24481   assert( pSem );
24482   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24483            pFile->eFileLock, getpid()));
24484   assert( eFileLock<=SHARED_LOCK );
24485   
24486   /* no-op if possible */
24487   if( pFile->eFileLock==eFileLock ){
24488     return SQLITE_OK;
24489   }
24490   
24491   /* shared can just be set because we always have an exclusive */
24492   if (eFileLock==SHARED_LOCK) {
24493     pFile->eFileLock = eFileLock;
24494     return SQLITE_OK;
24495   }
24496   
24497   /* no, really unlock. */
24498   if ( sem_post(pSem)==-1 ) {
24499     int rc, tErrno = errno;
24500     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24501     if( IS_LOCK_ERROR(rc) ){
24502       pFile->lastErrno = tErrno;
24503     }
24504     return rc; 
24505   }
24506   pFile->eFileLock = NO_LOCK;
24507   return SQLITE_OK;
24508 }
24509
24510 /*
24511  ** Close a file.
24512  */
24513 static int semClose(sqlite3_file *id) {
24514   if( id ){
24515     unixFile *pFile = (unixFile*)id;
24516     semUnlock(id, NO_LOCK);
24517     assert( pFile );
24518     unixEnterMutex();
24519     releaseInodeInfo(pFile);
24520     unixLeaveMutex();
24521     closeUnixFile(id);
24522   }
24523   return SQLITE_OK;
24524 }
24525
24526 #endif /* OS_VXWORKS */
24527 /*
24528 ** Named semaphore locking is only available on VxWorks.
24529 **
24530 *************** End of the named semaphore lock implementation ****************
24531 ******************************************************************************/
24532
24533
24534 /******************************************************************************
24535 *************************** Begin AFP Locking *********************************
24536 **
24537 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24538 ** on Apple Macintosh computers - both OS9 and OSX.
24539 **
24540 ** Third-party implementations of AFP are available.  But this code here
24541 ** only works on OSX.
24542 */
24543
24544 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24545 /*
24546 ** The afpLockingContext structure contains all afp lock specific state
24547 */
24548 typedef struct afpLockingContext afpLockingContext;
24549 struct afpLockingContext {
24550   int reserved;
24551   const char *dbPath;             /* Name of the open file */
24552 };
24553
24554 struct ByteRangeLockPB2
24555 {
24556   unsigned long long offset;        /* offset to first byte to lock */
24557   unsigned long long length;        /* nbr of bytes to lock */
24558   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24559   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24560   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24561   int fd;                           /* file desc to assoc this lock with */
24562 };
24563
24564 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24565
24566 /*
24567 ** This is a utility for setting or clearing a bit-range lock on an
24568 ** AFP filesystem.
24569 ** 
24570 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24571 */
24572 static int afpSetLock(
24573   const char *path,              /* Name of the file to be locked or unlocked */
24574   unixFile *pFile,               /* Open file descriptor on path */
24575   unsigned long long offset,     /* First byte to be locked */
24576   unsigned long long length,     /* Number of bytes to lock */
24577   int setLockFlag                /* True to set lock.  False to clear lock */
24578 ){
24579   struct ByteRangeLockPB2 pb;
24580   int err;
24581   
24582   pb.unLockFlag = setLockFlag ? 0 : 1;
24583   pb.startEndFlag = 0;
24584   pb.offset = offset;
24585   pb.length = length; 
24586   pb.fd = pFile->h;
24587   
24588   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24589     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24590     offset, length));
24591   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24592   if ( err==-1 ) {
24593     int rc;
24594     int tErrno = errno;
24595     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24596              path, tErrno, strerror(tErrno)));
24597 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24598     rc = SQLITE_BUSY;
24599 #else
24600     rc = sqliteErrorFromPosixError(tErrno,
24601                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24602 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24603     if( IS_LOCK_ERROR(rc) ){
24604       pFile->lastErrno = tErrno;
24605     }
24606     return rc;
24607   } else {
24608     return SQLITE_OK;
24609   }
24610 }
24611
24612 /*
24613 ** This routine checks if there is a RESERVED lock held on the specified
24614 ** file by this or any other process. If such a lock is held, set *pResOut
24615 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24616 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24617 */
24618 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24619   int rc = SQLITE_OK;
24620   int reserved = 0;
24621   unixFile *pFile = (unixFile*)id;
24622   
24623   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24624   
24625   assert( pFile );
24626   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24627   if( context->reserved ){
24628     *pResOut = 1;
24629     return SQLITE_OK;
24630   }
24631   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24632   
24633   /* Check if a thread in this process holds such a lock */
24634   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24635     reserved = 1;
24636   }
24637   
24638   /* Otherwise see if some other process holds it.
24639    */
24640   if( !reserved ){
24641     /* lock the RESERVED byte */
24642     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
24643     if( SQLITE_OK==lrc ){
24644       /* if we succeeded in taking the reserved lock, unlock it to restore
24645       ** the original state */
24646       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24647     } else {
24648       /* if we failed to get the lock then someone else must have it */
24649       reserved = 1;
24650     }
24651     if( IS_LOCK_ERROR(lrc) ){
24652       rc=lrc;
24653     }
24654   }
24655   
24656   unixLeaveMutex();
24657   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
24658   
24659   *pResOut = reserved;
24660   return rc;
24661 }
24662
24663 /*
24664 ** Lock the file with the lock specified by parameter eFileLock - one
24665 ** of the following:
24666 **
24667 **     (1) SHARED_LOCK
24668 **     (2) RESERVED_LOCK
24669 **     (3) PENDING_LOCK
24670 **     (4) EXCLUSIVE_LOCK
24671 **
24672 ** Sometimes when requesting one lock state, additional lock states
24673 ** are inserted in between.  The locking might fail on one of the later
24674 ** transitions leaving the lock state different from what it started but
24675 ** still short of its goal.  The following chart shows the allowed
24676 ** transitions and the inserted intermediate states:
24677 **
24678 **    UNLOCKED -> SHARED
24679 **    SHARED -> RESERVED
24680 **    SHARED -> (PENDING) -> EXCLUSIVE
24681 **    RESERVED -> (PENDING) -> EXCLUSIVE
24682 **    PENDING -> EXCLUSIVE
24683 **
24684 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24685 ** routine to lower a locking level.
24686 */
24687 static int afpLock(sqlite3_file *id, int eFileLock){
24688   int rc = SQLITE_OK;
24689   unixFile *pFile = (unixFile*)id;
24690   unixInodeInfo *pInode = pFile->pInode;
24691   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24692   
24693   assert( pFile );
24694   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24695            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24696            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24697
24698   /* If there is already a lock of this type or more restrictive on the
24699   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24700   ** unixEnterMutex() hasn't been called yet.
24701   */
24702   if( pFile->eFileLock>=eFileLock ){
24703     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24704            azFileLock(eFileLock)));
24705     return SQLITE_OK;
24706   }
24707
24708   /* Make sure the locking sequence is correct
24709   **  (1) We never move from unlocked to anything higher than shared lock.
24710   **  (2) SQLite never explicitly requests a pendig lock.
24711   **  (3) A shared lock is always held when a reserve lock is requested.
24712   */
24713   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24714   assert( eFileLock!=PENDING_LOCK );
24715   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24716   
24717   /* This mutex is needed because pFile->pInode is shared across threads
24718   */
24719   unixEnterMutex();
24720   pInode = pFile->pInode;
24721
24722   /* If some thread using this PID has a lock via a different unixFile*
24723   ** handle that precludes the requested lock, return BUSY.
24724   */
24725   if( (pFile->eFileLock!=pInode->eFileLock && 
24726        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24727      ){
24728     rc = SQLITE_BUSY;
24729     goto afp_end_lock;
24730   }
24731   
24732   /* If a SHARED lock is requested, and some thread using this PID already
24733   ** has a SHARED or RESERVED lock, then increment reference counts and
24734   ** return SQLITE_OK.
24735   */
24736   if( eFileLock==SHARED_LOCK && 
24737      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24738     assert( eFileLock==SHARED_LOCK );
24739     assert( pFile->eFileLock==0 );
24740     assert( pInode->nShared>0 );
24741     pFile->eFileLock = SHARED_LOCK;
24742     pInode->nShared++;
24743     pInode->nLock++;
24744     goto afp_end_lock;
24745   }
24746     
24747   /* A PENDING lock is needed before acquiring a SHARED lock and before
24748   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24749   ** be released.
24750   */
24751   if( eFileLock==SHARED_LOCK 
24752       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24753   ){
24754     int failed;
24755     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24756     if (failed) {
24757       rc = failed;
24758       goto afp_end_lock;
24759     }
24760   }
24761   
24762   /* If control gets to this point, then actually go ahead and make
24763   ** operating system calls for the specified lock.
24764   */
24765   if( eFileLock==SHARED_LOCK ){
24766     int lrc1, lrc2, lrc1Errno;
24767     long lk, mask;
24768     
24769     assert( pInode->nShared==0 );
24770     assert( pInode->eFileLock==0 );
24771         
24772     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24773     /* Now get the read-lock SHARED_LOCK */
24774     /* note that the quality of the randomness doesn't matter that much */
24775     lk = random(); 
24776     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24777     lrc1 = afpSetLock(context->dbPath, pFile, 
24778           SHARED_FIRST+pInode->sharedByte, 1, 1);
24779     if( IS_LOCK_ERROR(lrc1) ){
24780       lrc1Errno = pFile->lastErrno;
24781     }
24782     /* Drop the temporary PENDING lock */
24783     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24784     
24785     if( IS_LOCK_ERROR(lrc1) ) {
24786       pFile->lastErrno = lrc1Errno;
24787       rc = lrc1;
24788       goto afp_end_lock;
24789     } else if( IS_LOCK_ERROR(lrc2) ){
24790       rc = lrc2;
24791       goto afp_end_lock;
24792     } else if( lrc1 != SQLITE_OK ) {
24793       rc = lrc1;
24794     } else {
24795       pFile->eFileLock = SHARED_LOCK;
24796       pInode->nLock++;
24797       pInode->nShared = 1;
24798     }
24799   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24800     /* We are trying for an exclusive lock but another thread in this
24801      ** same process is still holding a shared lock. */
24802     rc = SQLITE_BUSY;
24803   }else{
24804     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24805     ** assumed that there is a SHARED or greater lock on the file
24806     ** already.
24807     */
24808     int failed = 0;
24809     assert( 0!=pFile->eFileLock );
24810     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
24811         /* Acquire a RESERVED lock */
24812         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24813       if( !failed ){
24814         context->reserved = 1;
24815       }
24816     }
24817     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
24818       /* Acquire an EXCLUSIVE lock */
24819         
24820       /* Remove the shared lock before trying the range.  we'll need to 
24821       ** reestablish the shared lock if we can't get the  afpUnlock
24822       */
24823       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24824                          pInode->sharedByte, 1, 0)) ){
24825         int failed2 = SQLITE_OK;
24826         /* now attemmpt to get the exclusive lock range */
24827         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24828                                SHARED_SIZE, 1);
24829         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24830                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
24831           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24832           ** a critical I/O error
24833           */
24834           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
24835                SQLITE_IOERR_LOCK;
24836           goto afp_end_lock;
24837         } 
24838       }else{
24839         rc = failed; 
24840       }
24841     }
24842     if( failed ){
24843       rc = failed;
24844     }
24845   }
24846   
24847   if( rc==SQLITE_OK ){
24848     pFile->eFileLock = eFileLock;
24849     pInode->eFileLock = eFileLock;
24850   }else if( eFileLock==EXCLUSIVE_LOCK ){
24851     pFile->eFileLock = PENDING_LOCK;
24852     pInode->eFileLock = PENDING_LOCK;
24853   }
24854   
24855 afp_end_lock:
24856   unixLeaveMutex();
24857   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
24858          rc==SQLITE_OK ? "ok" : "failed"));
24859   return rc;
24860 }
24861
24862 /*
24863 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24864 ** must be either NO_LOCK or SHARED_LOCK.
24865 **
24866 ** If the locking level of the file descriptor is already at or below
24867 ** the requested locking level, this routine is a no-op.
24868 */
24869 static int afpUnlock(sqlite3_file *id, int eFileLock) {
24870   int rc = SQLITE_OK;
24871   unixFile *pFile = (unixFile*)id;
24872   unixInodeInfo *pInode;
24873   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24874   int skipShared = 0;
24875 #ifdef SQLITE_TEST
24876   int h = pFile->h;
24877 #endif
24878
24879   assert( pFile );
24880   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
24881            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24882            getpid()));
24883
24884   assert( eFileLock<=SHARED_LOCK );
24885   if( pFile->eFileLock<=eFileLock ){
24886     return SQLITE_OK;
24887   }
24888   unixEnterMutex();
24889   pInode = pFile->pInode;
24890   assert( pInode->nShared!=0 );
24891   if( pFile->eFileLock>SHARED_LOCK ){
24892     assert( pInode->eFileLock==pFile->eFileLock );
24893     SimulateIOErrorBenign(1);
24894     SimulateIOError( h=(-1) )
24895     SimulateIOErrorBenign(0);
24896     
24897 #ifndef NDEBUG
24898     /* When reducing a lock such that other processes can start
24899     ** reading the database file again, make sure that the
24900     ** transaction counter was updated if any part of the database
24901     ** file changed.  If the transaction counter is not updated,
24902     ** other connections to the same file might not realize that
24903     ** the file has changed and hence might not know to flush their
24904     ** cache.  The use of a stale cache can lead to database corruption.
24905     */
24906     assert( pFile->inNormalWrite==0
24907            || pFile->dbUpdate==0
24908            || pFile->transCntrChng==1 );
24909     pFile->inNormalWrite = 0;
24910 #endif
24911     
24912     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
24913       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24914       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
24915         /* only re-establish the shared lock if necessary */
24916         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24917         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
24918       } else {
24919         skipShared = 1;
24920       }
24921     }
24922     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
24923       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24924     } 
24925     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
24926       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24927       if( !rc ){ 
24928         context->reserved = 0; 
24929       }
24930     }
24931     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
24932       pInode->eFileLock = SHARED_LOCK;
24933     }
24934   }
24935   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
24936
24937     /* Decrement the shared lock counter.  Release the lock using an
24938     ** OS call only when all threads in this same process have released
24939     ** the lock.
24940     */
24941     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24942     pInode->nShared--;
24943     if( pInode->nShared==0 ){
24944       SimulateIOErrorBenign(1);
24945       SimulateIOError( h=(-1) )
24946       SimulateIOErrorBenign(0);
24947       if( !skipShared ){
24948         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
24949       }
24950       if( !rc ){
24951         pInode->eFileLock = NO_LOCK;
24952         pFile->eFileLock = NO_LOCK;
24953       }
24954     }
24955     if( rc==SQLITE_OK ){
24956       pInode->nLock--;
24957       assert( pInode->nLock>=0 );
24958       if( pInode->nLock==0 ){
24959         rc = closePendingFds(pFile);
24960       }
24961     }
24962   }
24963   
24964   unixLeaveMutex();
24965   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24966   return rc;
24967 }
24968
24969 /*
24970 ** Close a file & cleanup AFP specific locking context 
24971 */
24972 static int afpClose(sqlite3_file *id) {
24973   int rc = SQLITE_OK;
24974   if( id ){
24975     unixFile *pFile = (unixFile*)id;
24976     afpUnlock(id, NO_LOCK);
24977     unixEnterMutex();
24978     if( pFile->pInode && pFile->pInode->nLock ){
24979       /* If there are outstanding locks, do not actually close the file just
24980       ** yet because that would clear those locks.  Instead, add the file
24981       ** descriptor to pInode->aPending.  It will be automatically closed when
24982       ** the last lock is cleared.
24983       */
24984       setPendingFd(pFile);
24985     }
24986     releaseInodeInfo(pFile);
24987     sqlite3_free(pFile->lockingContext);
24988     rc = closeUnixFile(id);
24989     unixLeaveMutex();
24990   }
24991   return rc;
24992 }
24993
24994 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24995 /*
24996 ** The code above is the AFP lock implementation.  The code is specific
24997 ** to MacOSX and does not work on other unix platforms.  No alternative
24998 ** is available.  If you don't compile for a mac, then the "unix-afp"
24999 ** VFS is not available.
25000 **
25001 ********************* End of the AFP lock implementation **********************
25002 ******************************************************************************/
25003
25004 /******************************************************************************
25005 *************************** Begin NFS Locking ********************************/
25006
25007 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25008 /*
25009  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25010  ** must be either NO_LOCK or SHARED_LOCK.
25011  **
25012  ** If the locking level of the file descriptor is already at or below
25013  ** the requested locking level, this routine is a no-op.
25014  */
25015 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25016   return _posixUnlock(id, eFileLock, 1);
25017 }
25018
25019 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25020 /*
25021 ** The code above is the NFS lock implementation.  The code is specific
25022 ** to MacOSX and does not work on other unix platforms.  No alternative
25023 ** is available.  
25024 **
25025 ********************* End of the NFS lock implementation **********************
25026 ******************************************************************************/
25027
25028 /******************************************************************************
25029 **************** Non-locking sqlite3_file methods *****************************
25030 **
25031 ** The next division contains implementations for all methods of the 
25032 ** sqlite3_file object other than the locking methods.  The locking
25033 ** methods were defined in divisions above (one locking method per
25034 ** division).  Those methods that are common to all locking modes
25035 ** are gather together into this division.
25036 */
25037
25038 /*
25039 ** Seek to the offset passed as the second argument, then read cnt 
25040 ** bytes into pBuf. Return the number of bytes actually read.
25041 **
25042 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25043 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25044 ** one system to another.  Since SQLite does not define USE_PREAD
25045 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25046 ** See tickets #2741 and #2681.
25047 **
25048 ** To avoid stomping the errno value on a failed read the lastErrno value
25049 ** is set before returning.
25050 */
25051 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25052   int got;
25053 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25054   i64 newOffset;
25055 #endif
25056   TIMER_START;
25057 #if defined(USE_PREAD)
25058   got = pread(id->h, pBuf, cnt, offset);
25059   SimulateIOError( got = -1 );
25060 #elif defined(USE_PREAD64)
25061   got = pread64(id->h, pBuf, cnt, offset);
25062   SimulateIOError( got = -1 );
25063 #else
25064   newOffset = lseek(id->h, offset, SEEK_SET);
25065   SimulateIOError( newOffset-- );
25066   if( newOffset!=offset ){
25067     if( newOffset == -1 ){
25068       ((unixFile*)id)->lastErrno = errno;
25069     }else{
25070       ((unixFile*)id)->lastErrno = 0;                   
25071     }
25072     return -1;
25073   }
25074   got = read(id->h, pBuf, cnt);
25075 #endif
25076   TIMER_END;
25077   if( got<0 ){
25078     ((unixFile*)id)->lastErrno = errno;
25079   }
25080   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25081   return got;
25082 }
25083
25084 /*
25085 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25086 ** bytes were read successfully and SQLITE_IOERR if anything goes
25087 ** wrong.
25088 */
25089 static int unixRead(
25090   sqlite3_file *id, 
25091   void *pBuf, 
25092   int amt,
25093   sqlite3_int64 offset
25094 ){
25095   unixFile *pFile = (unixFile *)id;
25096   int got;
25097   assert( id );
25098
25099   /* If this is a database file (not a journal, master-journal or temp
25100   ** file), the bytes in the locking range should never be read or written. */
25101 #if 0
25102   assert( pFile->pUnused==0
25103        || offset>=PENDING_BYTE+512
25104        || offset+amt<=PENDING_BYTE 
25105   );
25106 #endif
25107
25108   got = seekAndRead(pFile, offset, pBuf, amt);
25109   if( got==amt ){
25110     return SQLITE_OK;
25111   }else if( got<0 ){
25112     /* lastErrno set by seekAndRead */
25113     return SQLITE_IOERR_READ;
25114   }else{
25115     pFile->lastErrno = 0; /* not a system error */
25116     /* Unread parts of the buffer must be zero-filled */
25117     memset(&((char*)pBuf)[got], 0, amt-got);
25118     return SQLITE_IOERR_SHORT_READ;
25119   }
25120 }
25121
25122 /*
25123 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25124 ** Return the number of bytes actually read.  Update the offset.
25125 **
25126 ** To avoid stomping the errno value on a failed write the lastErrno value
25127 ** is set before returning.
25128 */
25129 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25130   int got;
25131 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25132   i64 newOffset;
25133 #endif
25134   TIMER_START;
25135 #if defined(USE_PREAD)
25136   got = pwrite(id->h, pBuf, cnt, offset);
25137 #elif defined(USE_PREAD64)
25138   got = pwrite64(id->h, pBuf, cnt, offset);
25139 #else
25140   newOffset = lseek(id->h, offset, SEEK_SET);
25141   if( newOffset!=offset ){
25142     if( newOffset == -1 ){
25143       ((unixFile*)id)->lastErrno = errno;
25144     }else{
25145       ((unixFile*)id)->lastErrno = 0;                   
25146     }
25147     return -1;
25148   }
25149   got = write(id->h, pBuf, cnt);
25150 #endif
25151   TIMER_END;
25152   if( got<0 ){
25153     ((unixFile*)id)->lastErrno = errno;
25154   }
25155
25156   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25157   return got;
25158 }
25159
25160
25161 /*
25162 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25163 ** or some other error code on failure.
25164 */
25165 static int unixWrite(
25166   sqlite3_file *id, 
25167   const void *pBuf, 
25168   int amt,
25169   sqlite3_int64 offset 
25170 ){
25171   unixFile *pFile = (unixFile*)id;
25172   int wrote = 0;
25173   assert( id );
25174   assert( amt>0 );
25175
25176   /* If this is a database file (not a journal, master-journal or temp
25177   ** file), the bytes in the locking range should never be read or written. */
25178 #if 0
25179   assert( pFile->pUnused==0
25180        || offset>=PENDING_BYTE+512
25181        || offset+amt<=PENDING_BYTE 
25182   );
25183 #endif
25184
25185 #ifndef NDEBUG
25186   /* If we are doing a normal write to a database file (as opposed to
25187   ** doing a hot-journal rollback or a write to some file other than a
25188   ** normal database file) then record the fact that the database
25189   ** has changed.  If the transaction counter is modified, record that
25190   ** fact too.
25191   */
25192   if( pFile->inNormalWrite ){
25193     pFile->dbUpdate = 1;  /* The database has been modified */
25194     if( offset<=24 && offset+amt>=27 ){
25195       int rc;
25196       char oldCntr[4];
25197       SimulateIOErrorBenign(1);
25198       rc = seekAndRead(pFile, 24, oldCntr, 4);
25199       SimulateIOErrorBenign(0);
25200       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25201         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25202       }
25203     }
25204   }
25205 #endif
25206
25207   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25208     amt -= wrote;
25209     offset += wrote;
25210     pBuf = &((char*)pBuf)[wrote];
25211   }
25212   SimulateIOError(( wrote=(-1), amt=1 ));
25213   SimulateDiskfullError(( wrote=0, amt=1 ));
25214   if( amt>0 ){
25215     if( wrote<0 ){
25216       /* lastErrno set by seekAndWrite */
25217       return SQLITE_IOERR_WRITE;
25218     }else{
25219       pFile->lastErrno = 0; /* not a system error */
25220       return SQLITE_FULL;
25221     }
25222   }
25223   return SQLITE_OK;
25224 }
25225
25226 #ifdef SQLITE_TEST
25227 /*
25228 ** Count the number of fullsyncs and normal syncs.  This is used to test
25229 ** that syncs and fullsyncs are occurring at the right times.
25230 */
25231 SQLITE_API int sqlite3_sync_count = 0;
25232 SQLITE_API int sqlite3_fullsync_count = 0;
25233 #endif
25234
25235 /*
25236 ** We do not trust systems to provide a working fdatasync().  Some do.
25237 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25238 ** If you know that your system does support fdatasync() correctly,
25239 ** then simply compile with -Dfdatasync=fdatasync
25240 */
25241 #if !defined(fdatasync) && !defined(__linux__)
25242 # define fdatasync fsync
25243 #endif
25244
25245 /*
25246 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25247 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25248 ** only available on Mac OS X.  But that could change.
25249 */
25250 #ifdef F_FULLFSYNC
25251 # define HAVE_FULLFSYNC 1
25252 #else
25253 # define HAVE_FULLFSYNC 0
25254 #endif
25255
25256
25257 /*
25258 ** The fsync() system call does not work as advertised on many
25259 ** unix systems.  The following procedure is an attempt to make
25260 ** it work better.
25261 **
25262 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25263 ** for testing when we want to run through the test suite quickly.
25264 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25265 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25266 ** or power failure will likely corrupt the database file.
25267 **
25268 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25269 ** The idea behind dataOnly is that it should only write the file content
25270 ** to disk, not the inode.  We only set dataOnly if the file size is 
25271 ** unchanged since the file size is part of the inode.  However, 
25272 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25273 ** file size has changed.  The only real difference between fdatasync()
25274 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25275 ** inode if the mtime or owner or other inode attributes have changed.
25276 ** We only care about the file size, not the other file attributes, so
25277 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25278 ** So, we always use fdatasync() if it is available, regardless of
25279 ** the value of the dataOnly flag.
25280 */
25281 static int full_fsync(int fd, int fullSync, int dataOnly){
25282   int rc;
25283
25284   /* The following "ifdef/elif/else/" block has the same structure as
25285   ** the one below. It is replicated here solely to avoid cluttering 
25286   ** up the real code with the UNUSED_PARAMETER() macros.
25287   */
25288 #ifdef SQLITE_NO_SYNC
25289   UNUSED_PARAMETER(fd);
25290   UNUSED_PARAMETER(fullSync);
25291   UNUSED_PARAMETER(dataOnly);
25292 #elif HAVE_FULLFSYNC
25293   UNUSED_PARAMETER(dataOnly);
25294 #else
25295   UNUSED_PARAMETER(fullSync);
25296   UNUSED_PARAMETER(dataOnly);
25297 #endif
25298
25299   /* Record the number of times that we do a normal fsync() and 
25300   ** FULLSYNC.  This is used during testing to verify that this procedure
25301   ** gets called with the correct arguments.
25302   */
25303 #ifdef SQLITE_TEST
25304   if( fullSync ) sqlite3_fullsync_count++;
25305   sqlite3_sync_count++;
25306 #endif
25307
25308   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25309   ** no-op
25310   */
25311 #ifdef SQLITE_NO_SYNC
25312   rc = SQLITE_OK;
25313 #elif HAVE_FULLFSYNC
25314   if( fullSync ){
25315     rc = fcntl(fd, F_FULLFSYNC, 0);
25316   }else{
25317     rc = 1;
25318   }
25319   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25320   ** It shouldn't be possible for fullfsync to fail on the local 
25321   ** file system (on OSX), so failure indicates that FULLFSYNC
25322   ** isn't supported for this file system. So, attempt an fsync 
25323   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25324   ** It'd be better to detect fullfsync support once and avoid 
25325   ** the fcntl call every time sync is called.
25326   */
25327   if( rc ) rc = fsync(fd);
25328
25329 #elif defined(__APPLE__)
25330   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25331   ** so currently we default to the macro that redefines fdatasync to fsync
25332   */
25333   rc = fsync(fd);
25334 #else 
25335   rc = fdatasync(fd);
25336 #if OS_VXWORKS
25337   if( rc==-1 && errno==ENOTSUP ){
25338     rc = fsync(fd);
25339   }
25340 #endif /* OS_VXWORKS */
25341 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25342
25343   if( OS_VXWORKS && rc!= -1 ){
25344     rc = 0;
25345   }
25346   return rc;
25347 }
25348
25349 /*
25350 ** Make sure all writes to a particular file are committed to disk.
25351 **
25352 ** If dataOnly==0 then both the file itself and its metadata (file
25353 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25354 ** file data is synced.
25355 **
25356 ** Under Unix, also make sure that the directory entry for the file
25357 ** has been created by fsync-ing the directory that contains the file.
25358 ** If we do not do this and we encounter a power failure, the directory
25359 ** entry for the journal might not exist after we reboot.  The next
25360 ** SQLite to access the file will not know that the journal exists (because
25361 ** the directory entry for the journal was never created) and the transaction
25362 ** will not roll back - possibly leading to database corruption.
25363 */
25364 static int unixSync(sqlite3_file *id, int flags){
25365   int rc;
25366   unixFile *pFile = (unixFile*)id;
25367
25368   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25369   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25370
25371   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25372   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25373       || (flags&0x0F)==SQLITE_SYNC_FULL
25374   );
25375
25376   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25377   ** line is to test that doing so does not cause any problems.
25378   */
25379   SimulateDiskfullError( return SQLITE_FULL );
25380
25381   assert( pFile );
25382   OSTRACE(("SYNC    %-3d\n", pFile->h));
25383   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25384   SimulateIOError( rc=1 );
25385   if( rc ){
25386     pFile->lastErrno = errno;
25387     return SQLITE_IOERR_FSYNC;
25388   }
25389   if( pFile->dirfd>=0 ){
25390     int err;
25391     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25392             HAVE_FULLFSYNC, isFullsync));
25393 #ifndef SQLITE_DISABLE_DIRSYNC
25394     /* The directory sync is only attempted if full_fsync is
25395     ** turned off or unavailable.  If a full_fsync occurred above,
25396     ** then the directory sync is superfluous.
25397     */
25398     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25399        /*
25400        ** We have received multiple reports of fsync() returning
25401        ** errors when applied to directories on certain file systems.
25402        ** A failed directory sync is not a big deal.  So it seems
25403        ** better to ignore the error.  Ticket #1657
25404        */
25405        /* pFile->lastErrno = errno; */
25406        /* return SQLITE_IOERR; */
25407     }
25408 #endif
25409     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25410     if( err==0 ){              /* directory when we are done */
25411       pFile->dirfd = -1;
25412     }else{
25413       pFile->lastErrno = errno;
25414       rc = SQLITE_IOERR_DIR_CLOSE;
25415     }
25416   }
25417   return rc;
25418 }
25419
25420 /*
25421 ** Truncate an open file to a specified size
25422 */
25423 static int unixTruncate(sqlite3_file *id, i64 nByte){
25424   int rc;
25425   assert( id );
25426   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25427   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25428   if( rc ){
25429     ((unixFile*)id)->lastErrno = errno;
25430     return SQLITE_IOERR_TRUNCATE;
25431   }else{
25432 #ifndef NDEBUG
25433     /* If we are doing a normal write to a database file (as opposed to
25434     ** doing a hot-journal rollback or a write to some file other than a
25435     ** normal database file) and we truncate the file to zero length,
25436     ** that effectively updates the change counter.  This might happen
25437     ** when restoring a database using the backup API from a zero-length
25438     ** source.
25439     */
25440     if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
25441       ((unixFile*)id)->transCntrChng = 1;
25442     }
25443 #endif
25444
25445     return SQLITE_OK;
25446   }
25447 }
25448
25449 /*
25450 ** Determine the current size of a file in bytes
25451 */
25452 static int unixFileSize(sqlite3_file *id, i64 *pSize){
25453   int rc;
25454   struct stat buf;
25455   assert( id );
25456   rc = fstat(((unixFile*)id)->h, &buf);
25457   SimulateIOError( rc=1 );
25458   if( rc!=0 ){
25459     ((unixFile*)id)->lastErrno = errno;
25460     return SQLITE_IOERR_FSTAT;
25461   }
25462   *pSize = buf.st_size;
25463
25464   /* When opening a zero-size database, the findInodeInfo() procedure
25465   ** writes a single byte into that file in order to work around a bug
25466   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25467   ** layers, we need to report this file size as zero even though it is
25468   ** really 1.   Ticket #3260.
25469   */
25470   if( *pSize==1 ) *pSize = 0;
25471
25472
25473   return SQLITE_OK;
25474 }
25475
25476 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25477 /*
25478 ** Handler for proxy-locking file-control verbs.  Defined below in the
25479 ** proxying locking division.
25480 */
25481 static int proxyFileControl(sqlite3_file*,int,void*);
25482 #endif
25483
25484
25485 /*
25486 ** Information and control of an open file handle.
25487 */
25488 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25489   switch( op ){
25490     case SQLITE_FCNTL_LOCKSTATE: {
25491       *(int*)pArg = ((unixFile*)id)->eFileLock;
25492       return SQLITE_OK;
25493     }
25494     case SQLITE_LAST_ERRNO: {
25495       *(int*)pArg = ((unixFile*)id)->lastErrno;
25496       return SQLITE_OK;
25497     }
25498     case SQLITE_FCNTL_SIZE_HINT: {
25499 #if 0 /* No performance advantage seen on Linux */
25500       sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
25501       unixFile *pFile = (unixFile*)id;
25502       ftruncate(pFile->h, szFile);
25503 #endif
25504       return SQLITE_OK;
25505     }
25506 #ifndef NDEBUG
25507     /* The pager calls this method to signal that it has done
25508     ** a rollback and that the database is therefore unchanged and
25509     ** it hence it is OK for the transaction change counter to be
25510     ** unchanged.
25511     */
25512     case SQLITE_FCNTL_DB_UNCHANGED: {
25513       ((unixFile*)id)->dbUpdate = 0;
25514       return SQLITE_OK;
25515     }
25516 #endif
25517 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25518     case SQLITE_SET_LOCKPROXYFILE:
25519     case SQLITE_GET_LOCKPROXYFILE: {
25520       return proxyFileControl(id,op,pArg);
25521     }
25522 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25523   }
25524   return SQLITE_ERROR;
25525 }
25526
25527 /*
25528 ** Return the sector size in bytes of the underlying block device for
25529 ** the specified file. This is almost always 512 bytes, but may be
25530 ** larger for some devices.
25531 **
25532 ** SQLite code assumes this function cannot fail. It also assumes that
25533 ** if two files are created in the same file-system directory (i.e.
25534 ** a database and its journal file) that the sector size will be the
25535 ** same for both.
25536 */
25537 static int unixSectorSize(sqlite3_file *NotUsed){
25538   UNUSED_PARAMETER(NotUsed);
25539   return SQLITE_DEFAULT_SECTOR_SIZE;
25540 }
25541
25542 /*
25543 ** Return the device characteristics for the file. This is always 0 for unix.
25544 */
25545 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25546   UNUSED_PARAMETER(NotUsed);
25547   return 0;
25548 }
25549
25550 #ifndef SQLITE_OMIT_WAL
25551
25552
25553 /*
25554 ** Object used to represent an shared memory buffer.  
25555 **
25556 ** When multiple threads all reference the same wal-index, each thread
25557 ** has its own unixShm object, but they all point to a single instance
25558 ** of this unixShmNode object.  In other words, each wal-index is opened
25559 ** only once per process.
25560 **
25561 ** Each unixShmNode object is connected to a single unixInodeInfo object.
25562 ** We could coalesce this object into unixInodeInfo, but that would mean
25563 ** every open file that does not use shared memory (in other words, most
25564 ** open files) would have to carry around this extra information.  So
25565 ** the unixInodeInfo object contains a pointer to this unixShmNode object
25566 ** and the unixShmNode object is created only when needed.
25567 **
25568 ** unixMutexHeld() must be true when creating or destroying
25569 ** this object or while reading or writing the following fields:
25570 **
25571 **      nRef
25572 **
25573 ** The following fields are read-only after the object is created:
25574 ** 
25575 **      fid
25576 **      zFilename
25577 **
25578 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
25579 ** unixMutexHeld() is true when reading or writing any other field
25580 ** in this structure.
25581 */
25582 struct unixShmNode {
25583   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
25584   sqlite3_mutex *mutex;      /* Mutex to access this object */
25585   char *zFilename;           /* Name of the mmapped file */
25586   int h;                     /* Open file descriptor */
25587   int szRegion;              /* Size of shared-memory regions */
25588   int nRegion;               /* Size of array apRegion */
25589   char **apRegion;           /* Array of mapped shared-memory regions */
25590   int nRef;                  /* Number of unixShm objects pointing to this */
25591   unixShm *pFirst;           /* All unixShm objects pointing to this */
25592 #ifdef SQLITE_DEBUG
25593   u8 exclMask;               /* Mask of exclusive locks held */
25594   u8 sharedMask;             /* Mask of shared locks held */
25595   u8 nextShmId;              /* Next available unixShm.id value */
25596 #endif
25597 };
25598
25599 /*
25600 ** Structure used internally by this VFS to record the state of an
25601 ** open shared memory connection.
25602 **
25603 ** The following fields are initialized when this object is created and
25604 ** are read-only thereafter:
25605 **
25606 **    unixShm.pFile
25607 **    unixShm.id
25608 **
25609 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
25610 ** while accessing any read/write fields.
25611 */
25612 struct unixShm {
25613   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
25614   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
25615   u8 hasMutex;               /* True if holding the unixShmNode mutex */
25616   u16 sharedMask;            /* Mask of shared locks held */
25617   u16 exclMask;              /* Mask of exclusive locks held */
25618 #ifdef SQLITE_DEBUG
25619   u8 id;                     /* Id of this connection within its unixShmNode */
25620 #endif
25621 };
25622
25623 /*
25624 ** Constants used for locking
25625 */
25626 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
25627 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
25628
25629 /*
25630 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
25631 **
25632 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
25633 ** otherwise.
25634 */
25635 static int unixShmSystemLock(
25636   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
25637   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
25638   int ofst,              /* First byte of the locking range */
25639   int n                  /* Number of bytes to lock */
25640 ){
25641   struct flock f;       /* The posix advisory locking structure */
25642   int rc = SQLITE_OK;   /* Result code form fcntl() */
25643
25644   /* Access to the unixShmNode object is serialized by the caller */
25645   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
25646
25647   /* Shared locks never span more than one byte */
25648   assert( n==1 || lockType!=F_RDLCK );
25649
25650   /* Locks are within range */
25651   assert( n>=1 && n<SQLITE_SHM_NLOCK );
25652
25653   /* Initialize the locking parameters */
25654   memset(&f, 0, sizeof(f));
25655   f.l_type = lockType;
25656   f.l_whence = SEEK_SET;
25657   f.l_start = ofst;
25658   f.l_len = n;
25659
25660   rc = fcntl(pShmNode->h, F_SETLK, &f);
25661   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
25662
25663   /* Update the global lock state and do debug tracing */
25664 #ifdef SQLITE_DEBUG
25665   { u16 mask;
25666   OSTRACE(("SHM-LOCK "));
25667   mask = (1<<(ofst+n)) - (1<<ofst);
25668   if( rc==SQLITE_OK ){
25669     if( lockType==F_UNLCK ){
25670       OSTRACE(("unlock %d ok", ofst));
25671       pShmNode->exclMask &= ~mask;
25672       pShmNode->sharedMask &= ~mask;
25673     }else if( lockType==F_RDLCK ){
25674       OSTRACE(("read-lock %d ok", ofst));
25675       pShmNode->exclMask &= ~mask;
25676       pShmNode->sharedMask |= mask;
25677     }else{
25678       assert( lockType==F_WRLCK );
25679       OSTRACE(("write-lock %d ok", ofst));
25680       pShmNode->exclMask |= mask;
25681       pShmNode->sharedMask &= ~mask;
25682     }
25683   }else{
25684     if( lockType==F_UNLCK ){
25685       OSTRACE(("unlock %d failed", ofst));
25686     }else if( lockType==F_RDLCK ){
25687       OSTRACE(("read-lock failed"));
25688     }else{
25689       assert( lockType==F_WRLCK );
25690       OSTRACE(("write-lock %d failed", ofst));
25691     }
25692   }
25693   OSTRACE((" - afterwards %03x,%03x\n",
25694            pShmNode->sharedMask, pShmNode->exclMask));
25695   }
25696 #endif
25697
25698   return rc;        
25699 }
25700
25701
25702 /*
25703 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
25704 **
25705 ** This is not a VFS shared-memory method; it is a utility function called
25706 ** by VFS shared-memory methods.
25707 */
25708 static void unixShmPurge(unixFile *pFd){
25709   unixShmNode *p = pFd->pInode->pShmNode;
25710   assert( unixMutexHeld() );
25711   if( p && p->nRef==0 ){
25712     int i;
25713     assert( p->pInode==pFd->pInode );
25714     if( p->mutex ) sqlite3_mutex_free(p->mutex);
25715     for(i=0; i<p->nRegion; i++){
25716       munmap(p->apRegion[i], p->szRegion);
25717     }
25718     sqlite3_free(p->apRegion);
25719     if( p->h>=0 ) close(p->h);
25720     p->pInode->pShmNode = 0;
25721     sqlite3_free(p);
25722   }
25723 }
25724
25725 /*
25726 ** Open a shared-memory area associated with open database file pDbFd.  
25727 ** This particular implementation uses mmapped files.
25728 **
25729 ** The file used to implement shared-memory is in the same directory
25730 ** as the open database file and has the same name as the open database
25731 ** file with the "-shm" suffix added.  For example, if the database file
25732 ** is "/home/user1/config.db" then the file that is created and mmapped
25733 ** for shared memory will be called "/home/user1/config.db-shm".  
25734 **
25735 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
25736 ** some other tmpfs mount. But if a file in a different directory
25737 ** from the database file is used, then differing access permissions
25738 ** or a chroot() might cause two different processes on the same
25739 ** database to end up using different files for shared memory - 
25740 ** meaning that their memory would not really be shared - resulting
25741 ** in database corruption.  Nevertheless, this tmpfs file usage
25742 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
25743 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
25744 ** option results in an incompatible build of SQLite;  builds of SQLite
25745 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
25746 ** same database file at the same time, database corruption will likely
25747 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
25748 ** "unsupported" and may go away in a future SQLite release.
25749 **
25750 ** When opening a new shared-memory file, if no other instances of that
25751 ** file are currently open, in this process or in other processes, then
25752 ** the file must be truncated to zero length or have its header cleared.
25753 */
25754 static int unixOpenSharedMemory(unixFile *pDbFd){
25755   struct unixShm *p = 0;          /* The connection to be opened */
25756   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
25757   int rc;                         /* Result code */
25758   unixInodeInfo *pInode;          /* The inode of fd */
25759   char *zShmFilename;             /* Name of the file used for SHM */
25760   int nShmFilename;               /* Size of the SHM filename in bytes */
25761
25762   /* Allocate space for the new unixShm object. */
25763   p = sqlite3_malloc( sizeof(*p) );
25764   if( p==0 ) return SQLITE_NOMEM;
25765   memset(p, 0, sizeof(*p));
25766   assert( pDbFd->pShm==0 );
25767
25768   /* Check to see if a unixShmNode object already exists. Reuse an existing
25769   ** one if present. Create a new one if necessary.
25770   */
25771   unixEnterMutex();
25772   pInode = pDbFd->pInode;
25773   pShmNode = pInode->pShmNode;
25774   if( pShmNode==0 ){
25775     struct stat sStat;                 /* fstat() info for database file */
25776
25777     /* Call fstat() to figure out the permissions on the database file. If
25778     ** a new *-shm file is created, an attempt will be made to create it
25779     ** with the same permissions. The actual permissions the file is created
25780     ** with are subject to the current umask setting.
25781     */
25782     if( fstat(pDbFd->h, &sStat) ){
25783       rc = SQLITE_IOERR_FSTAT;
25784       goto shm_open_err;
25785     }
25786
25787 #ifdef SQLITE_SHM_DIRECTORY
25788     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
25789 #else
25790     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
25791 #endif
25792     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
25793     if( pShmNode==0 ){
25794       rc = SQLITE_NOMEM;
25795       goto shm_open_err;
25796     }
25797     memset(pShmNode, 0, sizeof(*pShmNode));
25798     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
25799 #ifdef SQLITE_SHM_DIRECTORY
25800     sqlite3_snprintf(nShmFilename, zShmFilename, 
25801                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
25802                      (u32)sStat.st_ino, (u32)sStat.st_dev);
25803 #else
25804     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
25805 #endif
25806     pShmNode->h = -1;
25807     pDbFd->pInode->pShmNode = pShmNode;
25808     pShmNode->pInode = pDbFd->pInode;
25809     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
25810     if( pShmNode->mutex==0 ){
25811       rc = SQLITE_NOMEM;
25812       goto shm_open_err;
25813     }
25814
25815     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
25816     if( pShmNode->h<0 ){
25817       rc = SQLITE_CANTOPEN_BKPT;
25818       goto shm_open_err;
25819     }
25820
25821     /* Check to see if another process is holding the dead-man switch.
25822     ** If not, truncate the file to zero length. 
25823     */
25824     rc = SQLITE_OK;
25825     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
25826       if( ftruncate(pShmNode->h, 0) ){
25827         rc = SQLITE_IOERR_SHMOPEN;
25828       }
25829     }
25830     if( rc==SQLITE_OK ){
25831       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
25832     }
25833     if( rc ) goto shm_open_err;
25834   }
25835
25836   /* Make the new connection a child of the unixShmNode */
25837   p->pShmNode = pShmNode;
25838 #ifdef SQLITE_DEBUG
25839   p->id = pShmNode->nextShmId++;
25840 #endif
25841   pShmNode->nRef++;
25842   pDbFd->pShm = p;
25843   unixLeaveMutex();
25844
25845   /* The reference count on pShmNode has already been incremented under
25846   ** the cover of the unixEnterMutex() mutex and the pointer from the
25847   ** new (struct unixShm) object to the pShmNode has been set. All that is
25848   ** left to do is to link the new object into the linked list starting
25849   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
25850   ** mutex.
25851   */
25852   sqlite3_mutex_enter(pShmNode->mutex);
25853   p->pNext = pShmNode->pFirst;
25854   pShmNode->pFirst = p;
25855   sqlite3_mutex_leave(pShmNode->mutex);
25856   return SQLITE_OK;
25857
25858   /* Jump here on any error */
25859 shm_open_err:
25860   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
25861   sqlite3_free(p);
25862   unixLeaveMutex();
25863   return rc;
25864 }
25865
25866 /*
25867 ** This function is called to obtain a pointer to region iRegion of the 
25868 ** shared-memory associated with the database file fd. Shared-memory regions 
25869 ** are numbered starting from zero. Each shared-memory region is szRegion 
25870 ** bytes in size.
25871 **
25872 ** If an error occurs, an error code is returned and *pp is set to NULL.
25873 **
25874 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
25875 ** region has not been allocated (by any client, including one running in a
25876 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
25877 ** bExtend is non-zero and the requested shared-memory region has not yet 
25878 ** been allocated, it is allocated by this function.
25879 **
25880 ** If the shared-memory region has already been allocated or is allocated by
25881 ** this call as described above, then it is mapped into this processes 
25882 ** address space (if it is not already), *pp is set to point to the mapped 
25883 ** memory and SQLITE_OK returned.
25884 */
25885 static int unixShmMap(
25886   sqlite3_file *fd,               /* Handle open on database file */
25887   int iRegion,                    /* Region to retrieve */
25888   int szRegion,                   /* Size of regions */
25889   int bExtend,                    /* True to extend file if necessary */
25890   void volatile **pp              /* OUT: Mapped memory */
25891 ){
25892   unixFile *pDbFd = (unixFile*)fd;
25893   unixShm *p;
25894   unixShmNode *pShmNode;
25895   int rc = SQLITE_OK;
25896
25897   /* If the shared-memory file has not yet been opened, open it now. */
25898   if( pDbFd->pShm==0 ){
25899     rc = unixOpenSharedMemory(pDbFd);
25900     if( rc!=SQLITE_OK ) return rc;
25901   }
25902
25903   p = pDbFd->pShm;
25904   pShmNode = p->pShmNode;
25905   sqlite3_mutex_enter(pShmNode->mutex);
25906   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
25907
25908   if( pShmNode->nRegion<=iRegion ){
25909     char **apNew;                      /* New apRegion[] array */
25910     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
25911     struct stat sStat;                 /* Used by fstat() */
25912
25913     pShmNode->szRegion = szRegion;
25914
25915     /* The requested region is not mapped into this processes address space.
25916     ** Check to see if it has been allocated (i.e. if the wal-index file is
25917     ** large enough to contain the requested region).
25918     */
25919     if( fstat(pShmNode->h, &sStat) ){
25920       rc = SQLITE_IOERR_SHMSIZE;
25921       goto shmpage_out;
25922     }
25923
25924     if( sStat.st_size<nByte ){
25925       /* The requested memory region does not exist. If bExtend is set to
25926       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
25927       **
25928       ** Alternatively, if bExtend is true, use ftruncate() to allocate
25929       ** the requested memory region.
25930       */
25931       if( !bExtend ) goto shmpage_out;
25932       if( ftruncate(pShmNode->h, nByte) ){
25933         rc = SQLITE_IOERR_SHMSIZE;
25934         goto shmpage_out;
25935       }
25936     }
25937
25938     /* Map the requested memory region into this processes address space. */
25939     apNew = (char **)sqlite3_realloc(
25940         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
25941     );
25942     if( !apNew ){
25943       rc = SQLITE_IOERR_NOMEM;
25944       goto shmpage_out;
25945     }
25946     pShmNode->apRegion = apNew;
25947     while(pShmNode->nRegion<=iRegion){
25948       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
25949           MAP_SHARED, pShmNode->h, iRegion*szRegion
25950       );
25951       if( pMem==MAP_FAILED ){
25952         rc = SQLITE_IOERR;
25953         goto shmpage_out;
25954       }
25955       pShmNode->apRegion[pShmNode->nRegion] = pMem;
25956       pShmNode->nRegion++;
25957     }
25958   }
25959
25960 shmpage_out:
25961   if( pShmNode->nRegion>iRegion ){
25962     *pp = pShmNode->apRegion[iRegion];
25963   }else{
25964     *pp = 0;
25965   }
25966   sqlite3_mutex_leave(pShmNode->mutex);
25967   return rc;
25968 }
25969
25970 /*
25971 ** Change the lock state for a shared-memory segment.
25972 **
25973 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
25974 ** different here than in posix.  In xShmLock(), one can go from unlocked
25975 ** to shared and back or from unlocked to exclusive and back.  But one may
25976 ** not go from shared to exclusive or from exclusive to shared.
25977 */
25978 static int unixShmLock(
25979   sqlite3_file *fd,          /* Database file holding the shared memory */
25980   int ofst,                  /* First lock to acquire or release */
25981   int n,                     /* Number of locks to acquire or release */
25982   int flags                  /* What to do with the lock */
25983 ){
25984   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
25985   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
25986   unixShm *pX;                          /* For looping over all siblings */
25987   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
25988   int rc = SQLITE_OK;                   /* Result code */
25989   u16 mask;                             /* Mask of locks to take or release */
25990
25991   assert( pShmNode==pDbFd->pInode->pShmNode );
25992   assert( pShmNode->pInode==pDbFd->pInode );
25993   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
25994   assert( n>=1 );
25995   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
25996        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
25997        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
25998        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
25999   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26000
26001   mask = (1<<(ofst+n)) - (1<<ofst);
26002   assert( n>1 || mask==(1<<ofst) );
26003   sqlite3_mutex_enter(pShmNode->mutex);
26004   if( flags & SQLITE_SHM_UNLOCK ){
26005     u16 allMask = 0; /* Mask of locks held by siblings */
26006
26007     /* See if any siblings hold this same lock */
26008     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26009       if( pX==p ) continue;
26010       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26011       allMask |= pX->sharedMask;
26012     }
26013
26014     /* Unlock the system-level locks */
26015     if( (mask & allMask)==0 ){
26016       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26017     }else{
26018       rc = SQLITE_OK;
26019     }
26020
26021     /* Undo the local locks */
26022     if( rc==SQLITE_OK ){
26023       p->exclMask &= ~mask;
26024       p->sharedMask &= ~mask;
26025     } 
26026   }else if( flags & SQLITE_SHM_SHARED ){
26027     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26028
26029     /* Find out which shared locks are already held by sibling connections.
26030     ** If any sibling already holds an exclusive lock, go ahead and return
26031     ** SQLITE_BUSY.
26032     */
26033     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26034       if( (pX->exclMask & mask)!=0 ){
26035         rc = SQLITE_BUSY;
26036         break;
26037       }
26038       allShared |= pX->sharedMask;
26039     }
26040
26041     /* Get shared locks at the system level, if necessary */
26042     if( rc==SQLITE_OK ){
26043       if( (allShared & mask)==0 ){
26044         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26045       }else{
26046         rc = SQLITE_OK;
26047       }
26048     }
26049
26050     /* Get the local shared locks */
26051     if( rc==SQLITE_OK ){
26052       p->sharedMask |= mask;
26053     }
26054   }else{
26055     /* Make sure no sibling connections hold locks that will block this
26056     ** lock.  If any do, return SQLITE_BUSY right away.
26057     */
26058     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26059       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26060         rc = SQLITE_BUSY;
26061         break;
26062       }
26063     }
26064   
26065     /* Get the exclusive locks at the system level.  Then if successful
26066     ** also mark the local connection as being locked.
26067     */
26068     if( rc==SQLITE_OK ){
26069       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26070       if( rc==SQLITE_OK ){
26071         assert( (p->sharedMask & mask)==0 );
26072         p->exclMask |= mask;
26073       }
26074     }
26075   }
26076   sqlite3_mutex_leave(pShmNode->mutex);
26077   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26078            p->id, getpid(), p->sharedMask, p->exclMask));
26079   return rc;
26080 }
26081
26082 /*
26083 ** Implement a memory barrier or memory fence on shared memory.  
26084 **
26085 ** All loads and stores begun before the barrier must complete before
26086 ** any load or store begun after the barrier.
26087 */
26088 static void unixShmBarrier(
26089   sqlite3_file *fd                /* Database file holding the shared memory */
26090 ){
26091   UNUSED_PARAMETER(fd);
26092   unixEnterMutex();
26093   unixLeaveMutex();
26094 }
26095
26096 /*
26097 ** Close a connection to shared-memory.  Delete the underlying 
26098 ** storage if deleteFlag is true.
26099 **
26100 ** If there is no shared memory associated with the connection then this
26101 ** routine is a harmless no-op.
26102 */
26103 static int unixShmUnmap(
26104   sqlite3_file *fd,               /* The underlying database file */
26105   int deleteFlag                  /* Delete shared-memory if true */
26106 ){
26107   unixShm *p;                     /* The connection to be closed */
26108   unixShmNode *pShmNode;          /* The underlying shared-memory file */
26109   unixShm **pp;                   /* For looping over sibling connections */
26110   unixFile *pDbFd;                /* The underlying database file */
26111
26112   pDbFd = (unixFile*)fd;
26113   p = pDbFd->pShm;
26114   if( p==0 ) return SQLITE_OK;
26115   pShmNode = p->pShmNode;
26116
26117   assert( pShmNode==pDbFd->pInode->pShmNode );
26118   assert( pShmNode->pInode==pDbFd->pInode );
26119
26120   /* Remove connection p from the set of connections associated
26121   ** with pShmNode */
26122   sqlite3_mutex_enter(pShmNode->mutex);
26123   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26124   *pp = p->pNext;
26125
26126   /* Free the connection p */
26127   sqlite3_free(p);
26128   pDbFd->pShm = 0;
26129   sqlite3_mutex_leave(pShmNode->mutex);
26130
26131   /* If pShmNode->nRef has reached 0, then close the underlying
26132   ** shared-memory file, too */
26133   unixEnterMutex();
26134   assert( pShmNode->nRef>0 );
26135   pShmNode->nRef--;
26136   if( pShmNode->nRef==0 ){
26137     if( deleteFlag ) unlink(pShmNode->zFilename);
26138     unixShmPurge(pDbFd);
26139   }
26140   unixLeaveMutex();
26141
26142   return SQLITE_OK;
26143 }
26144
26145
26146 #else
26147 # define unixShmMap     0
26148 # define unixShmLock    0
26149 # define unixShmBarrier 0
26150 # define unixShmUnmap   0
26151 #endif /* #ifndef SQLITE_OMIT_WAL */
26152
26153 /*
26154 ** Here ends the implementation of all sqlite3_file methods.
26155 **
26156 ********************** End sqlite3_file Methods *******************************
26157 ******************************************************************************/
26158
26159 /*
26160 ** This division contains definitions of sqlite3_io_methods objects that
26161 ** implement various file locking strategies.  It also contains definitions
26162 ** of "finder" functions.  A finder-function is used to locate the appropriate
26163 ** sqlite3_io_methods object for a particular database file.  The pAppData
26164 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26165 ** the correct finder-function for that VFS.
26166 **
26167 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
26168 ** object.  The only interesting finder-function is autolockIoFinder, which
26169 ** looks at the filesystem type and tries to guess the best locking
26170 ** strategy from that.
26171 **
26172 ** For finder-funtion F, two objects are created:
26173 **
26174 **    (1) The real finder-function named "FImpt()".
26175 **
26176 **    (2) A constant pointer to this function named just "F".
26177 **
26178 **
26179 ** A pointer to the F pointer is used as the pAppData value for VFS
26180 ** objects.  We have to do this instead of letting pAppData point
26181 ** directly at the finder-function since C90 rules prevent a void*
26182 ** from be cast into a function pointer.
26183 **
26184 **
26185 ** Each instance of this macro generates two objects:
26186 **
26187 **   *  A constant sqlite3_io_methods object call METHOD that has locking
26188 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26189 **
26190 **   *  An I/O method finder function called FINDER that returns a pointer
26191 **      to the METHOD object in the previous bullet.
26192 */
26193 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26194 static const sqlite3_io_methods METHOD = {                                   \
26195    VERSION,                    /* iVersion */                                \
26196    CLOSE,                      /* xClose */                                  \
26197    unixRead,                   /* xRead */                                   \
26198    unixWrite,                  /* xWrite */                                  \
26199    unixTruncate,               /* xTruncate */                               \
26200    unixSync,                   /* xSync */                                   \
26201    unixFileSize,               /* xFileSize */                               \
26202    LOCK,                       /* xLock */                                   \
26203    UNLOCK,                     /* xUnlock */                                 \
26204    CKLOCK,                     /* xCheckReservedLock */                      \
26205    unixFileControl,            /* xFileControl */                            \
26206    unixSectorSize,             /* xSectorSize */                             \
26207    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26208    unixShmMap,                 /* xShmMap */                                 \
26209    unixShmLock,                /* xShmLock */                                \
26210    unixShmBarrier,             /* xShmBarrier */                             \
26211    unixShmUnmap                /* xShmUnmap */                               \
26212 };                                                                           \
26213 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26214   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26215   return &METHOD;                                                            \
26216 }                                                                            \
26217 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26218     = FINDER##Impl;
26219
26220 /*
26221 ** Here are all of the sqlite3_io_methods objects for each of the
26222 ** locking strategies.  Functions that return pointers to these methods
26223 ** are also created.
26224 */
26225 IOMETHODS(
26226   posixIoFinder,            /* Finder function name */
26227   posixIoMethods,           /* sqlite3_io_methods object name */
26228   2,                        /* shared memory is enabled */
26229   unixClose,                /* xClose method */
26230   unixLock,                 /* xLock method */
26231   unixUnlock,               /* xUnlock method */
26232   unixCheckReservedLock     /* xCheckReservedLock method */
26233 )
26234 IOMETHODS(
26235   nolockIoFinder,           /* Finder function name */
26236   nolockIoMethods,          /* sqlite3_io_methods object name */
26237   1,                        /* shared memory is disabled */
26238   nolockClose,              /* xClose method */
26239   nolockLock,               /* xLock method */
26240   nolockUnlock,             /* xUnlock method */
26241   nolockCheckReservedLock   /* xCheckReservedLock method */
26242 )
26243 IOMETHODS(
26244   dotlockIoFinder,          /* Finder function name */
26245   dotlockIoMethods,         /* sqlite3_io_methods object name */
26246   1,                        /* shared memory is disabled */
26247   dotlockClose,             /* xClose method */
26248   dotlockLock,              /* xLock method */
26249   dotlockUnlock,            /* xUnlock method */
26250   dotlockCheckReservedLock  /* xCheckReservedLock method */
26251 )
26252
26253 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26254 IOMETHODS(
26255   flockIoFinder,            /* Finder function name */
26256   flockIoMethods,           /* sqlite3_io_methods object name */
26257   1,                        /* shared memory is disabled */
26258   flockClose,               /* xClose method */
26259   flockLock,                /* xLock method */
26260   flockUnlock,              /* xUnlock method */
26261   flockCheckReservedLock    /* xCheckReservedLock method */
26262 )
26263 #endif
26264
26265 #if OS_VXWORKS
26266 IOMETHODS(
26267   semIoFinder,              /* Finder function name */
26268   semIoMethods,             /* sqlite3_io_methods object name */
26269   1,                        /* shared memory is disabled */
26270   semClose,                 /* xClose method */
26271   semLock,                  /* xLock method */
26272   semUnlock,                /* xUnlock method */
26273   semCheckReservedLock      /* xCheckReservedLock method */
26274 )
26275 #endif
26276
26277 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26278 IOMETHODS(
26279   afpIoFinder,              /* Finder function name */
26280   afpIoMethods,             /* sqlite3_io_methods object name */
26281   1,                        /* shared memory is disabled */
26282   afpClose,                 /* xClose method */
26283   afpLock,                  /* xLock method */
26284   afpUnlock,                /* xUnlock method */
26285   afpCheckReservedLock      /* xCheckReservedLock method */
26286 )
26287 #endif
26288
26289 /*
26290 ** The proxy locking method is a "super-method" in the sense that it
26291 ** opens secondary file descriptors for the conch and lock files and
26292 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
26293 ** secondary files.  For this reason, the division that implements
26294 ** proxy locking is located much further down in the file.  But we need
26295 ** to go ahead and define the sqlite3_io_methods and finder function
26296 ** for proxy locking here.  So we forward declare the I/O methods.
26297 */
26298 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26299 static int proxyClose(sqlite3_file*);
26300 static int proxyLock(sqlite3_file*, int);
26301 static int proxyUnlock(sqlite3_file*, int);
26302 static int proxyCheckReservedLock(sqlite3_file*, int*);
26303 IOMETHODS(
26304   proxyIoFinder,            /* Finder function name */
26305   proxyIoMethods,           /* sqlite3_io_methods object name */
26306   1,                        /* shared memory is disabled */
26307   proxyClose,               /* xClose method */
26308   proxyLock,                /* xLock method */
26309   proxyUnlock,              /* xUnlock method */
26310   proxyCheckReservedLock    /* xCheckReservedLock method */
26311 )
26312 #endif
26313
26314 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26315 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26316 IOMETHODS(
26317   nfsIoFinder,               /* Finder function name */
26318   nfsIoMethods,              /* sqlite3_io_methods object name */
26319   1,                         /* shared memory is disabled */
26320   unixClose,                 /* xClose method */
26321   unixLock,                  /* xLock method */
26322   nfsUnlock,                 /* xUnlock method */
26323   unixCheckReservedLock      /* xCheckReservedLock method */
26324 )
26325 #endif
26326
26327 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26328 /* 
26329 ** This "finder" function attempts to determine the best locking strategy 
26330 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26331 ** object that implements that strategy.
26332 **
26333 ** This is for MacOSX only.
26334 */
26335 static const sqlite3_io_methods *autolockIoFinderImpl(
26336   const char *filePath,    /* name of the database file */
26337   unixFile *pNew           /* open file object for the database file */
26338 ){
26339   static const struct Mapping {
26340     const char *zFilesystem;              /* Filesystem type name */
26341     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26342   } aMap[] = {
26343     { "hfs",    &posixIoMethods },
26344     { "ufs",    &posixIoMethods },
26345     { "afpfs",  &afpIoMethods },
26346     { "smbfs",  &afpIoMethods },
26347     { "webdav", &nolockIoMethods },
26348     { 0, 0 }
26349   };
26350   int i;
26351   struct statfs fsInfo;
26352   struct flock lockInfo;
26353
26354   if( !filePath ){
26355     /* If filePath==NULL that means we are dealing with a transient file
26356     ** that does not need to be locked. */
26357     return &nolockIoMethods;
26358   }
26359   if( statfs(filePath, &fsInfo) != -1 ){
26360     if( fsInfo.f_flags & MNT_RDONLY ){
26361       return &nolockIoMethods;
26362     }
26363     for(i=0; aMap[i].zFilesystem; i++){
26364       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26365         return aMap[i].pMethods;
26366       }
26367     }
26368   }
26369
26370   /* Default case. Handles, amongst others, "nfs".
26371   ** Test byte-range lock using fcntl(). If the call succeeds, 
26372   ** assume that the file-system supports POSIX style locks. 
26373   */
26374   lockInfo.l_len = 1;
26375   lockInfo.l_start = 0;
26376   lockInfo.l_whence = SEEK_SET;
26377   lockInfo.l_type = F_RDLCK;
26378   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26379     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26380       return &nfsIoMethods;
26381     } else {
26382       return &posixIoMethods;
26383     }
26384   }else{
26385     return &dotlockIoMethods;
26386   }
26387 }
26388 static const sqlite3_io_methods 
26389   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26390
26391 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26392
26393 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26394 /* 
26395 ** This "finder" function attempts to determine the best locking strategy 
26396 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26397 ** object that implements that strategy.
26398 **
26399 ** This is for VXWorks only.
26400 */
26401 static const sqlite3_io_methods *autolockIoFinderImpl(
26402   const char *filePath,    /* name of the database file */
26403   unixFile *pNew           /* the open file object */
26404 ){
26405   struct flock lockInfo;
26406
26407   if( !filePath ){
26408     /* If filePath==NULL that means we are dealing with a transient file
26409     ** that does not need to be locked. */
26410     return &nolockIoMethods;
26411   }
26412
26413   /* Test if fcntl() is supported and use POSIX style locks.
26414   ** Otherwise fall back to the named semaphore method.
26415   */
26416   lockInfo.l_len = 1;
26417   lockInfo.l_start = 0;
26418   lockInfo.l_whence = SEEK_SET;
26419   lockInfo.l_type = F_RDLCK;
26420   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26421     return &posixIoMethods;
26422   }else{
26423     return &semIoMethods;
26424   }
26425 }
26426 static const sqlite3_io_methods 
26427   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26428
26429 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
26430
26431 /*
26432 ** An abstract type for a pointer to a IO method finder function:
26433 */
26434 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
26435
26436
26437 /****************************************************************************
26438 **************************** sqlite3_vfs methods ****************************
26439 **
26440 ** This division contains the implementation of methods on the
26441 ** sqlite3_vfs object.
26442 */
26443
26444 /*
26445 ** Initialize the contents of the unixFile structure pointed to by pId.
26446 */
26447 static int fillInUnixFile(
26448   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
26449   int h,                  /* Open file descriptor of file being opened */
26450   int dirfd,              /* Directory file descriptor */
26451   sqlite3_file *pId,      /* Write to the unixFile structure here */
26452   const char *zFilename,  /* Name of the file being opened */
26453   int noLock,             /* Omit locking if true */
26454   int isDelete            /* Delete on close if true */
26455 ){
26456   const sqlite3_io_methods *pLockingStyle;
26457   unixFile *pNew = (unixFile *)pId;
26458   int rc = SQLITE_OK;
26459
26460   assert( pNew->pInode==NULL );
26461
26462   /* Parameter isDelete is only used on vxworks. Express this explicitly 
26463   ** here to prevent compiler warnings about unused parameters.
26464   */
26465   UNUSED_PARAMETER(isDelete);
26466
26467   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
26468   pNew->h = h;
26469   pNew->dirfd = dirfd;
26470   pNew->fileFlags = 0;
26471   assert( zFilename==0 || zFilename[0]=='/' );  /* Never a relative pathname */
26472   pNew->zPath = zFilename;
26473
26474 #if OS_VXWORKS
26475   pNew->pId = vxworksFindFileId(zFilename);
26476   if( pNew->pId==0 ){
26477     noLock = 1;
26478     rc = SQLITE_NOMEM;
26479   }
26480 #endif
26481
26482   if( noLock ){
26483     pLockingStyle = &nolockIoMethods;
26484   }else{
26485     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
26486 #if SQLITE_ENABLE_LOCKING_STYLE
26487     /* Cache zFilename in the locking context (AFP and dotlock override) for
26488     ** proxyLock activation is possible (remote proxy is based on db name)
26489     ** zFilename remains valid until file is closed, to support */
26490     pNew->lockingContext = (void*)zFilename;
26491 #endif
26492   }
26493
26494   if( pLockingStyle == &posixIoMethods
26495 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26496     || pLockingStyle == &nfsIoMethods
26497 #endif
26498   ){
26499     unixEnterMutex();
26500     rc = findInodeInfo(pNew, &pNew->pInode);
26501     if( rc!=SQLITE_OK ){
26502       /* If an error occured in findInodeInfo(), close the file descriptor
26503       ** immediately, before releasing the mutex. findInodeInfo() may fail
26504       ** in two scenarios:
26505       **
26506       **   (a) A call to fstat() failed.
26507       **   (b) A malloc failed.
26508       **
26509       ** Scenario (b) may only occur if the process is holding no other
26510       ** file descriptors open on the same file. If there were other file
26511       ** descriptors on this file, then no malloc would be required by
26512       ** findInodeInfo(). If this is the case, it is quite safe to close
26513       ** handle h - as it is guaranteed that no posix locks will be released
26514       ** by doing so.
26515       **
26516       ** If scenario (a) caused the error then things are not so safe. The
26517       ** implicit assumption here is that if fstat() fails, things are in
26518       ** such bad shape that dropping a lock or two doesn't matter much.
26519       */
26520       close(h);
26521       h = -1;
26522     }
26523     unixLeaveMutex();
26524   }
26525
26526 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26527   else if( pLockingStyle == &afpIoMethods ){
26528     /* AFP locking uses the file path so it needs to be included in
26529     ** the afpLockingContext.
26530     */
26531     afpLockingContext *pCtx;
26532     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
26533     if( pCtx==0 ){
26534       rc = SQLITE_NOMEM;
26535     }else{
26536       /* NB: zFilename exists and remains valid until the file is closed
26537       ** according to requirement F11141.  So we do not need to make a
26538       ** copy of the filename. */
26539       pCtx->dbPath = zFilename;
26540       pCtx->reserved = 0;
26541       srandomdev();
26542       unixEnterMutex();
26543       rc = findInodeInfo(pNew, &pNew->pInode);
26544       if( rc!=SQLITE_OK ){
26545         sqlite3_free(pNew->lockingContext);
26546         close(h);
26547         h = -1;
26548       }
26549       unixLeaveMutex();        
26550     }
26551   }
26552 #endif
26553
26554   else if( pLockingStyle == &dotlockIoMethods ){
26555     /* Dotfile locking uses the file path so it needs to be included in
26556     ** the dotlockLockingContext 
26557     */
26558     char *zLockFile;
26559     int nFilename;
26560     nFilename = (int)strlen(zFilename) + 6;
26561     zLockFile = (char *)sqlite3_malloc(nFilename);
26562     if( zLockFile==0 ){
26563       rc = SQLITE_NOMEM;
26564     }else{
26565       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
26566     }
26567     pNew->lockingContext = zLockFile;
26568   }
26569
26570 #if OS_VXWORKS
26571   else if( pLockingStyle == &semIoMethods ){
26572     /* Named semaphore locking uses the file path so it needs to be
26573     ** included in the semLockingContext
26574     */
26575     unixEnterMutex();
26576     rc = findInodeInfo(pNew, &pNew->pInode);
26577     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
26578       char *zSemName = pNew->pInode->aSemName;
26579       int n;
26580       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
26581                        pNew->pId->zCanonicalName);
26582       for( n=1; zSemName[n]; n++ )
26583         if( zSemName[n]=='/' ) zSemName[n] = '_';
26584       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
26585       if( pNew->pInode->pSem == SEM_FAILED ){
26586         rc = SQLITE_NOMEM;
26587         pNew->pInode->aSemName[0] = '\0';
26588       }
26589     }
26590     unixLeaveMutex();
26591   }
26592 #endif
26593   
26594   pNew->lastErrno = 0;
26595 #if OS_VXWORKS
26596   if( rc!=SQLITE_OK ){
26597     if( h>=0 ) close(h);
26598     h = -1;
26599     unlink(zFilename);
26600     isDelete = 0;
26601   }
26602   pNew->isDelete = isDelete;
26603 #endif
26604   if( rc!=SQLITE_OK ){
26605     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
26606     if( h>=0 ) close(h);
26607   }else{
26608     pNew->pMethod = pLockingStyle;
26609     OpenCounter(+1);
26610   }
26611   return rc;
26612 }
26613
26614 /*
26615 ** Open a file descriptor to the directory containing file zFilename.
26616 ** If successful, *pFd is set to the opened file descriptor and
26617 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26618 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26619 ** value.
26620 **
26621 ** If SQLITE_OK is returned, the caller is responsible for closing
26622 ** the file descriptor *pFd using close().
26623 */
26624 static int openDirectory(const char *zFilename, int *pFd){
26625   int ii;
26626   int fd = -1;
26627   char zDirname[MAX_PATHNAME+1];
26628
26629   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26630   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26631   if( ii>0 ){
26632     zDirname[ii] = '\0';
26633     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
26634     if( fd>=0 ){
26635 #ifdef FD_CLOEXEC
26636       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26637 #endif
26638       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26639     }
26640   }
26641   *pFd = fd;
26642   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
26643 }
26644
26645 /*
26646 ** Return the name of a directory in which to put temporary files.
26647 ** If no suitable temporary file directory can be found, return NULL.
26648 */
26649 static const char *unixTempFileDir(void){
26650   static const char *azDirs[] = {
26651      0,
26652      0,
26653      "/var/tmp",
26654      "/usr/tmp",
26655      "/tmp",
26656      0        /* List terminator */
26657   };
26658   unsigned int i;
26659   struct stat buf;
26660   const char *zDir = 0;
26661
26662   azDirs[0] = sqlite3_temp_directory;
26663   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
26664   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
26665     if( zDir==0 ) continue;
26666     if( stat(zDir, &buf) ) continue;
26667     if( !S_ISDIR(buf.st_mode) ) continue;
26668     if( access(zDir, 07) ) continue;
26669     break;
26670   }
26671   return zDir;
26672 }
26673
26674 /*
26675 ** Create a temporary file name in zBuf.  zBuf must be allocated
26676 ** by the calling process and must be big enough to hold at least
26677 ** pVfs->mxPathname bytes.
26678 */
26679 static int unixGetTempname(int nBuf, char *zBuf){
26680   static const unsigned char zChars[] =
26681     "abcdefghijklmnopqrstuvwxyz"
26682     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26683     "0123456789";
26684   unsigned int i, j;
26685   const char *zDir;
26686
26687   /* It's odd to simulate an io-error here, but really this is just
26688   ** using the io-error infrastructure to test that SQLite handles this
26689   ** function failing. 
26690   */
26691   SimulateIOError( return SQLITE_IOERR );
26692
26693   zDir = unixTempFileDir();
26694   if( zDir==0 ) zDir = ".";
26695
26696   /* Check that the output buffer is large enough for the temporary file 
26697   ** name. If it is not, return SQLITE_ERROR.
26698   */
26699   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
26700     return SQLITE_ERROR;
26701   }
26702
26703   do{
26704     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
26705     j = (int)strlen(zBuf);
26706     sqlite3_randomness(15, &zBuf[j]);
26707     for(i=0; i<15; i++, j++){
26708       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26709     }
26710     zBuf[j] = 0;
26711   }while( access(zBuf,0)==0 );
26712   return SQLITE_OK;
26713 }
26714
26715 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26716 /*
26717 ** Routine to transform a unixFile into a proxy-locking unixFile.
26718 ** Implementation in the proxy-lock division, but used by unixOpen()
26719 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
26720 */
26721 static int proxyTransformUnixFile(unixFile*, const char*);
26722 #endif
26723
26724 /*
26725 ** Search for an unused file descriptor that was opened on the database 
26726 ** file (not a journal or master-journal file) identified by pathname
26727 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
26728 ** argument to this function.
26729 **
26730 ** Such a file descriptor may exist if a database connection was closed
26731 ** but the associated file descriptor could not be closed because some
26732 ** other file descriptor open on the same file is holding a file-lock.
26733 ** Refer to comments in the unixClose() function and the lengthy comment
26734 ** describing "Posix Advisory Locking" at the start of this file for 
26735 ** further details. Also, ticket #4018.
26736 **
26737 ** If a suitable file descriptor is found, then it is returned. If no
26738 ** such file descriptor is located, -1 is returned.
26739 */
26740 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
26741   UnixUnusedFd *pUnused = 0;
26742
26743   /* Do not search for an unused file descriptor on vxworks. Not because
26744   ** vxworks would not benefit from the change (it might, we're not sure),
26745   ** but because no way to test it is currently available. It is better 
26746   ** not to risk breaking vxworks support for the sake of such an obscure 
26747   ** feature.  */
26748 #if !OS_VXWORKS
26749   struct stat sStat;                   /* Results of stat() call */
26750
26751   /* A stat() call may fail for various reasons. If this happens, it is
26752   ** almost certain that an open() call on the same path will also fail.
26753   ** For this reason, if an error occurs in the stat() call here, it is
26754   ** ignored and -1 is returned. The caller will try to open a new file
26755   ** descriptor on the same path, fail, and return an error to SQLite.
26756   **
26757   ** Even if a subsequent open() call does succeed, the consequences of
26758   ** not searching for a resusable file descriptor are not dire.  */
26759   if( 0==stat(zPath, &sStat) ){
26760     unixInodeInfo *pInode;
26761
26762     unixEnterMutex();
26763     pInode = inodeList;
26764     while( pInode && (pInode->fileId.dev!=sStat.st_dev
26765                      || pInode->fileId.ino!=sStat.st_ino) ){
26766        pInode = pInode->pNext;
26767     }
26768     if( pInode ){
26769       UnixUnusedFd **pp;
26770       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
26771       pUnused = *pp;
26772       if( pUnused ){
26773         *pp = pUnused->pNext;
26774       }
26775     }
26776     unixLeaveMutex();
26777   }
26778 #endif    /* if !OS_VXWORKS */
26779   return pUnused;
26780 }
26781
26782 /*
26783 ** This function is called by unixOpen() to determine the unix permissions
26784 ** to create new files with. If no error occurs, then SQLITE_OK is returned
26785 ** and a value suitable for passing as the third argument to open(2) is
26786 ** written to *pMode. If an IO error occurs, an SQLite error code is 
26787 ** returned and the value of *pMode is not modified.
26788 **
26789 ** If the file being opened is a temporary file, it is always created with
26790 ** the octal permissions 0600 (read/writable by owner only). If the file
26791 ** is a database or master journal file, it is created with the permissions 
26792 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
26793 **
26794 ** Finally, if the file being opened is a WAL or regular journal file, then 
26795 ** this function queries the file-system for the permissions on the 
26796 ** corresponding database file and sets *pMode to this value. Whenever 
26797 ** possible, WAL and journal files are created using the same permissions 
26798 ** as the associated database file.
26799 */
26800 static int findCreateFileMode(
26801   const char *zPath,              /* Path of file (possibly) being created */
26802   int flags,                      /* Flags passed as 4th argument to xOpen() */
26803   mode_t *pMode                   /* OUT: Permissions to open file with */
26804 ){
26805   int rc = SQLITE_OK;             /* Return Code */
26806   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
26807     char zDb[MAX_PATHNAME+1];     /* Database file path */
26808     int nDb;                      /* Number of valid bytes in zDb */
26809     struct stat sStat;            /* Output of stat() on database file */
26810
26811     nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
26812     memcpy(zDb, zPath, nDb);
26813     zDb[nDb] = '\0';
26814     if( 0==stat(zDb, &sStat) ){
26815       *pMode = sStat.st_mode & 0777;
26816     }else{
26817       rc = SQLITE_IOERR_FSTAT;
26818     }
26819   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
26820     *pMode = 0600;
26821   }else{
26822     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
26823   }
26824   return rc;
26825 }
26826
26827 /*
26828 ** Open the file zPath.
26829 ** 
26830 ** Previously, the SQLite OS layer used three functions in place of this
26831 ** one:
26832 **
26833 **     sqlite3OsOpenReadWrite();
26834 **     sqlite3OsOpenReadOnly();
26835 **     sqlite3OsOpenExclusive();
26836 **
26837 ** These calls correspond to the following combinations of flags:
26838 **
26839 **     ReadWrite() ->     (READWRITE | CREATE)
26840 **     ReadOnly()  ->     (READONLY) 
26841 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
26842 **
26843 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
26844 ** true, the file was configured to be automatically deleted when the
26845 ** file handle closed. To achieve the same effect using this new 
26846 ** interface, add the DELETEONCLOSE flag to those specified above for 
26847 ** OpenExclusive().
26848 */
26849 static int unixOpen(
26850   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
26851   const char *zPath,           /* Pathname of file to be opened */
26852   sqlite3_file *pFile,         /* The file descriptor to be filled in */
26853   int flags,                   /* Input flags to control the opening */
26854   int *pOutFlags               /* Output flags returned to SQLite core */
26855 ){
26856   unixFile *p = (unixFile *)pFile;
26857   int fd = -1;                   /* File descriptor returned by open() */
26858   int dirfd = -1;                /* Directory file descriptor */
26859   int openFlags = 0;             /* Flags to pass to open() */
26860   int eType = flags&0xFFFFFF00;  /* Type of file to open */
26861   int noLock;                    /* True to omit locking primitives */
26862   int rc = SQLITE_OK;            /* Function Return Code */
26863
26864   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
26865   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
26866   int isCreate     = (flags & SQLITE_OPEN_CREATE);
26867   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
26868   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
26869 #if SQLITE_ENABLE_LOCKING_STYLE
26870   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
26871 #endif
26872
26873   /* If creating a master or main-file journal, this function will open
26874   ** a file-descriptor on the directory too. The first time unixSync()
26875   ** is called the directory file descriptor will be fsync()ed and close()d.
26876   */
26877   int isOpenDirectory = (isCreate && (
26878         eType==SQLITE_OPEN_MASTER_JOURNAL 
26879      || eType==SQLITE_OPEN_MAIN_JOURNAL 
26880      || eType==SQLITE_OPEN_WAL
26881   ));
26882
26883   /* If argument zPath is a NULL pointer, this function is required to open
26884   ** a temporary file. Use this buffer to store the file name in.
26885   */
26886   char zTmpname[MAX_PATHNAME+1];
26887   const char *zName = zPath;
26888
26889   /* Check the following statements are true: 
26890   **
26891   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
26892   **   (b) if CREATE is set, then READWRITE must also be set, and
26893   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
26894   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
26895   */
26896   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
26897   assert(isCreate==0 || isReadWrite);
26898   assert(isExclusive==0 || isCreate);
26899   assert(isDelete==0 || isCreate);
26900
26901   /* The main DB, main journal, WAL file and master journal are never 
26902   ** automatically deleted. Nor are they ever temporary files.  */
26903   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
26904   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
26905   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
26906   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
26907
26908   /* Assert that the upper layer has set one of the "file-type" flags. */
26909   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
26910        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
26911        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
26912        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
26913   );
26914
26915   memset(p, 0, sizeof(unixFile));
26916
26917   if( eType==SQLITE_OPEN_MAIN_DB ){
26918     UnixUnusedFd *pUnused;
26919     pUnused = findReusableFd(zName, flags);
26920     if( pUnused ){
26921       fd = pUnused->fd;
26922     }else{
26923       pUnused = sqlite3_malloc(sizeof(*pUnused));
26924       if( !pUnused ){
26925         return SQLITE_NOMEM;
26926       }
26927     }
26928     p->pUnused = pUnused;
26929   }else if( !zName ){
26930     /* If zName is NULL, the upper layer is requesting a temp file. */
26931     assert(isDelete && !isOpenDirectory);
26932     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
26933     if( rc!=SQLITE_OK ){
26934       return rc;
26935     }
26936     zName = zTmpname;
26937   }
26938
26939   /* Determine the value of the flags parameter passed to POSIX function
26940   ** open(). These must be calculated even if open() is not called, as
26941   ** they may be stored as part of the file handle and used by the 
26942   ** 'conch file' locking functions later on.  */
26943   if( isReadonly )  openFlags |= O_RDONLY;
26944   if( isReadWrite ) openFlags |= O_RDWR;
26945   if( isCreate )    openFlags |= O_CREAT;
26946   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
26947   openFlags |= (O_LARGEFILE|O_BINARY);
26948
26949   if( fd<0 ){
26950     mode_t openMode;              /* Permissions to create file with */
26951     rc = findCreateFileMode(zName, flags, &openMode);
26952     if( rc!=SQLITE_OK ){
26953       assert( !p->pUnused );
26954       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
26955       return rc;
26956     }
26957     fd = open(zName, openFlags, openMode);
26958     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
26959     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
26960       /* Failed to open the file for read/write access. Try read-only. */
26961       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
26962       openFlags &= ~(O_RDWR|O_CREAT);
26963       flags |= SQLITE_OPEN_READONLY;
26964       openFlags |= O_RDONLY;
26965       fd = open(zName, openFlags, openMode);
26966     }
26967     if( fd<0 ){
26968       rc = SQLITE_CANTOPEN_BKPT;
26969       goto open_finished;
26970     }
26971   }
26972   assert( fd>=0 );
26973   if( pOutFlags ){
26974     *pOutFlags = flags;
26975   }
26976
26977   if( p->pUnused ){
26978     p->pUnused->fd = fd;
26979     p->pUnused->flags = flags;
26980   }
26981
26982   if( isDelete ){
26983 #if OS_VXWORKS
26984     zPath = zName;
26985 #else
26986     unlink(zName);
26987 #endif
26988   }
26989 #if SQLITE_ENABLE_LOCKING_STYLE
26990   else{
26991     p->openFlags = openFlags;
26992   }
26993 #endif
26994
26995   if( isOpenDirectory ){
26996     rc = openDirectory(zPath, &dirfd);
26997     if( rc!=SQLITE_OK ){
26998       /* It is safe to close fd at this point, because it is guaranteed not
26999       ** to be open on a database file. If it were open on a database file,
27000       ** it would not be safe to close as this would release any locks held
27001       ** on the file by this process.  */
27002       assert( eType!=SQLITE_OPEN_MAIN_DB );
27003       close(fd);             /* silently leak if fail, already in error */
27004       goto open_finished;
27005     }
27006   }
27007
27008 #ifdef FD_CLOEXEC
27009   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27010 #endif
27011
27012   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27013
27014   
27015 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27016   struct statfs fsInfo;
27017   if( fstatfs(fd, &fsInfo) == -1 ){
27018     ((unixFile*)pFile)->lastErrno = errno;
27019     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27020     close(fd); /* silently leak if fail, in error */
27021     return SQLITE_IOERR_ACCESS;
27022   }
27023   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27024     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27025   }
27026 #endif
27027   
27028 #if SQLITE_ENABLE_LOCKING_STYLE
27029 #if SQLITE_PREFER_PROXY_LOCKING
27030   isAutoProxy = 1;
27031 #endif
27032   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27033     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27034     int useProxy = 0;
27035
27036     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27037     ** never use proxy, NULL means use proxy for non-local files only.  */
27038     if( envforce!=NULL ){
27039       useProxy = atoi(envforce)>0;
27040     }else{
27041       struct statfs fsInfo;
27042       if( statfs(zPath, &fsInfo) == -1 ){
27043         /* In theory, the close(fd) call is sub-optimal. If the file opened
27044         ** with fd is a database file, and there are other connections open
27045         ** on that file that are currently holding advisory locks on it,
27046         ** then the call to close() will cancel those locks. In practice,
27047         ** we're assuming that statfs() doesn't fail very often. At least
27048         ** not while other file descriptors opened by the same process on
27049         ** the same file are working.  */
27050         p->lastErrno = errno;
27051         if( dirfd>=0 ){
27052           close(dirfd); /* silently leak if fail, in error */
27053         }
27054         close(fd); /* silently leak if fail, in error */
27055         rc = SQLITE_IOERR_ACCESS;
27056         goto open_finished;
27057       }
27058       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27059     }
27060     if( useProxy ){
27061       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27062       if( rc==SQLITE_OK ){
27063         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27064         if( rc!=SQLITE_OK ){
27065           /* Use unixClose to clean up the resources added in fillInUnixFile 
27066           ** and clear all the structure's references.  Specifically, 
27067           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
27068           */
27069           unixClose(pFile);
27070           return rc;
27071         }
27072       }
27073       goto open_finished;
27074     }
27075   }
27076 #endif
27077   
27078   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27079 open_finished:
27080   if( rc!=SQLITE_OK ){
27081     sqlite3_free(p->pUnused);
27082   }
27083   return rc;
27084 }
27085
27086
27087 /*
27088 ** Delete the file at zPath. If the dirSync argument is true, fsync()
27089 ** the directory after deleting the file.
27090 */
27091 static int unixDelete(
27092   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27093   const char *zPath,        /* Name of file to be deleted */
27094   int dirSync               /* If true, fsync() directory after deleting file */
27095 ){
27096   int rc = SQLITE_OK;
27097   UNUSED_PARAMETER(NotUsed);
27098   SimulateIOError(return SQLITE_IOERR_DELETE);
27099   if( unlink(zPath)==(-1) && errno!=ENOENT ){
27100     return SQLITE_IOERR_DELETE;
27101   }
27102 #ifndef SQLITE_DISABLE_DIRSYNC
27103   if( dirSync ){
27104     int fd;
27105     rc = openDirectory(zPath, &fd);
27106     if( rc==SQLITE_OK ){
27107 #if OS_VXWORKS
27108       if( fsync(fd)==-1 )
27109 #else
27110       if( fsync(fd) )
27111 #endif
27112       {
27113         rc = SQLITE_IOERR_DIR_FSYNC;
27114       }
27115       if( close(fd)&&!rc ){
27116         rc = SQLITE_IOERR_DIR_CLOSE;
27117       }
27118     }
27119   }
27120 #endif
27121   return rc;
27122 }
27123
27124 /*
27125 ** Test the existance of or access permissions of file zPath. The
27126 ** test performed depends on the value of flags:
27127 **
27128 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27129 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27130 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27131 **
27132 ** Otherwise return 0.
27133 */
27134 static int unixAccess(
27135   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27136   const char *zPath,      /* Path of the file to examine */
27137   int flags,              /* What do we want to learn about the zPath file? */
27138   int *pResOut            /* Write result boolean here */
27139 ){
27140   int amode = 0;
27141   UNUSED_PARAMETER(NotUsed);
27142   SimulateIOError( return SQLITE_IOERR_ACCESS; );
27143   switch( flags ){
27144     case SQLITE_ACCESS_EXISTS:
27145       amode = F_OK;
27146       break;
27147     case SQLITE_ACCESS_READWRITE:
27148       amode = W_OK|R_OK;
27149       break;
27150     case SQLITE_ACCESS_READ:
27151       amode = R_OK;
27152       break;
27153
27154     default:
27155       assert(!"Invalid flags argument");
27156   }
27157   *pResOut = (access(zPath, amode)==0);
27158   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27159     struct stat buf;
27160     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27161       *pResOut = 0;
27162     }
27163   }
27164   return SQLITE_OK;
27165 }
27166
27167
27168 /*
27169 ** Turn a relative pathname into a full pathname. The relative path
27170 ** is stored as a nul-terminated string in the buffer pointed to by
27171 ** zPath. 
27172 **
27173 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
27174 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
27175 ** this buffer before returning.
27176 */
27177 static int unixFullPathname(
27178   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27179   const char *zPath,            /* Possibly relative input path */
27180   int nOut,                     /* Size of output buffer in bytes */
27181   char *zOut                    /* Output buffer */
27182 ){
27183
27184   /* It's odd to simulate an io-error here, but really this is just
27185   ** using the io-error infrastructure to test that SQLite handles this
27186   ** function failing. This function could fail if, for example, the
27187   ** current working directory has been unlinked.
27188   */
27189   SimulateIOError( return SQLITE_ERROR );
27190
27191   assert( pVfs->mxPathname==MAX_PATHNAME );
27192   UNUSED_PARAMETER(pVfs);
27193
27194   zOut[nOut-1] = '\0';
27195   if( zPath[0]=='/' ){
27196     sqlite3_snprintf(nOut, zOut, "%s", zPath);
27197   }else{
27198     int nCwd;
27199     if( getcwd(zOut, nOut-1)==0 ){
27200       return SQLITE_CANTOPEN_BKPT;
27201     }
27202     nCwd = (int)strlen(zOut);
27203     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27204   }
27205   return SQLITE_OK;
27206 }
27207
27208
27209 #ifndef SQLITE_OMIT_LOAD_EXTENSION
27210 /*
27211 ** Interfaces for opening a shared library, finding entry points
27212 ** within the shared library, and closing the shared library.
27213 */
27214 #include <dlfcn.h>
27215 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27216   UNUSED_PARAMETER(NotUsed);
27217   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27218 }
27219
27220 /*
27221 ** SQLite calls this function immediately after a call to unixDlSym() or
27222 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
27223 ** message is available, it is written to zBufOut. If no error message
27224 ** is available, zBufOut is left unmodified and SQLite uses a default
27225 ** error message.
27226 */
27227 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27228   char *zErr;
27229   UNUSED_PARAMETER(NotUsed);
27230   unixEnterMutex();
27231   zErr = dlerror();
27232   if( zErr ){
27233     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27234   }
27235   unixLeaveMutex();
27236 }
27237 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27238   /* 
27239   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27240   ** cast into a pointer to a function.  And yet the library dlsym() routine
27241   ** returns a void* which is really a pointer to a function.  So how do we
27242   ** use dlsym() with -pedantic-errors?
27243   **
27244   ** Variable x below is defined to be a pointer to a function taking
27245   ** parameters void* and const char* and returning a pointer to a function.
27246   ** We initialize x by assigning it a pointer to the dlsym() function.
27247   ** (That assignment requires a cast.)  Then we call the function that
27248   ** x points to.  
27249   **
27250   ** This work-around is unlikely to work correctly on any system where
27251   ** you really cannot cast a function pointer into void*.  But then, on the
27252   ** other hand, dlsym() will not work on such a system either, so we have
27253   ** not really lost anything.
27254   */
27255   void (*(*x)(void*,const char*))(void);
27256   UNUSED_PARAMETER(NotUsed);
27257   x = (void(*(*)(void*,const char*))(void))dlsym;
27258   return (*x)(p, zSym);
27259 }
27260 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27261   UNUSED_PARAMETER(NotUsed);
27262   dlclose(pHandle);
27263 }
27264 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27265   #define unixDlOpen  0
27266   #define unixDlError 0
27267   #define unixDlSym   0
27268   #define unixDlClose 0
27269 #endif
27270
27271 /*
27272 ** Write nBuf bytes of random data to the supplied buffer zBuf.
27273 */
27274 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27275   UNUSED_PARAMETER(NotUsed);
27276   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27277
27278   /* We have to initialize zBuf to prevent valgrind from reporting
27279   ** errors.  The reports issued by valgrind are incorrect - we would
27280   ** prefer that the randomness be increased by making use of the
27281   ** uninitialized space in zBuf - but valgrind errors tend to worry
27282   ** some users.  Rather than argue, it seems easier just to initialize
27283   ** the whole array and silence valgrind, even if that means less randomness
27284   ** in the random seed.
27285   **
27286   ** When testing, initializing zBuf[] to zero is all we do.  That means
27287   ** that we always use the same random number sequence.  This makes the
27288   ** tests repeatable.
27289   */
27290   memset(zBuf, 0, nBuf);
27291 #if !defined(SQLITE_TEST)
27292   {
27293     int pid, fd;
27294     fd = open("/dev/urandom", O_RDONLY);
27295     if( fd<0 ){
27296       time_t t;
27297       time(&t);
27298       memcpy(zBuf, &t, sizeof(t));
27299       pid = getpid();
27300       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27301       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27302       nBuf = sizeof(t) + sizeof(pid);
27303     }else{
27304       nBuf = read(fd, zBuf, nBuf);
27305       close(fd);
27306     }
27307   }
27308 #endif
27309   return nBuf;
27310 }
27311
27312
27313 /*
27314 ** Sleep for a little while.  Return the amount of time slept.
27315 ** The argument is the number of microseconds we want to sleep.
27316 ** The return value is the number of microseconds of sleep actually
27317 ** requested from the underlying operating system, a number which
27318 ** might be greater than or equal to the argument, but not less
27319 ** than the argument.
27320 */
27321 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27322 #if OS_VXWORKS
27323   struct timespec sp;
27324
27325   sp.tv_sec = microseconds / 1000000;
27326   sp.tv_nsec = (microseconds % 1000000) * 1000;
27327   nanosleep(&sp, NULL);
27328   UNUSED_PARAMETER(NotUsed);
27329   return microseconds;
27330 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
27331   usleep(microseconds);
27332   UNUSED_PARAMETER(NotUsed);
27333   return microseconds;
27334 #else
27335   int seconds = (microseconds+999999)/1000000;
27336   sleep(seconds);
27337   UNUSED_PARAMETER(NotUsed);
27338   return seconds*1000000;
27339 #endif
27340 }
27341
27342 /*
27343 ** The following variable, if set to a non-zero value, is interpreted as
27344 ** the number of seconds since 1970 and is used to set the result of
27345 ** sqlite3OsCurrentTime() during testing.
27346 */
27347 #ifdef SQLITE_TEST
27348 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27349 #endif
27350
27351 /*
27352 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
27353 ** the current time and date as a Julian Day number times 86_400_000.  In
27354 ** other words, write into *piNow the number of milliseconds since the Julian
27355 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27356 ** proleptic Gregorian calendar.
27357 **
27358 ** On success, return 0.  Return 1 if the time and date cannot be found.
27359 */
27360 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27361   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27362 #if defined(NO_GETTOD)
27363   time_t t;
27364   time(&t);
27365   *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27366 #elif OS_VXWORKS
27367   struct timespec sNow;
27368   clock_gettime(CLOCK_REALTIME, &sNow);
27369   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27370 #else
27371   struct timeval sNow;
27372   gettimeofday(&sNow, 0);
27373   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27374 #endif
27375
27376 #ifdef SQLITE_TEST
27377   if( sqlite3_current_time ){
27378     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27379   }
27380 #endif
27381   UNUSED_PARAMETER(NotUsed);
27382   return 0;
27383 }
27384
27385 /*
27386 ** Find the current time (in Universal Coordinated Time).  Write the
27387 ** current time and date as a Julian Day number into *prNow and
27388 ** return 0.  Return 1 if the time and date cannot be found.
27389 */
27390 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27391   sqlite3_int64 i;
27392   UNUSED_PARAMETER(NotUsed);
27393   unixCurrentTimeInt64(0, &i);
27394   *prNow = i/86400000.0;
27395   return 0;
27396 }
27397
27398 /*
27399 ** We added the xGetLastError() method with the intention of providing
27400 ** better low-level error messages when operating-system problems come up
27401 ** during SQLite operation.  But so far, none of that has been implemented
27402 ** in the core.  So this routine is never called.  For now, it is merely
27403 ** a place-holder.
27404 */
27405 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
27406   UNUSED_PARAMETER(NotUsed);
27407   UNUSED_PARAMETER(NotUsed2);
27408   UNUSED_PARAMETER(NotUsed3);
27409   return 0;
27410 }
27411
27412
27413 /*
27414 ************************ End of sqlite3_vfs methods ***************************
27415 ******************************************************************************/
27416
27417 /******************************************************************************
27418 ************************** Begin Proxy Locking ********************************
27419 **
27420 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
27421 ** other locking methods on secondary lock files.  Proxy locking is a
27422 ** meta-layer over top of the primitive locking implemented above.  For
27423 ** this reason, the division that implements of proxy locking is deferred
27424 ** until late in the file (here) after all of the other I/O methods have
27425 ** been defined - so that the primitive locking methods are available
27426 ** as services to help with the implementation of proxy locking.
27427 **
27428 ****
27429 **
27430 ** The default locking schemes in SQLite use byte-range locks on the
27431 ** database file to coordinate safe, concurrent access by multiple readers
27432 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
27433 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
27434 ** as POSIX read & write locks over fixed set of locations (via fsctl),
27435 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
27436 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
27437 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
27438 ** address in the shared range is taken for a SHARED lock, the entire
27439 ** shared range is taken for an EXCLUSIVE lock):
27440 **
27441 **      PENDING_BYTE        0x40000000                  
27442 **      RESERVED_BYTE       0x40000001
27443 **      SHARED_RANGE        0x40000002 -> 0x40000200
27444 **
27445 ** This works well on the local file system, but shows a nearly 100x
27446 ** slowdown in read performance on AFP because the AFP client disables
27447 ** the read cache when byte-range locks are present.  Enabling the read
27448 ** cache exposes a cache coherency problem that is present on all OS X
27449 ** supported network file systems.  NFS and AFP both observe the
27450 ** close-to-open semantics for ensuring cache coherency
27451 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
27452 ** address the requirements for concurrent database access by multiple
27453 ** readers and writers
27454 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
27455 **
27456 ** To address the performance and cache coherency issues, proxy file locking
27457 ** changes the way database access is controlled by limiting access to a
27458 ** single host at a time and moving file locks off of the database file
27459 ** and onto a proxy file on the local file system.  
27460 **
27461 **
27462 ** Using proxy locks
27463 ** -----------------
27464 **
27465 ** C APIs
27466 **
27467 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
27468 **                       <proxy_path> | ":auto:");
27469 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
27470 **
27471 **
27472 ** SQL pragmas
27473 **
27474 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
27475 **  PRAGMA [database.]lock_proxy_file
27476 **
27477 ** Specifying ":auto:" means that if there is a conch file with a matching
27478 ** host ID in it, the proxy path in the conch file will be used, otherwise
27479 ** a proxy path based on the user's temp dir
27480 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
27481 ** actual proxy file name is generated from the name and path of the
27482 ** database file.  For example:
27483 **
27484 **       For database path "/Users/me/foo.db" 
27485 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
27486 **
27487 ** Once a lock proxy is configured for a database connection, it can not
27488 ** be removed, however it may be switched to a different proxy path via
27489 ** the above APIs (assuming the conch file is not being held by another
27490 ** connection or process). 
27491 **
27492 **
27493 ** How proxy locking works
27494 ** -----------------------
27495 **
27496 ** Proxy file locking relies primarily on two new supporting files: 
27497 **
27498 **   *  conch file to limit access to the database file to a single host
27499 **      at a time
27500 **
27501 **   *  proxy file to act as a proxy for the advisory locks normally
27502 **      taken on the database
27503 **
27504 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
27505 ** by taking an sqlite-style shared lock on the conch file, reading the
27506 ** contents and comparing the host's unique host ID (see below) and lock
27507 ** proxy path against the values stored in the conch.  The conch file is
27508 ** stored in the same directory as the database file and the file name
27509 ** is patterned after the database file name as ".<databasename>-conch".
27510 ** If the conch file does not exist, or it's contents do not match the
27511 ** host ID and/or proxy path, then the lock is escalated to an exclusive
27512 ** lock and the conch file contents is updated with the host ID and proxy
27513 ** path and the lock is downgraded to a shared lock again.  If the conch
27514 ** is held by another process (with a shared lock), the exclusive lock
27515 ** will fail and SQLITE_BUSY is returned.
27516 **
27517 ** The proxy file - a single-byte file used for all advisory file locks
27518 ** normally taken on the database file.   This allows for safe sharing
27519 ** of the database file for multiple readers and writers on the same
27520 ** host (the conch ensures that they all use the same local lock file).
27521 **
27522 ** Requesting the lock proxy does not immediately take the conch, it is
27523 ** only taken when the first request to lock database file is made.  
27524 ** This matches the semantics of the traditional locking behavior, where
27525 ** opening a connection to a database file does not take a lock on it.
27526 ** The shared lock and an open file descriptor are maintained until 
27527 ** the connection to the database is closed. 
27528 **
27529 ** The proxy file and the lock file are never deleted so they only need
27530 ** to be created the first time they are used.
27531 **
27532 ** Configuration options
27533 ** ---------------------
27534 **
27535 **  SQLITE_PREFER_PROXY_LOCKING
27536 **
27537 **       Database files accessed on non-local file systems are
27538 **       automatically configured for proxy locking, lock files are
27539 **       named automatically using the same logic as
27540 **       PRAGMA lock_proxy_file=":auto:"
27541 **    
27542 **  SQLITE_PROXY_DEBUG
27543 **
27544 **       Enables the logging of error messages during host id file
27545 **       retrieval and creation
27546 **
27547 **  LOCKPROXYDIR
27548 **
27549 **       Overrides the default directory used for lock proxy files that
27550 **       are named automatically via the ":auto:" setting
27551 **
27552 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
27553 **
27554 **       Permissions to use when creating a directory for storing the
27555 **       lock proxy files, only used when LOCKPROXYDIR is not set.
27556 **    
27557 **    
27558 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
27559 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
27560 ** force proxy locking to be used for every database file opened, and 0
27561 ** will force automatic proxy locking to be disabled for all database
27562 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
27563 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
27564 */
27565
27566 /*
27567 ** Proxy locking is only available on MacOSX 
27568 */
27569 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27570
27571 /*
27572 ** The proxyLockingContext has the path and file structures for the remote 
27573 ** and local proxy files in it
27574 */
27575 typedef struct proxyLockingContext proxyLockingContext;
27576 struct proxyLockingContext {
27577   unixFile *conchFile;         /* Open conch file */
27578   char *conchFilePath;         /* Name of the conch file */
27579   unixFile *lockProxy;         /* Open proxy lock file */
27580   char *lockProxyPath;         /* Name of the proxy lock file */
27581   char *dbPath;                /* Name of the open file */
27582   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
27583   void *oldLockingContext;     /* Original lockingcontext to restore on close */
27584   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
27585 };
27586
27587 /* 
27588 ** The proxy lock file path for the database at dbPath is written into lPath, 
27589 ** which must point to valid, writable memory large enough for a maxLen length
27590 ** file path. 
27591 */
27592 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
27593   int len;
27594   int dbLen;
27595   int i;
27596
27597 #ifdef LOCKPROXYDIR
27598   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
27599 #else
27600 # ifdef _CS_DARWIN_USER_TEMP_DIR
27601   {
27602     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
27603       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
27604                lPath, errno, getpid()));
27605       return SQLITE_IOERR_LOCK;
27606     }
27607     len = strlcat(lPath, "sqliteplocks", maxLen);    
27608   }
27609 # else
27610   len = strlcpy(lPath, "/tmp/", maxLen);
27611 # endif
27612 #endif
27613
27614   if( lPath[len-1]!='/' ){
27615     len = strlcat(lPath, "/", maxLen);
27616   }
27617   
27618   /* transform the db path to a unique cache name */
27619   dbLen = (int)strlen(dbPath);
27620   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
27621     char c = dbPath[i];
27622     lPath[i+len] = (c=='/')?'_':c;
27623   }
27624   lPath[i+len]='\0';
27625   strlcat(lPath, ":auto:", maxLen);
27626   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
27627   return SQLITE_OK;
27628 }
27629
27630 /* 
27631  ** Creates the lock file and any missing directories in lockPath
27632  */
27633 static int proxyCreateLockPath(const char *lockPath){
27634   int i, len;
27635   char buf[MAXPATHLEN];
27636   int start = 0;
27637   
27638   assert(lockPath!=NULL);
27639   /* try to create all the intermediate directories */
27640   len = (int)strlen(lockPath);
27641   buf[0] = lockPath[0];
27642   for( i=1; i<len; i++ ){
27643     if( lockPath[i] == '/' && (i - start > 0) ){
27644       /* only mkdir if leaf dir != "." or "/" or ".." */
27645       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
27646          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
27647         buf[i]='\0';
27648         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
27649           int err=errno;
27650           if( err!=EEXIST ) {
27651             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
27652                      "'%s' proxy lock path=%s pid=%d\n",
27653                      buf, strerror(err), lockPath, getpid()));
27654             return err;
27655           }
27656         }
27657       }
27658       start=i+1;
27659     }
27660     buf[i] = lockPath[i];
27661   }
27662   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
27663   return 0;
27664 }
27665
27666 /*
27667 ** Create a new VFS file descriptor (stored in memory obtained from
27668 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
27669 **
27670 ** The caller is responsible not only for closing the file descriptor
27671 ** but also for freeing the memory associated with the file descriptor.
27672 */
27673 static int proxyCreateUnixFile(
27674     const char *path,        /* path for the new unixFile */
27675     unixFile **ppFile,       /* unixFile created and returned by ref */
27676     int islockfile           /* if non zero missing dirs will be created */
27677 ) {
27678   int fd = -1;
27679   int dirfd = -1;
27680   unixFile *pNew;
27681   int rc = SQLITE_OK;
27682   int openFlags = O_RDWR | O_CREAT;
27683   sqlite3_vfs dummyVfs;
27684   int terrno = 0;
27685   UnixUnusedFd *pUnused = NULL;
27686
27687   /* 1. first try to open/create the file
27688   ** 2. if that fails, and this is a lock file (not-conch), try creating
27689   ** the parent directories and then try again.
27690   ** 3. if that fails, try to open the file read-only
27691   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
27692   */
27693   pUnused = findReusableFd(path, openFlags);
27694   if( pUnused ){
27695     fd = pUnused->fd;
27696   }else{
27697     pUnused = sqlite3_malloc(sizeof(*pUnused));
27698     if( !pUnused ){
27699       return SQLITE_NOMEM;
27700     }
27701   }
27702   if( fd<0 ){
27703     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27704     terrno = errno;
27705     if( fd<0 && errno==ENOENT && islockfile ){
27706       if( proxyCreateLockPath(path) == SQLITE_OK ){
27707         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27708       }
27709     }
27710   }
27711   if( fd<0 ){
27712     openFlags = O_RDONLY;
27713     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27714     terrno = errno;
27715   }
27716   if( fd<0 ){
27717     if( islockfile ){
27718       return SQLITE_BUSY;
27719     }
27720     switch (terrno) {
27721       case EACCES:
27722         return SQLITE_PERM;
27723       case EIO: 
27724         return SQLITE_IOERR_LOCK; /* even though it is the conch */
27725       default:
27726         return SQLITE_CANTOPEN_BKPT;
27727     }
27728   }
27729   
27730   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
27731   if( pNew==NULL ){
27732     rc = SQLITE_NOMEM;
27733     goto end_create_proxy;
27734   }
27735   memset(pNew, 0, sizeof(unixFile));
27736   pNew->openFlags = openFlags;
27737   dummyVfs.pAppData = (void*)&autolockIoFinder;
27738   pUnused->fd = fd;
27739   pUnused->flags = openFlags;
27740   pNew->pUnused = pUnused;
27741   
27742   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
27743   if( rc==SQLITE_OK ){
27744     *ppFile = pNew;
27745     return SQLITE_OK;
27746   }
27747 end_create_proxy:    
27748   close(fd); /* silently leak fd if error, we're already in error */
27749   sqlite3_free(pNew);
27750   sqlite3_free(pUnused);
27751   return rc;
27752 }
27753
27754 #ifdef SQLITE_TEST
27755 /* simulate multiple hosts by creating unique hostid file paths */
27756 SQLITE_API int sqlite3_hostid_num = 0;
27757 #endif
27758
27759 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
27760
27761 /* Not always defined in the headers as it ought to be */
27762 extern int gethostuuid(uuid_t id, const struct timespec *wait);
27763
27764 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
27765 ** bytes of writable memory.
27766 */
27767 static int proxyGetHostID(unsigned char *pHostID, int *pError){
27768   struct timespec timeout = {1, 0}; /* 1 sec timeout */
27769   
27770   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
27771   memset(pHostID, 0, PROXY_HOSTIDLEN);
27772   if( gethostuuid(pHostID, &timeout) ){
27773     int err = errno;
27774     if( pError ){
27775       *pError = err;
27776     }
27777     return SQLITE_IOERR;
27778   }
27779 #ifdef SQLITE_TEST
27780   /* simulate multiple hosts by creating unique hostid file paths */
27781   if( sqlite3_hostid_num != 0){
27782     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
27783   }
27784 #endif
27785   
27786   return SQLITE_OK;
27787 }
27788
27789 /* The conch file contains the header, host id and lock file path
27790  */
27791 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
27792 #define PROXY_HEADERLEN    1   /* conch file header length */
27793 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
27794 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
27795
27796 /* 
27797 ** Takes an open conch file, copies the contents to a new path and then moves 
27798 ** it back.  The newly created file's file descriptor is assigned to the
27799 ** conch file structure and finally the original conch file descriptor is 
27800 ** closed.  Returns zero if successful.
27801 */
27802 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
27803   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27804   unixFile *conchFile = pCtx->conchFile;
27805   char tPath[MAXPATHLEN];
27806   char buf[PROXY_MAXCONCHLEN];
27807   char *cPath = pCtx->conchFilePath;
27808   size_t readLen = 0;
27809   size_t pathLen = 0;
27810   char errmsg[64] = "";
27811   int fd = -1;
27812   int rc = -1;
27813   UNUSED_PARAMETER(myHostID);
27814
27815   /* create a new path by replace the trailing '-conch' with '-break' */
27816   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
27817   if( pathLen>MAXPATHLEN || pathLen<6 || 
27818      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
27819     sprintf(errmsg, "path error (len %d)", (int)pathLen);
27820     goto end_breaklock;
27821   }
27822   /* read the conch content */
27823   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
27824   if( readLen<PROXY_PATHINDEX ){
27825     sprintf(errmsg, "read error (len %d)", (int)readLen);
27826     goto end_breaklock;
27827   }
27828   /* write it out to the temporary break file */
27829   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
27830   if( fd<0 ){
27831     sprintf(errmsg, "create failed (%d)", errno);
27832     goto end_breaklock;
27833   }
27834   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
27835     sprintf(errmsg, "write failed (%d)", errno);
27836     goto end_breaklock;
27837   }
27838   if( rename(tPath, cPath) ){
27839     sprintf(errmsg, "rename failed (%d)", errno);
27840     goto end_breaklock;
27841   }
27842   rc = 0;
27843   fprintf(stderr, "broke stale lock on %s\n", cPath);
27844   close(conchFile->h);
27845   conchFile->h = fd;
27846   conchFile->openFlags = O_RDWR | O_CREAT;
27847
27848 end_breaklock:
27849   if( rc ){
27850     if( fd>=0 ){
27851       unlink(tPath);
27852       close(fd);
27853     }
27854     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
27855   }
27856   return rc;
27857 }
27858
27859 /* Take the requested lock on the conch file and break a stale lock if the 
27860 ** host id matches.
27861 */
27862 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
27863   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27864   unixFile *conchFile = pCtx->conchFile;
27865   int rc = SQLITE_OK;
27866   int nTries = 0;
27867   struct timespec conchModTime;
27868   
27869   do {
27870     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27871     nTries ++;
27872     if( rc==SQLITE_BUSY ){
27873       /* If the lock failed (busy):
27874        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
27875        * 2nd try: fail if the mod time changed or host id is different, wait 
27876        *           10 sec and try again
27877        * 3rd try: break the lock unless the mod time has changed.
27878        */
27879       struct stat buf;
27880       if( fstat(conchFile->h, &buf) ){
27881         pFile->lastErrno = errno;
27882         return SQLITE_IOERR_LOCK;
27883       }
27884       
27885       if( nTries==1 ){
27886         conchModTime = buf.st_mtimespec;
27887         usleep(500000); /* wait 0.5 sec and try the lock again*/
27888         continue;  
27889       }
27890
27891       assert( nTries>1 );
27892       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
27893          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
27894         return SQLITE_BUSY;
27895       }
27896       
27897       if( nTries==2 ){  
27898         char tBuf[PROXY_MAXCONCHLEN];
27899         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
27900         if( len<0 ){
27901           pFile->lastErrno = errno;
27902           return SQLITE_IOERR_LOCK;
27903         }
27904         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
27905           /* don't break the lock if the host id doesn't match */
27906           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
27907             return SQLITE_BUSY;
27908           }
27909         }else{
27910           /* don't break the lock on short read or a version mismatch */
27911           return SQLITE_BUSY;
27912         }
27913         usleep(10000000); /* wait 10 sec and try the lock again */
27914         continue; 
27915       }
27916       
27917       assert( nTries==3 );
27918       if( 0==proxyBreakConchLock(pFile, myHostID) ){
27919         rc = SQLITE_OK;
27920         if( lockType==EXCLUSIVE_LOCK ){
27921           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
27922         }
27923         if( !rc ){
27924           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27925         }
27926       }
27927     }
27928   } while( rc==SQLITE_BUSY && nTries<3 );
27929   
27930   return rc;
27931 }
27932
27933 /* Takes the conch by taking a shared lock and read the contents conch, if 
27934 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
27935 ** lockPath means that the lockPath in the conch file will be used if the 
27936 ** host IDs match, or a new lock path will be generated automatically 
27937 ** and written to the conch file.
27938 */
27939 static int proxyTakeConch(unixFile *pFile){
27940   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27941   
27942   if( pCtx->conchHeld!=0 ){
27943     return SQLITE_OK;
27944   }else{
27945     unixFile *conchFile = pCtx->conchFile;
27946     uuid_t myHostID;
27947     int pError = 0;
27948     char readBuf[PROXY_MAXCONCHLEN];
27949     char lockPath[MAXPATHLEN];
27950     char *tempLockPath = NULL;
27951     int rc = SQLITE_OK;
27952     int createConch = 0;
27953     int hostIdMatch = 0;
27954     int readLen = 0;
27955     int tryOldLockPath = 0;
27956     int forceNewLockPath = 0;
27957     
27958     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
27959              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
27960
27961     rc = proxyGetHostID(myHostID, &pError);
27962     if( (rc&0xff)==SQLITE_IOERR ){
27963       pFile->lastErrno = pError;
27964       goto end_takeconch;
27965     }
27966     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
27967     if( rc!=SQLITE_OK ){
27968       goto end_takeconch;
27969     }
27970     /* read the existing conch file */
27971     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
27972     if( readLen<0 ){
27973       /* I/O error: lastErrno set by seekAndRead */
27974       pFile->lastErrno = conchFile->lastErrno;
27975       rc = SQLITE_IOERR_READ;
27976       goto end_takeconch;
27977     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
27978              readBuf[0]!=(char)PROXY_CONCHVERSION ){
27979       /* a short read or version format mismatch means we need to create a new 
27980       ** conch file. 
27981       */
27982       createConch = 1;
27983     }
27984     /* if the host id matches and the lock path already exists in the conch
27985     ** we'll try to use the path there, if we can't open that path, we'll 
27986     ** retry with a new auto-generated path 
27987     */
27988     do { /* in case we need to try again for an :auto: named lock file */
27989
27990       if( !createConch && !forceNewLockPath ){
27991         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
27992                                   PROXY_HOSTIDLEN);
27993         /* if the conch has data compare the contents */
27994         if( !pCtx->lockProxyPath ){
27995           /* for auto-named local lock file, just check the host ID and we'll
27996            ** use the local lock file path that's already in there
27997            */
27998           if( hostIdMatch ){
27999             size_t pathLen = (readLen - PROXY_PATHINDEX);
28000             
28001             if( pathLen>=MAXPATHLEN ){
28002               pathLen=MAXPATHLEN-1;
28003             }
28004             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28005             lockPath[pathLen] = 0;
28006             tempLockPath = lockPath;
28007             tryOldLockPath = 1;
28008             /* create a copy of the lock path if the conch is taken */
28009             goto end_takeconch;
28010           }
28011         }else if( hostIdMatch
28012                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28013                            readLen-PROXY_PATHINDEX)
28014         ){
28015           /* conch host and lock path match */
28016           goto end_takeconch; 
28017         }
28018       }
28019       
28020       /* if the conch isn't writable and doesn't match, we can't take it */
28021       if( (conchFile->openFlags&O_RDWR) == 0 ){
28022         rc = SQLITE_BUSY;
28023         goto end_takeconch;
28024       }
28025       
28026       /* either the conch didn't match or we need to create a new one */
28027       if( !pCtx->lockProxyPath ){
28028         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28029         tempLockPath = lockPath;
28030         /* create a copy of the lock path _only_ if the conch is taken */
28031       }
28032       
28033       /* update conch with host and path (this will fail if other process
28034       ** has a shared lock already), if the host id matches, use the big
28035       ** stick.
28036       */
28037       futimes(conchFile->h, NULL);
28038       if( hostIdMatch && !createConch ){
28039         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28040           /* We are trying for an exclusive lock but another thread in this
28041            ** same process is still holding a shared lock. */
28042           rc = SQLITE_BUSY;
28043         } else {          
28044           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28045         }
28046       }else{
28047         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28048       }
28049       if( rc==SQLITE_OK ){
28050         char writeBuffer[PROXY_MAXCONCHLEN];
28051         int writeSize = 0;
28052         
28053         writeBuffer[0] = (char)PROXY_CONCHVERSION;
28054         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28055         if( pCtx->lockProxyPath!=NULL ){
28056           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28057         }else{
28058           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28059         }
28060         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28061         ftruncate(conchFile->h, writeSize);
28062         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28063         fsync(conchFile->h);
28064         /* If we created a new conch file (not just updated the contents of a 
28065          ** valid conch file), try to match the permissions of the database 
28066          */
28067         if( rc==SQLITE_OK && createConch ){
28068           struct stat buf;
28069           int err = fstat(pFile->h, &buf);
28070           if( err==0 ){
28071             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28072                                         S_IROTH|S_IWOTH);
28073             /* try to match the database file R/W permissions, ignore failure */
28074 #ifndef SQLITE_PROXY_DEBUG
28075             fchmod(conchFile->h, cmode);
28076 #else
28077             if( fchmod(conchFile->h, cmode)!=0 ){
28078               int code = errno;
28079               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28080                       cmode, code, strerror(code));
28081             } else {
28082               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28083             }
28084           }else{
28085             int code = errno;
28086             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
28087                     err, code, strerror(code));
28088 #endif
28089           }
28090         }
28091       }
28092       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28093       
28094     end_takeconch:
28095       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28096       if( rc==SQLITE_OK && pFile->openFlags ){
28097         if( pFile->h>=0 ){
28098 #ifdef STRICT_CLOSE_ERROR
28099           if( close(pFile->h) ){
28100             pFile->lastErrno = errno;
28101             return SQLITE_IOERR_CLOSE;
28102           }
28103 #else
28104           close(pFile->h); /* silently leak fd if fail */
28105 #endif
28106         }
28107         pFile->h = -1;
28108         int fd = open(pCtx->dbPath, pFile->openFlags,
28109                       SQLITE_DEFAULT_FILE_PERMISSIONS);
28110         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28111         if( fd>=0 ){
28112           pFile->h = fd;
28113         }else{
28114           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28115            during locking */
28116         }
28117       }
28118       if( rc==SQLITE_OK && !pCtx->lockProxy ){
28119         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28120         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28121         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28122           /* we couldn't create the proxy lock file with the old lock file path
28123            ** so try again via auto-naming 
28124            */
28125           forceNewLockPath = 1;
28126           tryOldLockPath = 0;
28127           continue; /* go back to the do {} while start point, try again */
28128         }
28129       }
28130       if( rc==SQLITE_OK ){
28131         /* Need to make a copy of path if we extracted the value
28132          ** from the conch file or the path was allocated on the stack
28133          */
28134         if( tempLockPath ){
28135           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28136           if( !pCtx->lockProxyPath ){
28137             rc = SQLITE_NOMEM;
28138           }
28139         }
28140       }
28141       if( rc==SQLITE_OK ){
28142         pCtx->conchHeld = 1;
28143         
28144         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28145           afpLockingContext *afpCtx;
28146           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28147           afpCtx->dbPath = pCtx->lockProxyPath;
28148         }
28149       } else {
28150         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28151       }
28152       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28153                rc==SQLITE_OK?"ok":"failed"));
28154       return rc;
28155     } while (1); /* in case we need to retry the :auto: lock file - 
28156                  ** we should never get here except via the 'continue' call. */
28157   }
28158 }
28159
28160 /*
28161 ** If pFile holds a lock on a conch file, then release that lock.
28162 */
28163 static int proxyReleaseConch(unixFile *pFile){
28164   int rc = SQLITE_OK;         /* Subroutine return code */
28165   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28166   unixFile *conchFile;        /* Name of the conch file */
28167
28168   pCtx = (proxyLockingContext *)pFile->lockingContext;
28169   conchFile = pCtx->conchFile;
28170   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28171            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28172            getpid()));
28173   if( pCtx->conchHeld>0 ){
28174     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28175   }
28176   pCtx->conchHeld = 0;
28177   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28178            (rc==SQLITE_OK ? "ok" : "failed")));
28179   return rc;
28180 }
28181
28182 /*
28183 ** Given the name of a database file, compute the name of its conch file.
28184 ** Store the conch filename in memory obtained from sqlite3_malloc().
28185 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28186 ** or SQLITE_NOMEM if unable to obtain memory.
28187 **
28188 ** The caller is responsible for ensuring that the allocated memory
28189 ** space is eventually freed.
28190 **
28191 ** *pConchPath is set to NULL if a memory allocation error occurs.
28192 */
28193 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28194   int i;                        /* Loop counter */
28195   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28196   char *conchPath;              /* buffer in which to construct conch name */
28197
28198   /* Allocate space for the conch filename and initialize the name to
28199   ** the name of the original database file. */  
28200   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28201   if( conchPath==0 ){
28202     return SQLITE_NOMEM;
28203   }
28204   memcpy(conchPath, dbPath, len+1);
28205   
28206   /* now insert a "." before the last / character */
28207   for( i=(len-1); i>=0; i-- ){
28208     if( conchPath[i]=='/' ){
28209       i++;
28210       break;
28211     }
28212   }
28213   conchPath[i]='.';
28214   while ( i<len ){
28215     conchPath[i+1]=dbPath[i];
28216     i++;
28217   }
28218
28219   /* append the "-conch" suffix to the file */
28220   memcpy(&conchPath[i+1], "-conch", 7);
28221   assert( (int)strlen(conchPath) == len+7 );
28222
28223   return SQLITE_OK;
28224 }
28225
28226
28227 /* Takes a fully configured proxy locking-style unix file and switches
28228 ** the local lock file path 
28229 */
28230 static int switchLockProxyPath(unixFile *pFile, const char *path) {
28231   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28232   char *oldPath = pCtx->lockProxyPath;
28233   int rc = SQLITE_OK;
28234
28235   if( pFile->eFileLock!=NO_LOCK ){
28236     return SQLITE_BUSY;
28237   }  
28238
28239   /* nothing to do if the path is NULL, :auto: or matches the existing path */
28240   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28241     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28242     return SQLITE_OK;
28243   }else{
28244     unixFile *lockProxy = pCtx->lockProxy;
28245     pCtx->lockProxy=NULL;
28246     pCtx->conchHeld = 0;
28247     if( lockProxy!=NULL ){
28248       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28249       if( rc ) return rc;
28250       sqlite3_free(lockProxy);
28251     }
28252     sqlite3_free(oldPath);
28253     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28254   }
28255   
28256   return rc;
28257 }
28258
28259 /*
28260 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
28261 ** is a string buffer at least MAXPATHLEN+1 characters in size.
28262 **
28263 ** This routine find the filename associated with pFile and writes it
28264 ** int dbPath.
28265 */
28266 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28267 #if defined(__APPLE__)
28268   if( pFile->pMethod == &afpIoMethods ){
28269     /* afp style keeps a reference to the db path in the filePath field 
28270     ** of the struct */
28271     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28272     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28273   } else
28274 #endif
28275   if( pFile->pMethod == &dotlockIoMethods ){
28276     /* dot lock style uses the locking context to store the dot lock
28277     ** file path */
28278     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28279     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28280   }else{
28281     /* all other styles use the locking context to store the db file path */
28282     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28283     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28284   }
28285   return SQLITE_OK;
28286 }
28287
28288 /*
28289 ** Takes an already filled in unix file and alters it so all file locking 
28290 ** will be performed on the local proxy lock file.  The following fields
28291 ** are preserved in the locking context so that they can be restored and 
28292 ** the unix structure properly cleaned up at close time:
28293 **  ->lockingContext
28294 **  ->pMethod
28295 */
28296 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28297   proxyLockingContext *pCtx;
28298   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28299   char *lockPath=NULL;
28300   int rc = SQLITE_OK;
28301   
28302   if( pFile->eFileLock!=NO_LOCK ){
28303     return SQLITE_BUSY;
28304   }
28305   proxyGetDbPathForUnixFile(pFile, dbPath);
28306   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28307     lockPath=NULL;
28308   }else{
28309     lockPath=(char *)path;
28310   }
28311   
28312   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28313            (lockPath ? lockPath : ":auto:"), getpid()));
28314
28315   pCtx = sqlite3_malloc( sizeof(*pCtx) );
28316   if( pCtx==0 ){
28317     return SQLITE_NOMEM;
28318   }
28319   memset(pCtx, 0, sizeof(*pCtx));
28320
28321   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28322   if( rc==SQLITE_OK ){
28323     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28324     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28325       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28326       ** (c) the file system is read-only, then enable no-locking access.
28327       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28328       ** that openFlags will have only one of O_RDONLY or O_RDWR.
28329       */
28330       struct statfs fsInfo;
28331       struct stat conchInfo;
28332       int goLockless = 0;
28333
28334       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28335         int err = errno;
28336         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28337           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28338         }
28339       }
28340       if( goLockless ){
28341         pCtx->conchHeld = -1; /* read only FS/ lockless */
28342         rc = SQLITE_OK;
28343       }
28344     }
28345   }  
28346   if( rc==SQLITE_OK && lockPath ){
28347     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28348   }
28349
28350   if( rc==SQLITE_OK ){
28351     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28352     if( pCtx->dbPath==NULL ){
28353       rc = SQLITE_NOMEM;
28354     }
28355   }
28356   if( rc==SQLITE_OK ){
28357     /* all memory is allocated, proxys are created and assigned, 
28358     ** switch the locking context and pMethod then return.
28359     */
28360     pCtx->oldLockingContext = pFile->lockingContext;
28361     pFile->lockingContext = pCtx;
28362     pCtx->pOldMethod = pFile->pMethod;
28363     pFile->pMethod = &proxyIoMethods;
28364   }else{
28365     if( pCtx->conchFile ){ 
28366       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28367       sqlite3_free(pCtx->conchFile);
28368     }
28369     sqlite3_free(pCtx->lockProxyPath);
28370     sqlite3_free(pCtx->conchFilePath); 
28371     sqlite3_free(pCtx);
28372   }
28373   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
28374            (rc==SQLITE_OK ? "ok" : "failed")));
28375   return rc;
28376 }
28377
28378
28379 /*
28380 ** This routine handles sqlite3_file_control() calls that are specific
28381 ** to proxy locking.
28382 */
28383 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
28384   switch( op ){
28385     case SQLITE_GET_LOCKPROXYFILE: {
28386       unixFile *pFile = (unixFile*)id;
28387       if( pFile->pMethod == &proxyIoMethods ){
28388         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28389         proxyTakeConch(pFile);
28390         if( pCtx->lockProxyPath ){
28391           *(const char **)pArg = pCtx->lockProxyPath;
28392         }else{
28393           *(const char **)pArg = ":auto: (not held)";
28394         }
28395       } else {
28396         *(const char **)pArg = NULL;
28397       }
28398       return SQLITE_OK;
28399     }
28400     case SQLITE_SET_LOCKPROXYFILE: {
28401       unixFile *pFile = (unixFile*)id;
28402       int rc = SQLITE_OK;
28403       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
28404       if( pArg==NULL || (const char *)pArg==0 ){
28405         if( isProxyStyle ){
28406           /* turn off proxy locking - not supported */
28407           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
28408         }else{
28409           /* turn off proxy locking - already off - NOOP */
28410           rc = SQLITE_OK;
28411         }
28412       }else{
28413         const char *proxyPath = (const char *)pArg;
28414         if( isProxyStyle ){
28415           proxyLockingContext *pCtx = 
28416             (proxyLockingContext*)pFile->lockingContext;
28417           if( !strcmp(pArg, ":auto:") 
28418            || (pCtx->lockProxyPath &&
28419                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
28420           ){
28421             rc = SQLITE_OK;
28422           }else{
28423             rc = switchLockProxyPath(pFile, proxyPath);
28424           }
28425         }else{
28426           /* turn on proxy file locking */
28427           rc = proxyTransformUnixFile(pFile, proxyPath);
28428         }
28429       }
28430       return rc;
28431     }
28432     default: {
28433       assert( 0 );  /* The call assures that only valid opcodes are sent */
28434     }
28435   }
28436   /*NOTREACHED*/
28437   return SQLITE_ERROR;
28438 }
28439
28440 /*
28441 ** Within this division (the proxying locking implementation) the procedures
28442 ** above this point are all utilities.  The lock-related methods of the
28443 ** proxy-locking sqlite3_io_method object follow.
28444 */
28445
28446
28447 /*
28448 ** This routine checks if there is a RESERVED lock held on the specified
28449 ** file by this or any other process. If such a lock is held, set *pResOut
28450 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28451 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28452 */
28453 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
28454   unixFile *pFile = (unixFile*)id;
28455   int rc = proxyTakeConch(pFile);
28456   if( rc==SQLITE_OK ){
28457     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28458     if( pCtx->conchHeld>0 ){
28459       unixFile *proxy = pCtx->lockProxy;
28460       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
28461     }else{ /* conchHeld < 0 is lockless */
28462       pResOut=0;
28463     }
28464   }
28465   return rc;
28466 }
28467
28468 /*
28469 ** Lock the file with the lock specified by parameter eFileLock - one
28470 ** of the following:
28471 **
28472 **     (1) SHARED_LOCK
28473 **     (2) RESERVED_LOCK
28474 **     (3) PENDING_LOCK
28475 **     (4) EXCLUSIVE_LOCK
28476 **
28477 ** Sometimes when requesting one lock state, additional lock states
28478 ** are inserted in between.  The locking might fail on one of the later
28479 ** transitions leaving the lock state different from what it started but
28480 ** still short of its goal.  The following chart shows the allowed
28481 ** transitions and the inserted intermediate states:
28482 **
28483 **    UNLOCKED -> SHARED
28484 **    SHARED -> RESERVED
28485 **    SHARED -> (PENDING) -> EXCLUSIVE
28486 **    RESERVED -> (PENDING) -> EXCLUSIVE
28487 **    PENDING -> EXCLUSIVE
28488 **
28489 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28490 ** routine to lower a locking level.
28491 */
28492 static int proxyLock(sqlite3_file *id, int eFileLock) {
28493   unixFile *pFile = (unixFile*)id;
28494   int rc = proxyTakeConch(pFile);
28495   if( rc==SQLITE_OK ){
28496     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28497     if( pCtx->conchHeld>0 ){
28498       unixFile *proxy = pCtx->lockProxy;
28499       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
28500       pFile->eFileLock = proxy->eFileLock;
28501     }else{
28502       /* conchHeld < 0 is lockless */
28503     }
28504   }
28505   return rc;
28506 }
28507
28508
28509 /*
28510 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28511 ** must be either NO_LOCK or SHARED_LOCK.
28512 **
28513 ** If the locking level of the file descriptor is already at or below
28514 ** the requested locking level, this routine is a no-op.
28515 */
28516 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
28517   unixFile *pFile = (unixFile*)id;
28518   int rc = proxyTakeConch(pFile);
28519   if( rc==SQLITE_OK ){
28520     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28521     if( pCtx->conchHeld>0 ){
28522       unixFile *proxy = pCtx->lockProxy;
28523       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
28524       pFile->eFileLock = proxy->eFileLock;
28525     }else{
28526       /* conchHeld < 0 is lockless */
28527     }
28528   }
28529   return rc;
28530 }
28531
28532 /*
28533 ** Close a file that uses proxy locks.
28534 */
28535 static int proxyClose(sqlite3_file *id) {
28536   if( id ){
28537     unixFile *pFile = (unixFile*)id;
28538     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28539     unixFile *lockProxy = pCtx->lockProxy;
28540     unixFile *conchFile = pCtx->conchFile;
28541     int rc = SQLITE_OK;
28542     
28543     if( lockProxy ){
28544       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
28545       if( rc ) return rc;
28546       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
28547       if( rc ) return rc;
28548       sqlite3_free(lockProxy);
28549       pCtx->lockProxy = 0;
28550     }
28551     if( conchFile ){
28552       if( pCtx->conchHeld ){
28553         rc = proxyReleaseConch(pFile);
28554         if( rc ) return rc;
28555       }
28556       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
28557       if( rc ) return rc;
28558       sqlite3_free(conchFile);
28559     }
28560     sqlite3_free(pCtx->lockProxyPath);
28561     sqlite3_free(pCtx->conchFilePath);
28562     sqlite3_free(pCtx->dbPath);
28563     /* restore the original locking context and pMethod then close it */
28564     pFile->lockingContext = pCtx->oldLockingContext;
28565     pFile->pMethod = pCtx->pOldMethod;
28566     sqlite3_free(pCtx);
28567     return pFile->pMethod->xClose(id);
28568   }
28569   return SQLITE_OK;
28570 }
28571
28572
28573
28574 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28575 /*
28576 ** The proxy locking style is intended for use with AFP filesystems.
28577 ** And since AFP is only supported on MacOSX, the proxy locking is also
28578 ** restricted to MacOSX.
28579 ** 
28580 **
28581 ******************* End of the proxy lock implementation **********************
28582 ******************************************************************************/
28583
28584 /*
28585 ** Initialize the operating system interface.
28586 **
28587 ** This routine registers all VFS implementations for unix-like operating
28588 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
28589 ** should be the only routines in this file that are visible from other
28590 ** files.
28591 **
28592 ** This routine is called once during SQLite initialization and by a
28593 ** single thread.  The memory allocation and mutex subsystems have not
28594 ** necessarily been initialized when this routine is called, and so they
28595 ** should not be used.
28596 */
28597 SQLITE_API int sqlite3_os_init(void){ 
28598   /* 
28599   ** The following macro defines an initializer for an sqlite3_vfs object.
28600   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
28601   ** to the "finder" function.  (pAppData is a pointer to a pointer because
28602   ** silly C90 rules prohibit a void* from being cast to a function pointer
28603   ** and so we have to go through the intermediate pointer to avoid problems
28604   ** when compiling with -pedantic-errors on GCC.)
28605   **
28606   ** The FINDER parameter to this macro is the name of the pointer to the
28607   ** finder-function.  The finder-function returns a pointer to the
28608   ** sqlite_io_methods object that implements the desired locking
28609   ** behaviors.  See the division above that contains the IOMETHODS
28610   ** macro for addition information on finder-functions.
28611   **
28612   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
28613   ** object.  But the "autolockIoFinder" available on MacOSX does a little
28614   ** more than that; it looks at the filesystem type that hosts the 
28615   ** database file and tries to choose an locking method appropriate for
28616   ** that filesystem time.
28617   */
28618   #define UNIXVFS(VFSNAME, FINDER) {                        \
28619     2,                    /* iVersion */                    \
28620     sizeof(unixFile),     /* szOsFile */                    \
28621     MAX_PATHNAME,         /* mxPathname */                  \
28622     0,                    /* pNext */                       \
28623     VFSNAME,              /* zName */                       \
28624     (void*)&FINDER,       /* pAppData */                    \
28625     unixOpen,             /* xOpen */                       \
28626     unixDelete,           /* xDelete */                     \
28627     unixAccess,           /* xAccess */                     \
28628     unixFullPathname,     /* xFullPathname */               \
28629     unixDlOpen,           /* xDlOpen */                     \
28630     unixDlError,          /* xDlError */                    \
28631     unixDlSym,            /* xDlSym */                      \
28632     unixDlClose,          /* xDlClose */                    \
28633     unixRandomness,       /* xRandomness */                 \
28634     unixSleep,            /* xSleep */                      \
28635     unixCurrentTime,      /* xCurrentTime */                \
28636     unixGetLastError,     /* xGetLastError */               \
28637     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
28638   }
28639
28640   /*
28641   ** All default VFSes for unix are contained in the following array.
28642   **
28643   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
28644   ** by the SQLite core when the VFS is registered.  So the following
28645   ** array cannot be const.
28646   */
28647   static sqlite3_vfs aVfs[] = {
28648 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
28649     UNIXVFS("unix",          autolockIoFinder ),
28650 #else
28651     UNIXVFS("unix",          posixIoFinder ),
28652 #endif
28653     UNIXVFS("unix-none",     nolockIoFinder ),
28654     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
28655 #if OS_VXWORKS
28656     UNIXVFS("unix-namedsem", semIoFinder ),
28657 #endif
28658 #if SQLITE_ENABLE_LOCKING_STYLE
28659     UNIXVFS("unix-posix",    posixIoFinder ),
28660 #if !OS_VXWORKS
28661     UNIXVFS("unix-flock",    flockIoFinder ),
28662 #endif
28663 #endif
28664 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28665     UNIXVFS("unix-afp",      afpIoFinder ),
28666     UNIXVFS("unix-nfs",      nfsIoFinder ),
28667     UNIXVFS("unix-proxy",    proxyIoFinder ),
28668 #endif
28669   };
28670   unsigned int i;          /* Loop counter */
28671
28672   /* Register all VFSes defined in the aVfs[] array */
28673   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
28674     sqlite3_vfs_register(&aVfs[i], i==0);
28675   }
28676   return SQLITE_OK; 
28677 }
28678
28679 /*
28680 ** Shutdown the operating system interface.
28681 **
28682 ** Some operating systems might need to do some cleanup in this routine,
28683 ** to release dynamically allocated objects.  But not on unix.
28684 ** This routine is a no-op for unix.
28685 */
28686 SQLITE_API int sqlite3_os_end(void){ 
28687   return SQLITE_OK; 
28688 }
28689  
28690 #endif /* SQLITE_OS_UNIX */
28691
28692 /************** End of os_unix.c *********************************************/
28693 /************** Begin file os_win.c ******************************************/
28694 /*
28695 ** 2004 May 22
28696 **
28697 ** The author disclaims copyright to this source code.  In place of
28698 ** a legal notice, here is a blessing:
28699 **
28700 **    May you do good and not evil.
28701 **    May you find forgiveness for yourself and forgive others.
28702 **    May you share freely, never taking more than you give.
28703 **
28704 ******************************************************************************
28705 **
28706 ** This file contains code that is specific to windows.
28707 */
28708 #if SQLITE_OS_WIN               /* This file is used for windows only */
28709
28710
28711 /*
28712 ** A Note About Memory Allocation:
28713 **
28714 ** This driver uses malloc()/free() directly rather than going through
28715 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
28716 ** are designed for use on embedded systems where memory is scarce and
28717 ** malloc failures happen frequently.  Win32 does not typically run on
28718 ** embedded systems, and when it does the developers normally have bigger
28719 ** problems to worry about than running out of memory.  So there is not
28720 ** a compelling need to use the wrappers.
28721 **
28722 ** But there is a good reason to not use the wrappers.  If we use the
28723 ** wrappers then we will get simulated malloc() failures within this
28724 ** driver.  And that causes all kinds of problems for our tests.  We
28725 ** could enhance SQLite to deal with simulated malloc failures within
28726 ** the OS driver, but the code to deal with those failure would not
28727 ** be exercised on Linux (which does not need to malloc() in the driver)
28728 ** and so we would have difficulty writing coverage tests for that
28729 ** code.  Better to leave the code out, we think.
28730 **
28731 ** The point of this discussion is as follows:  When creating a new
28732 ** OS layer for an embedded system, if you use this file as an example,
28733 ** avoid the use of malloc()/free().  Those routines work ok on windows
28734 ** desktops but not so well in embedded systems.
28735 */
28736
28737 #include <winbase.h>
28738
28739 #ifdef __CYGWIN__
28740 # include <sys/cygwin.h>
28741 #endif
28742
28743 /*
28744 ** Macros used to determine whether or not to use threads.
28745 */
28746 #if defined(THREADSAFE) && THREADSAFE
28747 # define SQLITE_W32_THREADS 1
28748 #endif
28749
28750 /*
28751 ** Include code that is common to all os_*.c files
28752 */
28753 /************** Include os_common.h in the middle of os_win.c ****************/
28754 /************** Begin file os_common.h ***************************************/
28755 /*
28756 ** 2004 May 22
28757 **
28758 ** The author disclaims copyright to this source code.  In place of
28759 ** a legal notice, here is a blessing:
28760 **
28761 **    May you do good and not evil.
28762 **    May you find forgiveness for yourself and forgive others.
28763 **    May you share freely, never taking more than you give.
28764 **
28765 ******************************************************************************
28766 **
28767 ** This file contains macros and a little bit of code that is common to
28768 ** all of the platform-specific files (os_*.c) and is #included into those
28769 ** files.
28770 **
28771 ** This file should be #included by the os_*.c files only.  It is not a
28772 ** general purpose header file.
28773 */
28774 #ifndef _OS_COMMON_H_
28775 #define _OS_COMMON_H_
28776
28777 /*
28778 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
28779 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
28780 ** switch.  The following code should catch this problem at compile-time.
28781 */
28782 #ifdef MEMORY_DEBUG
28783 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
28784 #endif
28785
28786 #ifdef SQLITE_DEBUG
28787 SQLITE_PRIVATE int sqlite3OSTrace = 0;
28788 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
28789 #else
28790 #define OSTRACE(X)
28791 #endif
28792
28793 /*
28794 ** Macros for performance tracing.  Normally turned off.  Only works
28795 ** on i486 hardware.
28796 */
28797 #ifdef SQLITE_PERFORMANCE_TRACE
28798
28799 /* 
28800 ** hwtime.h contains inline assembler code for implementing 
28801 ** high-performance timing routines.
28802 */
28803 /************** Include hwtime.h in the middle of os_common.h ****************/
28804 /************** Begin file hwtime.h ******************************************/
28805 /*
28806 ** 2008 May 27
28807 **
28808 ** The author disclaims copyright to this source code.  In place of
28809 ** a legal notice, here is a blessing:
28810 **
28811 **    May you do good and not evil.
28812 **    May you find forgiveness for yourself and forgive others.
28813 **    May you share freely, never taking more than you give.
28814 **
28815 ******************************************************************************
28816 **
28817 ** This file contains inline asm code for retrieving "high-performance"
28818 ** counters for x86 class CPUs.
28819 */
28820 #ifndef _HWTIME_H_
28821 #define _HWTIME_H_
28822
28823 /*
28824 ** The following routine only works on pentium-class (or newer) processors.
28825 ** It uses the RDTSC opcode to read the cycle count value out of the
28826 ** processor and returns that value.  This can be used for high-res
28827 ** profiling.
28828 */
28829 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
28830       (defined(i386) || defined(__i386__) || defined(_M_IX86))
28831
28832   #if defined(__GNUC__)
28833
28834   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28835      unsigned int lo, hi;
28836      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
28837      return (sqlite_uint64)hi << 32 | lo;
28838   }
28839
28840   #elif defined(_MSC_VER)
28841
28842   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
28843      __asm {
28844         rdtsc
28845         ret       ; return value at EDX:EAX
28846      }
28847   }
28848
28849   #endif
28850
28851 #elif (defined(__GNUC__) && defined(__x86_64__))
28852
28853   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28854       unsigned long val;
28855       __asm__ __volatile__ ("rdtsc" : "=A" (val));
28856       return val;
28857   }
28858  
28859 #elif (defined(__GNUC__) && defined(__ppc__))
28860
28861   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28862       unsigned long long retval;
28863       unsigned long junk;
28864       __asm__ __volatile__ ("\n\
28865           1:      mftbu   %1\n\
28866                   mftb    %L0\n\
28867                   mftbu   %0\n\
28868                   cmpw    %0,%1\n\
28869                   bne     1b"
28870                   : "=r" (retval), "=r" (junk));
28871       return retval;
28872   }
28873
28874 #else
28875
28876   #error Need implementation of sqlite3Hwtime() for your platform.
28877
28878   /*
28879   ** To compile without implementing sqlite3Hwtime() for your platform,
28880   ** you can remove the above #error and use the following
28881   ** stub function.  You will lose timing support for many
28882   ** of the debugging and testing utilities, but it should at
28883   ** least compile and run.
28884   */
28885 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
28886
28887 #endif
28888
28889 #endif /* !defined(_HWTIME_H_) */
28890
28891 /************** End of hwtime.h **********************************************/
28892 /************** Continuing where we left off in os_common.h ******************/
28893
28894 static sqlite_uint64 g_start;
28895 static sqlite_uint64 g_elapsed;
28896 #define TIMER_START       g_start=sqlite3Hwtime()
28897 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
28898 #define TIMER_ELAPSED     g_elapsed
28899 #else
28900 #define TIMER_START
28901 #define TIMER_END
28902 #define TIMER_ELAPSED     ((sqlite_uint64)0)
28903 #endif
28904
28905 /*
28906 ** If we compile with the SQLITE_TEST macro set, then the following block
28907 ** of code will give us the ability to simulate a disk I/O error.  This
28908 ** is used for testing the I/O recovery logic.
28909 */
28910 #ifdef SQLITE_TEST
28911 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
28912 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
28913 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
28914 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
28915 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
28916 SQLITE_API int sqlite3_diskfull_pending = 0;
28917 SQLITE_API int sqlite3_diskfull = 0;
28918 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
28919 #define SimulateIOError(CODE)  \
28920   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
28921        || sqlite3_io_error_pending-- == 1 )  \
28922               { local_ioerr(); CODE; }
28923 static void local_ioerr(){
28924   IOTRACE(("IOERR\n"));
28925   sqlite3_io_error_hit++;
28926   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
28927 }
28928 #define SimulateDiskfullError(CODE) \
28929    if( sqlite3_diskfull_pending ){ \
28930      if( sqlite3_diskfull_pending == 1 ){ \
28931        local_ioerr(); \
28932        sqlite3_diskfull = 1; \
28933        sqlite3_io_error_hit = 1; \
28934        CODE; \
28935      }else{ \
28936        sqlite3_diskfull_pending--; \
28937      } \
28938    }
28939 #else
28940 #define SimulateIOErrorBenign(X)
28941 #define SimulateIOError(A)
28942 #define SimulateDiskfullError(A)
28943 #endif
28944
28945 /*
28946 ** When testing, keep a count of the number of open files.
28947 */
28948 #ifdef SQLITE_TEST
28949 SQLITE_API int sqlite3_open_file_count = 0;
28950 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
28951 #else
28952 #define OpenCounter(X)
28953 #endif
28954
28955 #endif /* !defined(_OS_COMMON_H_) */
28956
28957 /************** End of os_common.h *******************************************/
28958 /************** Continuing where we left off in os_win.c *********************/
28959
28960 /*
28961 ** Some microsoft compilers lack this definition.
28962 */
28963 #ifndef INVALID_FILE_ATTRIBUTES
28964 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
28965 #endif
28966
28967 /*
28968 ** Determine if we are dealing with WindowsCE - which has a much
28969 ** reduced API.
28970 */
28971 #if SQLITE_OS_WINCE
28972 # define AreFileApisANSI() 1
28973 # define FormatMessageW(a,b,c,d,e,f,g) 0
28974 #endif
28975
28976 /* Forward references */
28977 typedef struct winShm winShm;           /* A connection to shared-memory */
28978 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
28979
28980 /*
28981 ** WinCE lacks native support for file locking so we have to fake it
28982 ** with some code of our own.
28983 */
28984 #if SQLITE_OS_WINCE
28985 typedef struct winceLock {
28986   int nReaders;       /* Number of reader locks obtained */
28987   BOOL bPending;      /* Indicates a pending lock has been obtained */
28988   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
28989   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
28990 } winceLock;
28991 #endif
28992
28993 /*
28994 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
28995 ** portability layer.
28996 */
28997 typedef struct winFile winFile;
28998 struct winFile {
28999   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29000   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29001   HANDLE h;               /* Handle for accessing the file */
29002   unsigned char locktype; /* Type of lock currently held on this file */
29003   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29004   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29005   DWORD sectorSize;       /* Sector size of the device file is on */
29006   winShm *pShm;           /* Instance of shared memory on this file */
29007   const char *zPath;      /* Full pathname of this file */
29008 #if SQLITE_OS_WINCE
29009   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29010   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29011   HANDLE hShared;         /* Shared memory segment used for locking */
29012   winceLock local;        /* Locks obtained by this instance of winFile */
29013   winceLock *shared;      /* Global shared lock memory for the file  */
29014 #endif
29015 };
29016
29017 /*
29018 ** Forward prototypes.
29019 */
29020 static int getSectorSize(
29021     sqlite3_vfs *pVfs,
29022     const char *zRelative     /* UTF-8 file name */
29023 );
29024
29025 /*
29026 ** The following variable is (normally) set once and never changes
29027 ** thereafter.  It records whether the operating system is Win95
29028 ** or WinNT.
29029 **
29030 ** 0:   Operating system unknown.
29031 ** 1:   Operating system is Win95.
29032 ** 2:   Operating system is WinNT.
29033 **
29034 ** In order to facilitate testing on a WinNT system, the test fixture
29035 ** can manually set this value to 1 to emulate Win98 behavior.
29036 */
29037 #ifdef SQLITE_TEST
29038 SQLITE_API int sqlite3_os_type = 0;
29039 #else
29040 static int sqlite3_os_type = 0;
29041 #endif
29042
29043 /*
29044 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29045 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29046 **
29047 ** Here is an interesting observation:  Win95, Win98, and WinME lack
29048 ** the LockFileEx() API.  But we can still statically link against that
29049 ** API as long as we don't call it when running Win95/98/ME.  A call to
29050 ** this routine is used to determine if the host is Win95/98/ME or
29051 ** WinNT/2K/XP so that we will know whether or not we can safely call
29052 ** the LockFileEx() API.
29053 */
29054 #if SQLITE_OS_WINCE
29055 # define isNT()  (1)
29056 #else
29057   static int isNT(void){
29058     if( sqlite3_os_type==0 ){
29059       OSVERSIONINFO sInfo;
29060       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29061       GetVersionEx(&sInfo);
29062       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29063     }
29064     return sqlite3_os_type==2;
29065   }
29066 #endif /* SQLITE_OS_WINCE */
29067
29068 /*
29069 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
29070 **
29071 ** Space to hold the returned string is obtained from malloc.
29072 */
29073 static WCHAR *utf8ToUnicode(const char *zFilename){
29074   int nChar;
29075   WCHAR *zWideFilename;
29076
29077   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29078   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29079   if( zWideFilename==0 ){
29080     return 0;
29081   }
29082   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29083   if( nChar==0 ){
29084     free(zWideFilename);
29085     zWideFilename = 0;
29086   }
29087   return zWideFilename;
29088 }
29089
29090 /*
29091 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29092 ** obtained from malloc().
29093 */
29094 static char *unicodeToUtf8(const WCHAR *zWideFilename){
29095   int nByte;
29096   char *zFilename;
29097
29098   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29099   zFilename = malloc( nByte );
29100   if( zFilename==0 ){
29101     return 0;
29102   }
29103   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29104                               0, 0);
29105   if( nByte == 0 ){
29106     free(zFilename);
29107     zFilename = 0;
29108   }
29109   return zFilename;
29110 }
29111
29112 /*
29113 ** Convert an ansi string to microsoft unicode, based on the
29114 ** current codepage settings for file apis.
29115 ** 
29116 ** Space to hold the returned string is obtained
29117 ** from malloc.
29118 */
29119 static WCHAR *mbcsToUnicode(const char *zFilename){
29120   int nByte;
29121   WCHAR *zMbcsFilename;
29122   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29123
29124   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29125   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29126   if( zMbcsFilename==0 ){
29127     return 0;
29128   }
29129   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29130   if( nByte==0 ){
29131     free(zMbcsFilename);
29132     zMbcsFilename = 0;
29133   }
29134   return zMbcsFilename;
29135 }
29136
29137 /*
29138 ** Convert microsoft unicode to multibyte character string, based on the
29139 ** user's Ansi codepage.
29140 **
29141 ** Space to hold the returned string is obtained from
29142 ** malloc().
29143 */
29144 static char *unicodeToMbcs(const WCHAR *zWideFilename){
29145   int nByte;
29146   char *zFilename;
29147   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29148
29149   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29150   zFilename = malloc( nByte );
29151   if( zFilename==0 ){
29152     return 0;
29153   }
29154   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29155                               0, 0);
29156   if( nByte == 0 ){
29157     free(zFilename);
29158     zFilename = 0;
29159   }
29160   return zFilename;
29161 }
29162
29163 /*
29164 ** Convert multibyte character string to UTF-8.  Space to hold the
29165 ** returned string is obtained from malloc().
29166 */
29167 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29168   char *zFilenameUtf8;
29169   WCHAR *zTmpWide;
29170
29171   zTmpWide = mbcsToUnicode(zFilename);
29172   if( zTmpWide==0 ){
29173     return 0;
29174   }
29175   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29176   free(zTmpWide);
29177   return zFilenameUtf8;
29178 }
29179
29180 /*
29181 ** Convert UTF-8 to multibyte character string.  Space to hold the 
29182 ** returned string is obtained from malloc().
29183 */
29184 static char *utf8ToMbcs(const char *zFilename){
29185   char *zFilenameMbcs;
29186   WCHAR *zTmpWide;
29187
29188   zTmpWide = utf8ToUnicode(zFilename);
29189   if( zTmpWide==0 ){
29190     return 0;
29191   }
29192   zFilenameMbcs = unicodeToMbcs(zTmpWide);
29193   free(zTmpWide);
29194   return zFilenameMbcs;
29195 }
29196
29197 #if SQLITE_OS_WINCE
29198 /*************************************************************************
29199 ** This section contains code for WinCE only.
29200 */
29201 /*
29202 ** WindowsCE does not have a localtime() function.  So create a
29203 ** substitute.
29204 */
29205 struct tm *__cdecl localtime(const time_t *t)
29206 {
29207   static struct tm y;
29208   FILETIME uTm, lTm;
29209   SYSTEMTIME pTm;
29210   sqlite3_int64 t64;
29211   t64 = *t;
29212   t64 = (t64 + 11644473600)*10000000;
29213   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29214   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29215   FileTimeToLocalFileTime(&uTm,&lTm);
29216   FileTimeToSystemTime(&lTm,&pTm);
29217   y.tm_year = pTm.wYear - 1900;
29218   y.tm_mon = pTm.wMonth - 1;
29219   y.tm_wday = pTm.wDayOfWeek;
29220   y.tm_mday = pTm.wDay;
29221   y.tm_hour = pTm.wHour;
29222   y.tm_min = pTm.wMinute;
29223   y.tm_sec = pTm.wSecond;
29224   return &y;
29225 }
29226
29227 /* This will never be called, but defined to make the code compile */
29228 #define GetTempPathA(a,b)
29229
29230 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29231 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29232 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29233
29234 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29235
29236 /*
29237 ** Acquire a lock on the handle h
29238 */
29239 static void winceMutexAcquire(HANDLE h){
29240    DWORD dwErr;
29241    do {
29242      dwErr = WaitForSingleObject(h, INFINITE);
29243    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29244 }
29245 /*
29246 ** Release a lock acquired by winceMutexAcquire()
29247 */
29248 #define winceMutexRelease(h) ReleaseMutex(h)
29249
29250 /*
29251 ** Create the mutex and shared memory used for locking in the file
29252 ** descriptor pFile
29253 */
29254 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29255   WCHAR *zTok;
29256   WCHAR *zName = utf8ToUnicode(zFilename);
29257   BOOL bInit = TRUE;
29258
29259   /* Initialize the local lockdata */
29260   ZeroMemory(&pFile->local, sizeof(pFile->local));
29261
29262   /* Replace the backslashes from the filename and lowercase it
29263   ** to derive a mutex name. */
29264   zTok = CharLowerW(zName);
29265   for (;*zTok;zTok++){
29266     if (*zTok == '\\') *zTok = '_';
29267   }
29268
29269   /* Create/open the named mutex */
29270   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29271   if (!pFile->hMutex){
29272     pFile->lastErrno = GetLastError();
29273     free(zName);
29274     return FALSE;
29275   }
29276
29277   /* Acquire the mutex before continuing */
29278   winceMutexAcquire(pFile->hMutex);
29279   
29280   /* Since the names of named mutexes, semaphores, file mappings etc are 
29281   ** case-sensitive, take advantage of that by uppercasing the mutex name
29282   ** and using that as the shared filemapping name.
29283   */
29284   CharUpperW(zName);
29285   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29286                                        PAGE_READWRITE, 0, sizeof(winceLock),
29287                                        zName);  
29288
29289   /* Set a flag that indicates we're the first to create the memory so it 
29290   ** must be zero-initialized */
29291   if (GetLastError() == ERROR_ALREADY_EXISTS){
29292     bInit = FALSE;
29293   }
29294
29295   free(zName);
29296
29297   /* If we succeeded in making the shared memory handle, map it. */
29298   if (pFile->hShared){
29299     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
29300              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29301     /* If mapping failed, close the shared memory handle and erase it */
29302     if (!pFile->shared){
29303       pFile->lastErrno = GetLastError();
29304       CloseHandle(pFile->hShared);
29305       pFile->hShared = NULL;
29306     }
29307   }
29308
29309   /* If shared memory could not be created, then close the mutex and fail */
29310   if (pFile->hShared == NULL){
29311     winceMutexRelease(pFile->hMutex);
29312     CloseHandle(pFile->hMutex);
29313     pFile->hMutex = NULL;
29314     return FALSE;
29315   }
29316   
29317   /* Initialize the shared memory if we're supposed to */
29318   if (bInit) {
29319     ZeroMemory(pFile->shared, sizeof(winceLock));
29320   }
29321
29322   winceMutexRelease(pFile->hMutex);
29323   return TRUE;
29324 }
29325
29326 /*
29327 ** Destroy the part of winFile that deals with wince locks
29328 */
29329 static void winceDestroyLock(winFile *pFile){
29330   if (pFile->hMutex){
29331     /* Acquire the mutex */
29332     winceMutexAcquire(pFile->hMutex);
29333
29334     /* The following blocks should probably assert in debug mode, but they
29335        are to cleanup in case any locks remained open */
29336     if (pFile->local.nReaders){
29337       pFile->shared->nReaders --;
29338     }
29339     if (pFile->local.bReserved){
29340       pFile->shared->bReserved = FALSE;
29341     }
29342     if (pFile->local.bPending){
29343       pFile->shared->bPending = FALSE;
29344     }
29345     if (pFile->local.bExclusive){
29346       pFile->shared->bExclusive = FALSE;
29347     }
29348
29349     /* De-reference and close our copy of the shared memory handle */
29350     UnmapViewOfFile(pFile->shared);
29351     CloseHandle(pFile->hShared);
29352
29353     /* Done with the mutex */
29354     winceMutexRelease(pFile->hMutex);    
29355     CloseHandle(pFile->hMutex);
29356     pFile->hMutex = NULL;
29357   }
29358 }
29359
29360 /* 
29361 ** An implementation of the LockFile() API of windows for wince
29362 */
29363 static BOOL winceLockFile(
29364   HANDLE *phFile,
29365   DWORD dwFileOffsetLow,
29366   DWORD dwFileOffsetHigh,
29367   DWORD nNumberOfBytesToLockLow,
29368   DWORD nNumberOfBytesToLockHigh
29369 ){
29370   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29371   BOOL bReturn = FALSE;
29372
29373   UNUSED_PARAMETER(dwFileOffsetHigh);
29374   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29375
29376   if (!pFile->hMutex) return TRUE;
29377   winceMutexAcquire(pFile->hMutex);
29378
29379   /* Wanting an exclusive lock? */
29380   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
29381        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29382     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
29383        pFile->shared->bExclusive = TRUE;
29384        pFile->local.bExclusive = TRUE;
29385        bReturn = TRUE;
29386     }
29387   }
29388
29389   /* Want a read-only lock? */
29390   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
29391            nNumberOfBytesToLockLow == 1){
29392     if (pFile->shared->bExclusive == 0){
29393       pFile->local.nReaders ++;
29394       if (pFile->local.nReaders == 1){
29395         pFile->shared->nReaders ++;
29396       }
29397       bReturn = TRUE;
29398     }
29399   }
29400
29401   /* Want a pending lock? */
29402   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
29403     /* If no pending lock has been acquired, then acquire it */
29404     if (pFile->shared->bPending == 0) {
29405       pFile->shared->bPending = TRUE;
29406       pFile->local.bPending = TRUE;
29407       bReturn = TRUE;
29408     }
29409   }
29410
29411   /* Want a reserved lock? */
29412   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
29413     if (pFile->shared->bReserved == 0) {
29414       pFile->shared->bReserved = TRUE;
29415       pFile->local.bReserved = TRUE;
29416       bReturn = TRUE;
29417     }
29418   }
29419
29420   winceMutexRelease(pFile->hMutex);
29421   return bReturn;
29422 }
29423
29424 /*
29425 ** An implementation of the UnlockFile API of windows for wince
29426 */
29427 static BOOL winceUnlockFile(
29428   HANDLE *phFile,
29429   DWORD dwFileOffsetLow,
29430   DWORD dwFileOffsetHigh,
29431   DWORD nNumberOfBytesToUnlockLow,
29432   DWORD nNumberOfBytesToUnlockHigh
29433 ){
29434   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29435   BOOL bReturn = FALSE;
29436
29437   UNUSED_PARAMETER(dwFileOffsetHigh);
29438   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
29439
29440   if (!pFile->hMutex) return TRUE;
29441   winceMutexAcquire(pFile->hMutex);
29442
29443   /* Releasing a reader lock or an exclusive lock */
29444   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
29445     /* Did we have an exclusive lock? */
29446     if (pFile->local.bExclusive){
29447       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
29448       pFile->local.bExclusive = FALSE;
29449       pFile->shared->bExclusive = FALSE;
29450       bReturn = TRUE;
29451     }
29452
29453     /* Did we just have a reader lock? */
29454     else if (pFile->local.nReaders){
29455       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
29456       pFile->local.nReaders --;
29457       if (pFile->local.nReaders == 0)
29458       {
29459         pFile->shared->nReaders --;
29460       }
29461       bReturn = TRUE;
29462     }
29463   }
29464
29465   /* Releasing a pending lock */
29466   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
29467     if (pFile->local.bPending){
29468       pFile->local.bPending = FALSE;
29469       pFile->shared->bPending = FALSE;
29470       bReturn = TRUE;
29471     }
29472   }
29473   /* Releasing a reserved lock */
29474   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
29475     if (pFile->local.bReserved) {
29476       pFile->local.bReserved = FALSE;
29477       pFile->shared->bReserved = FALSE;
29478       bReturn = TRUE;
29479     }
29480   }
29481
29482   winceMutexRelease(pFile->hMutex);
29483   return bReturn;
29484 }
29485
29486 /*
29487 ** An implementation of the LockFileEx() API of windows for wince
29488 */
29489 static BOOL winceLockFileEx(
29490   HANDLE *phFile,
29491   DWORD dwFlags,
29492   DWORD dwReserved,
29493   DWORD nNumberOfBytesToLockLow,
29494   DWORD nNumberOfBytesToLockHigh,
29495   LPOVERLAPPED lpOverlapped
29496 ){
29497   UNUSED_PARAMETER(dwReserved);
29498   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29499
29500   /* If the caller wants a shared read lock, forward this call
29501   ** to winceLockFile */
29502   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
29503       dwFlags == 1 &&
29504       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29505     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
29506   }
29507   return FALSE;
29508 }
29509 /*
29510 ** End of the special code for wince
29511 *****************************************************************************/
29512 #endif /* SQLITE_OS_WINCE */
29513
29514 /*****************************************************************************
29515 ** The next group of routines implement the I/O methods specified
29516 ** by the sqlite3_io_methods object.
29517 ******************************************************************************/
29518
29519 /*
29520 ** Close a file.
29521 **
29522 ** It is reported that an attempt to close a handle might sometimes
29523 ** fail.  This is a very unreasonable result, but windows is notorious
29524 ** for being unreasonable so I do not doubt that it might happen.  If
29525 ** the close fails, we pause for 100 milliseconds and try again.  As
29526 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
29527 ** giving up and returning an error.
29528 */
29529 #define MX_CLOSE_ATTEMPT 3
29530 static int winClose(sqlite3_file *id){
29531   int rc, cnt = 0;
29532   winFile *pFile = (winFile*)id;
29533
29534   assert( id!=0 );
29535   assert( pFile->pShm==0 );
29536   OSTRACE(("CLOSE %d\n", pFile->h));
29537   do{
29538     rc = CloseHandle(pFile->h);
29539     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
29540   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
29541 #if SQLITE_OS_WINCE
29542 #define WINCE_DELETION_ATTEMPTS 3
29543   winceDestroyLock(pFile);
29544   if( pFile->zDeleteOnClose ){
29545     int cnt = 0;
29546     while(
29547            DeleteFileW(pFile->zDeleteOnClose)==0
29548         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
29549         && cnt++ < WINCE_DELETION_ATTEMPTS
29550     ){
29551        Sleep(100);  /* Wait a little before trying again */
29552     }
29553     free(pFile->zDeleteOnClose);
29554   }
29555 #endif
29556   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
29557   OpenCounter(-1);
29558   return rc ? SQLITE_OK : SQLITE_IOERR;
29559 }
29560
29561 /*
29562 ** Some microsoft compilers lack this definition.
29563 */
29564 #ifndef INVALID_SET_FILE_POINTER
29565 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
29566 #endif
29567
29568 /*
29569 ** Read data from a file into a buffer.  Return SQLITE_OK if all
29570 ** bytes were read successfully and SQLITE_IOERR if anything goes
29571 ** wrong.
29572 */
29573 static int winRead(
29574   sqlite3_file *id,          /* File to read from */
29575   void *pBuf,                /* Write content into this buffer */
29576   int amt,                   /* Number of bytes to read */
29577   sqlite3_int64 offset       /* Begin reading at this offset */
29578 ){
29579   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29580   LONG lowerBits = (LONG)(offset & 0xffffffff);
29581   DWORD rc;
29582   winFile *pFile = (winFile*)id;
29583   DWORD error;
29584   DWORD got;
29585
29586   assert( id!=0 );
29587   SimulateIOError(return SQLITE_IOERR_READ);
29588   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
29589   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29590   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29591     pFile->lastErrno = error;
29592     return SQLITE_FULL;
29593   }
29594   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
29595     pFile->lastErrno = GetLastError();
29596     return SQLITE_IOERR_READ;
29597   }
29598   if( got==(DWORD)amt ){
29599     return SQLITE_OK;
29600   }else{
29601     /* Unread parts of the buffer must be zero-filled */
29602     memset(&((char*)pBuf)[got], 0, amt-got);
29603     return SQLITE_IOERR_SHORT_READ;
29604   }
29605 }
29606
29607 /*
29608 ** Write data from a buffer into a file.  Return SQLITE_OK on success
29609 ** or some other error code on failure.
29610 */
29611 static int winWrite(
29612   sqlite3_file *id,         /* File to write into */
29613   const void *pBuf,         /* The bytes to be written */
29614   int amt,                  /* Number of bytes to write */
29615   sqlite3_int64 offset      /* Offset into the file to begin writing at */
29616 ){
29617   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29618   LONG lowerBits = (LONG)(offset & 0xffffffff);
29619   DWORD rc;
29620   winFile *pFile = (winFile*)id;
29621   DWORD error;
29622   DWORD wrote = 0;
29623
29624   assert( id!=0 );
29625   SimulateIOError(return SQLITE_IOERR_WRITE);
29626   SimulateDiskfullError(return SQLITE_FULL);
29627   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
29628   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29629   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29630     pFile->lastErrno = error;
29631     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29632       return SQLITE_FULL;
29633     }else{
29634       return SQLITE_IOERR_WRITE;
29635     }
29636   }
29637   assert( amt>0 );
29638   while(
29639      amt>0
29640      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
29641      && wrote>0
29642   ){
29643     amt -= wrote;
29644     pBuf = &((char*)pBuf)[wrote];
29645   }
29646   if( !rc || amt>(int)wrote ){
29647     pFile->lastErrno = GetLastError();
29648     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29649       return SQLITE_FULL;
29650     }else{
29651       return SQLITE_IOERR_WRITE;
29652     }
29653   }
29654   return SQLITE_OK;
29655 }
29656
29657 /*
29658 ** Truncate an open file to a specified size
29659 */
29660 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
29661   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
29662   LONG lowerBits = (LONG)(nByte & 0xffffffff);
29663   DWORD dwRet;
29664   winFile *pFile = (winFile*)id;
29665   DWORD error;
29666   int rc = SQLITE_OK;
29667
29668   assert( id!=0 );
29669   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
29670   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
29671   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29672   if( dwRet==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29673     pFile->lastErrno = error;
29674     rc = SQLITE_IOERR_TRUNCATE;
29675   /* SetEndOfFile will fail if nByte is negative */
29676   }else if( !SetEndOfFile(pFile->h) ){
29677     pFile->lastErrno = GetLastError();
29678     rc = SQLITE_IOERR_TRUNCATE;
29679   }
29680   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc==SQLITE_OK ? "ok" : "failed"));
29681   return rc;
29682 }
29683
29684 #ifdef SQLITE_TEST
29685 /*
29686 ** Count the number of fullsyncs and normal syncs.  This is used to test
29687 ** that syncs and fullsyncs are occuring at the right times.
29688 */
29689 SQLITE_API int sqlite3_sync_count = 0;
29690 SQLITE_API int sqlite3_fullsync_count = 0;
29691 #endif
29692
29693 /*
29694 ** Make sure all writes to a particular file are committed to disk.
29695 */
29696 static int winSync(sqlite3_file *id, int flags){
29697 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
29698   winFile *pFile = (winFile*)id;
29699 #else
29700   UNUSED_PARAMETER(id);
29701 #endif
29702
29703   assert( pFile );
29704   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
29705   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
29706       || (flags&0x0F)==SQLITE_SYNC_FULL
29707   );
29708
29709   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
29710
29711 #ifndef SQLITE_TEST
29712   UNUSED_PARAMETER(flags);
29713 #else
29714   if( flags & SQLITE_SYNC_FULL ){
29715     sqlite3_fullsync_count++;
29716   }
29717   sqlite3_sync_count++;
29718 #endif
29719
29720   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
29721   ** line is to test that doing so does not cause any problems.
29722   */
29723   SimulateDiskfullError( return SQLITE_FULL );
29724   SimulateIOError( return SQLITE_IOERR; );
29725
29726   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
29727   ** no-op
29728   */
29729 #ifdef SQLITE_NO_SYNC
29730   return SQLITE_OK;
29731 #else
29732   if( FlushFileBuffers(pFile->h) ){
29733     return SQLITE_OK;
29734   }else{
29735     pFile->lastErrno = GetLastError();
29736     return SQLITE_IOERR;
29737   }
29738 #endif
29739 }
29740
29741 /*
29742 ** Determine the current size of a file in bytes
29743 */
29744 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
29745   DWORD upperBits;
29746   DWORD lowerBits;
29747   winFile *pFile = (winFile*)id;
29748   DWORD error;
29749
29750   assert( id!=0 );
29751   SimulateIOError(return SQLITE_IOERR_FSTAT);
29752   lowerBits = GetFileSize(pFile->h, &upperBits);
29753   if(   (lowerBits == INVALID_FILE_SIZE)
29754      && ((error = GetLastError()) != NO_ERROR) )
29755   {
29756     pFile->lastErrno = error;
29757     return SQLITE_IOERR_FSTAT;
29758   }
29759   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
29760   return SQLITE_OK;
29761 }
29762
29763 /*
29764 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
29765 */
29766 #ifndef LOCKFILE_FAIL_IMMEDIATELY
29767 # define LOCKFILE_FAIL_IMMEDIATELY 1
29768 #endif
29769
29770 /*
29771 ** Acquire a reader lock.
29772 ** Different API routines are called depending on whether or not this
29773 ** is Win95 or WinNT.
29774 */
29775 static int getReadLock(winFile *pFile){
29776   int res;
29777   if( isNT() ){
29778     OVERLAPPED ovlp;
29779     ovlp.Offset = SHARED_FIRST;
29780     ovlp.OffsetHigh = 0;
29781     ovlp.hEvent = 0;
29782     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
29783                      0, SHARED_SIZE, 0, &ovlp);
29784 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29785 */
29786 #if SQLITE_OS_WINCE==0
29787   }else{
29788     int lk;
29789     sqlite3_randomness(sizeof(lk), &lk);
29790     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
29791     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
29792 #endif
29793   }
29794   if( res == 0 ){
29795     pFile->lastErrno = GetLastError();
29796   }
29797   return res;
29798 }
29799
29800 /*
29801 ** Undo a readlock
29802 */
29803 static int unlockReadLock(winFile *pFile){
29804   int res;
29805   if( isNT() ){
29806     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29807 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29808 */
29809 #if SQLITE_OS_WINCE==0
29810   }else{
29811     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
29812 #endif
29813   }
29814   if( res == 0 ){
29815     pFile->lastErrno = GetLastError();
29816   }
29817   return res;
29818 }
29819
29820 /*
29821 ** Lock the file with the lock specified by parameter locktype - one
29822 ** of the following:
29823 **
29824 **     (1) SHARED_LOCK
29825 **     (2) RESERVED_LOCK
29826 **     (3) PENDING_LOCK
29827 **     (4) EXCLUSIVE_LOCK
29828 **
29829 ** Sometimes when requesting one lock state, additional lock states
29830 ** are inserted in between.  The locking might fail on one of the later
29831 ** transitions leaving the lock state different from what it started but
29832 ** still short of its goal.  The following chart shows the allowed
29833 ** transitions and the inserted intermediate states:
29834 **
29835 **    UNLOCKED -> SHARED
29836 **    SHARED -> RESERVED
29837 **    SHARED -> (PENDING) -> EXCLUSIVE
29838 **    RESERVED -> (PENDING) -> EXCLUSIVE
29839 **    PENDING -> EXCLUSIVE
29840 **
29841 ** This routine will only increase a lock.  The winUnlock() routine
29842 ** erases all locks at once and returns us immediately to locking level 0.
29843 ** It is not possible to lower the locking level one step at a time.  You
29844 ** must go straight to locking level 0.
29845 */
29846 static int winLock(sqlite3_file *id, int locktype){
29847   int rc = SQLITE_OK;    /* Return code from subroutines */
29848   int res = 1;           /* Result of a windows lock call */
29849   int newLocktype;       /* Set pFile->locktype to this value before exiting */
29850   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
29851   winFile *pFile = (winFile*)id;
29852   DWORD error = NO_ERROR;
29853
29854   assert( id!=0 );
29855   OSTRACE(("LOCK %d %d was %d(%d)\n",
29856            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
29857
29858   /* If there is already a lock of this type or more restrictive on the
29859   ** OsFile, do nothing. Don't use the end_lock: exit path, as
29860   ** sqlite3OsEnterMutex() hasn't been called yet.
29861   */
29862   if( pFile->locktype>=locktype ){
29863     return SQLITE_OK;
29864   }
29865
29866   /* Make sure the locking sequence is correct
29867   */
29868   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
29869   assert( locktype!=PENDING_LOCK );
29870   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
29871
29872   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
29873   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
29874   ** the PENDING_LOCK byte is temporary.
29875   */
29876   newLocktype = pFile->locktype;
29877   if(   (pFile->locktype==NO_LOCK)
29878      || (   (locktype==EXCLUSIVE_LOCK)
29879          && (pFile->locktype==RESERVED_LOCK))
29880   ){
29881     int cnt = 3;
29882     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
29883       /* Try 3 times to get the pending lock.  The pending lock might be
29884       ** held by another reader process who will release it momentarily.
29885       */
29886       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
29887       Sleep(1);
29888     }
29889     gotPendingLock = res;
29890     if( !res ){
29891       error = GetLastError();
29892     }
29893   }
29894
29895   /* Acquire a shared lock
29896   */
29897   if( locktype==SHARED_LOCK && res ){
29898     assert( pFile->locktype==NO_LOCK );
29899     res = getReadLock(pFile);
29900     if( res ){
29901       newLocktype = SHARED_LOCK;
29902     }else{
29903       error = GetLastError();
29904     }
29905   }
29906
29907   /* Acquire a RESERVED lock
29908   */
29909   if( locktype==RESERVED_LOCK && res ){
29910     assert( pFile->locktype==SHARED_LOCK );
29911     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29912     if( res ){
29913       newLocktype = RESERVED_LOCK;
29914     }else{
29915       error = GetLastError();
29916     }
29917   }
29918
29919   /* Acquire a PENDING lock
29920   */
29921   if( locktype==EXCLUSIVE_LOCK && res ){
29922     newLocktype = PENDING_LOCK;
29923     gotPendingLock = 0;
29924   }
29925
29926   /* Acquire an EXCLUSIVE lock
29927   */
29928   if( locktype==EXCLUSIVE_LOCK && res ){
29929     assert( pFile->locktype>=SHARED_LOCK );
29930     res = unlockReadLock(pFile);
29931     OSTRACE(("unreadlock = %d\n", res));
29932     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29933     if( res ){
29934       newLocktype = EXCLUSIVE_LOCK;
29935     }else{
29936       error = GetLastError();
29937       OSTRACE(("error-code = %d\n", error));
29938       getReadLock(pFile);
29939     }
29940   }
29941
29942   /* If we are holding a PENDING lock that ought to be released, then
29943   ** release it now.
29944   */
29945   if( gotPendingLock && locktype==SHARED_LOCK ){
29946     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29947   }
29948
29949   /* Update the state of the lock has held in the file descriptor then
29950   ** return the appropriate result code.
29951   */
29952   if( res ){
29953     rc = SQLITE_OK;
29954   }else{
29955     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
29956            locktype, newLocktype));
29957     pFile->lastErrno = error;
29958     rc = SQLITE_BUSY;
29959   }
29960   pFile->locktype = (u8)newLocktype;
29961   return rc;
29962 }
29963
29964 /*
29965 ** This routine checks if there is a RESERVED lock held on the specified
29966 ** file by this or any other process. If such a lock is held, return
29967 ** non-zero, otherwise zero.
29968 */
29969 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
29970   int rc;
29971   winFile *pFile = (winFile*)id;
29972
29973   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29974
29975   assert( id!=0 );
29976   if( pFile->locktype>=RESERVED_LOCK ){
29977     rc = 1;
29978     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
29979   }else{
29980     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29981     if( rc ){
29982       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29983     }
29984     rc = !rc;
29985     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
29986   }
29987   *pResOut = rc;
29988   return SQLITE_OK;
29989 }
29990
29991 /*
29992 ** Lower the locking level on file descriptor id to locktype.  locktype
29993 ** must be either NO_LOCK or SHARED_LOCK.
29994 **
29995 ** If the locking level of the file descriptor is already at or below
29996 ** the requested locking level, this routine is a no-op.
29997 **
29998 ** It is not possible for this routine to fail if the second argument
29999 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30000 ** might return SQLITE_IOERR;
30001 */
30002 static int winUnlock(sqlite3_file *id, int locktype){
30003   int type;
30004   winFile *pFile = (winFile*)id;
30005   int rc = SQLITE_OK;
30006   assert( pFile!=0 );
30007   assert( locktype<=SHARED_LOCK );
30008   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30009           pFile->locktype, pFile->sharedLockByte));
30010   type = pFile->locktype;
30011   if( type>=EXCLUSIVE_LOCK ){
30012     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30013     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30014       /* This should never happen.  We should always be able to
30015       ** reacquire the read lock */
30016       rc = SQLITE_IOERR_UNLOCK;
30017     }
30018   }
30019   if( type>=RESERVED_LOCK ){
30020     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30021   }
30022   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30023     unlockReadLock(pFile);
30024   }
30025   if( type>=PENDING_LOCK ){
30026     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30027   }
30028   pFile->locktype = (u8)locktype;
30029   return rc;
30030 }
30031
30032 /*
30033 ** Control and query of the open file handle.
30034 */
30035 static int winFileControl(sqlite3_file *id, int op, void *pArg){
30036   switch( op ){
30037     case SQLITE_FCNTL_LOCKSTATE: {
30038       *(int*)pArg = ((winFile*)id)->locktype;
30039       return SQLITE_OK;
30040     }
30041     case SQLITE_LAST_ERRNO: {
30042       *(int*)pArg = (int)((winFile*)id)->lastErrno;
30043       return SQLITE_OK;
30044     }
30045     case SQLITE_FCNTL_SIZE_HINT: {
30046       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30047       SimulateIOErrorBenign(1);
30048       winTruncate(id, sz);
30049       SimulateIOErrorBenign(0);
30050       return SQLITE_OK;
30051     }
30052   }
30053   return SQLITE_ERROR;
30054 }
30055
30056 /*
30057 ** Return the sector size in bytes of the underlying block device for
30058 ** the specified file. This is almost always 512 bytes, but may be
30059 ** larger for some devices.
30060 **
30061 ** SQLite code assumes this function cannot fail. It also assumes that
30062 ** if two files are created in the same file-system directory (i.e.
30063 ** a database and its journal file) that the sector size will be the
30064 ** same for both.
30065 */
30066 static int winSectorSize(sqlite3_file *id){
30067   assert( id!=0 );
30068   return (int)(((winFile*)id)->sectorSize);
30069 }
30070
30071 /*
30072 ** Return a vector of device characteristics.
30073 */
30074 static int winDeviceCharacteristics(sqlite3_file *id){
30075   UNUSED_PARAMETER(id);
30076   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30077 }
30078
30079 #ifndef SQLITE_OMIT_WAL
30080
30081 /*
30082 ** Helper functions to obtain and relinquish the global mutex. The
30083 ** global mutex is used to protect the winLockInfo objects used by 
30084 ** this file, all of which may be shared by multiple threads.
30085 **
30086 ** Function winShmMutexHeld() is used to assert() that the global mutex 
30087 ** is held when required. This function is only used as part of assert() 
30088 ** statements. e.g.
30089 **
30090 **   winShmEnterMutex()
30091 **     assert( winShmMutexHeld() );
30092 **   winShmLeaveMutex()
30093 */
30094 static void winShmEnterMutex(void){
30095   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30096 }
30097 static void winShmLeaveMutex(void){
30098   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30099 }
30100 #ifdef SQLITE_DEBUG
30101 static int winShmMutexHeld(void) {
30102   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30103 }
30104 #endif
30105
30106 /*
30107 ** Object used to represent a single file opened and mmapped to provide
30108 ** shared memory.  When multiple threads all reference the same
30109 ** log-summary, each thread has its own winFile object, but they all
30110 ** point to a single instance of this object.  In other words, each
30111 ** log-summary is opened only once per process.
30112 **
30113 ** winShmMutexHeld() must be true when creating or destroying
30114 ** this object or while reading or writing the following fields:
30115 **
30116 **      nRef
30117 **      pNext 
30118 **
30119 ** The following fields are read-only after the object is created:
30120 ** 
30121 **      fid
30122 **      zFilename
30123 **
30124 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30125 ** winShmMutexHeld() is true when reading or writing any other field
30126 ** in this structure.
30127 **
30128 */
30129 struct winShmNode {
30130   sqlite3_mutex *mutex;      /* Mutex to access this object */
30131   char *zFilename;           /* Name of the file */
30132   winFile hFile;             /* File handle from winOpen */
30133
30134   int szRegion;              /* Size of shared-memory regions */
30135   int nRegion;               /* Size of array apRegion */
30136   struct ShmRegion {
30137     HANDLE hMap;             /* File handle from CreateFileMapping */
30138     void *pMap;
30139   } *aRegion;
30140   DWORD lastErrno;           /* The Windows errno from the last I/O error */
30141
30142   int nRef;                  /* Number of winShm objects pointing to this */
30143   winShm *pFirst;            /* All winShm objects pointing to this */
30144   winShmNode *pNext;         /* Next in list of all winShmNode objects */
30145 #ifdef SQLITE_DEBUG
30146   u8 nextShmId;              /* Next available winShm.id value */
30147 #endif
30148 };
30149
30150 /*
30151 ** A global array of all winShmNode objects.
30152 **
30153 ** The winShmMutexHeld() must be true while reading or writing this list.
30154 */
30155 static winShmNode *winShmNodeList = 0;
30156
30157 /*
30158 ** Structure used internally by this VFS to record the state of an
30159 ** open shared memory connection.
30160 **
30161 ** The following fields are initialized when this object is created and
30162 ** are read-only thereafter:
30163 **
30164 **    winShm.pShmNode
30165 **    winShm.id
30166 **
30167 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30168 ** while accessing any read/write fields.
30169 */
30170 struct winShm {
30171   winShmNode *pShmNode;      /* The underlying winShmNode object */
30172   winShm *pNext;             /* Next winShm with the same winShmNode */
30173   u8 hasMutex;               /* True if holding the winShmNode mutex */
30174   u16 sharedMask;            /* Mask of shared locks held */
30175   u16 exclMask;              /* Mask of exclusive locks held */
30176 #ifdef SQLITE_DEBUG
30177   u8 id;                     /* Id of this connection with its winShmNode */
30178 #endif
30179 };
30180
30181 /*
30182 ** Constants used for locking
30183 */
30184 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30185 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30186
30187 /*
30188 ** Apply advisory locks for all n bytes beginning at ofst.
30189 */
30190 #define _SHM_UNLCK  1
30191 #define _SHM_RDLCK  2
30192 #define _SHM_WRLCK  3
30193 static int winShmSystemLock(
30194   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30195   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30196   int ofst,             /* Offset to first byte to be locked/unlocked */
30197   int nByte             /* Number of bytes to lock or unlock */
30198 ){
30199   OVERLAPPED ovlp;
30200   DWORD dwFlags;
30201   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30202
30203   /* Access to the winShmNode object is serialized by the caller */
30204   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30205
30206   /* Initialize the locking parameters */
30207   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30208   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30209
30210   memset(&ovlp, 0, sizeof(OVERLAPPED));
30211   ovlp.Offset = ofst;
30212
30213   /* Release/Acquire the system-level lock */
30214   if( lockType==_SHM_UNLCK ){
30215     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30216   }else{
30217     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30218   }
30219   
30220   if( rc!= 0 ){
30221     rc = SQLITE_OK;
30222   }else{
30223     pFile->lastErrno =  GetLastError();
30224     rc = SQLITE_BUSY;
30225   }
30226
30227   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30228            pFile->hFile.h,
30229            rc==SQLITE_OK ? "ok" : "failed",
30230            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30231            pFile->lastErrno));
30232
30233   return rc;
30234 }
30235
30236 /* Forward references to VFS methods */
30237 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30238 static int winDelete(sqlite3_vfs *,const char*,int);
30239
30240 /*
30241 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30242 **
30243 ** This is not a VFS shared-memory method; it is a utility function called
30244 ** by VFS shared-memory methods.
30245 */
30246 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30247   winShmNode **pp;
30248   winShmNode *p;
30249   assert( winShmMutexHeld() );
30250   pp = &winShmNodeList;
30251   while( (p = *pp)!=0 ){
30252     if( p->nRef==0 ){
30253       int i;
30254       if( p->mutex ) sqlite3_mutex_free(p->mutex);
30255       for(i=0; i<p->nRegion; i++){
30256         UnmapViewOfFile(p->aRegion[i].pMap);
30257         CloseHandle(p->aRegion[i].hMap);
30258       }
30259       if( p->hFile.h != INVALID_HANDLE_VALUE ){
30260         SimulateIOErrorBenign(1);
30261         winClose((sqlite3_file *)&p->hFile);
30262         SimulateIOErrorBenign(0);
30263       }
30264       if( deleteFlag ){
30265         SimulateIOErrorBenign(1);
30266         winDelete(pVfs, p->zFilename, 0);
30267         SimulateIOErrorBenign(0);
30268       }
30269       *pp = p->pNext;
30270       sqlite3_free(p->aRegion);
30271       sqlite3_free(p);
30272     }else{
30273       pp = &p->pNext;
30274     }
30275   }
30276 }
30277
30278 /*
30279 ** Open the shared-memory area associated with database file pDbFd.
30280 **
30281 ** When opening a new shared-memory file, if no other instances of that
30282 ** file are currently open, in this process or in other processes, then
30283 ** the file must be truncated to zero length or have its header cleared.
30284 */
30285 static int winOpenSharedMemory(winFile *pDbFd){
30286   struct winShm *p;                  /* The connection to be opened */
30287   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30288   int rc;                            /* Result code */
30289   struct winShmNode *pNew;           /* Newly allocated winShmNode */
30290   int nName;                         /* Size of zName in bytes */
30291
30292   assert( pDbFd->pShm==0 );    /* Not previously opened */
30293
30294   /* Allocate space for the new sqlite3_shm object.  Also speculatively
30295   ** allocate space for a new winShmNode and filename.
30296   */
30297   p = sqlite3_malloc( sizeof(*p) );
30298   if( p==0 ) return SQLITE_NOMEM;
30299   memset(p, 0, sizeof(*p));
30300   nName = sqlite3Strlen30(pDbFd->zPath);
30301   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30302   if( pNew==0 ){
30303     sqlite3_free(p);
30304     return SQLITE_NOMEM;
30305   }
30306   memset(pNew, 0, sizeof(*pNew));
30307   pNew->zFilename = (char*)&pNew[1];
30308   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30309
30310   /* Look to see if there is an existing winShmNode that can be used.
30311   ** If no matching winShmNode currently exists, create a new one.
30312   */
30313   winShmEnterMutex();
30314   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30315     /* TBD need to come up with better match here.  Perhaps
30316     ** use FILE_ID_BOTH_DIR_INFO Structure.
30317     */
30318     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30319   }
30320   if( pShmNode ){
30321     sqlite3_free(pNew);
30322   }else{
30323     pShmNode = pNew;
30324     pNew = 0;
30325     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30326     pShmNode->pNext = winShmNodeList;
30327     winShmNodeList = pShmNode;
30328
30329     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30330     if( pShmNode->mutex==0 ){
30331       rc = SQLITE_NOMEM;
30332       goto shm_open_err;
30333     }
30334     rc = winOpen(pDbFd->pVfs,
30335                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
30336                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30337                  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30338                  0);
30339     if( SQLITE_OK!=rc ){
30340       rc = SQLITE_CANTOPEN_BKPT;
30341       goto shm_open_err;
30342     }
30343
30344     /* Check to see if another process is holding the dead-man switch.
30345     ** If not, truncate the file to zero length. 
30346     */
30347     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30348       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30349       if( rc!=SQLITE_OK ){
30350         rc = SQLITE_IOERR_SHMOPEN;
30351       }
30352     }
30353     if( rc==SQLITE_OK ){
30354       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30355       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30356     }
30357     if( rc ) goto shm_open_err;
30358   }
30359
30360   /* Make the new connection a child of the winShmNode */
30361   p->pShmNode = pShmNode;
30362 #ifdef SQLITE_DEBUG
30363   p->id = pShmNode->nextShmId++;
30364 #endif
30365   pShmNode->nRef++;
30366   pDbFd->pShm = p;
30367   winShmLeaveMutex();
30368
30369   /* The reference count on pShmNode has already been incremented under
30370   ** the cover of the winShmEnterMutex() mutex and the pointer from the
30371   ** new (struct winShm) object to the pShmNode has been set. All that is
30372   ** left to do is to link the new object into the linked list starting
30373   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30374   ** mutex.
30375   */
30376   sqlite3_mutex_enter(pShmNode->mutex);
30377   p->pNext = pShmNode->pFirst;
30378   pShmNode->pFirst = p;
30379   sqlite3_mutex_leave(pShmNode->mutex);
30380   return SQLITE_OK;
30381
30382   /* Jump here on any error */
30383 shm_open_err:
30384   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30385   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30386   sqlite3_free(p);
30387   sqlite3_free(pNew);
30388   winShmLeaveMutex();
30389   return rc;
30390 }
30391
30392 /*
30393 ** Close a connection to shared-memory.  Delete the underlying 
30394 ** storage if deleteFlag is true.
30395 */
30396 static int winShmUnmap(
30397   sqlite3_file *fd,          /* Database holding shared memory */
30398   int deleteFlag             /* Delete after closing if true */
30399 ){
30400   winFile *pDbFd;       /* Database holding shared-memory */
30401   winShm *p;            /* The connection to be closed */
30402   winShmNode *pShmNode; /* The underlying shared-memory file */
30403   winShm **pp;          /* For looping over sibling connections */
30404
30405   pDbFd = (winFile*)fd;
30406   p = pDbFd->pShm;
30407   if( p==0 ) return SQLITE_OK;
30408   pShmNode = p->pShmNode;
30409
30410   /* Remove connection p from the set of connections associated
30411   ** with pShmNode */
30412   sqlite3_mutex_enter(pShmNode->mutex);
30413   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30414   *pp = p->pNext;
30415
30416   /* Free the connection p */
30417   sqlite3_free(p);
30418   pDbFd->pShm = 0;
30419   sqlite3_mutex_leave(pShmNode->mutex);
30420
30421   /* If pShmNode->nRef has reached 0, then close the underlying
30422   ** shared-memory file, too */
30423   winShmEnterMutex();
30424   assert( pShmNode->nRef>0 );
30425   pShmNode->nRef--;
30426   if( pShmNode->nRef==0 ){
30427     winShmPurge(pDbFd->pVfs, deleteFlag);
30428   }
30429   winShmLeaveMutex();
30430
30431   return SQLITE_OK;
30432 }
30433
30434 /*
30435 ** Change the lock state for a shared-memory segment.
30436 */
30437 static int winShmLock(
30438   sqlite3_file *fd,          /* Database file holding the shared memory */
30439   int ofst,                  /* First lock to acquire or release */
30440   int n,                     /* Number of locks to acquire or release */
30441   int flags                  /* What to do with the lock */
30442 ){
30443   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
30444   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
30445   winShm *pX;                           /* For looping over all siblings */
30446   winShmNode *pShmNode = p->pShmNode;
30447   int rc = SQLITE_OK;                   /* Result code */
30448   u16 mask;                             /* Mask of locks to take or release */
30449
30450   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30451   assert( n>=1 );
30452   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30453        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30454        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30455        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30456   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30457
30458   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
30459   assert( n>1 || mask==(1<<ofst) );
30460   sqlite3_mutex_enter(pShmNode->mutex);
30461   if( flags & SQLITE_SHM_UNLOCK ){
30462     u16 allMask = 0; /* Mask of locks held by siblings */
30463
30464     /* See if any siblings hold this same lock */
30465     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30466       if( pX==p ) continue;
30467       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30468       allMask |= pX->sharedMask;
30469     }
30470
30471     /* Unlock the system-level locks */
30472     if( (mask & allMask)==0 ){
30473       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
30474     }else{
30475       rc = SQLITE_OK;
30476     }
30477
30478     /* Undo the local locks */
30479     if( rc==SQLITE_OK ){
30480       p->exclMask &= ~mask;
30481       p->sharedMask &= ~mask;
30482     } 
30483   }else if( flags & SQLITE_SHM_SHARED ){
30484     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30485
30486     /* Find out which shared locks are already held by sibling connections.
30487     ** If any sibling already holds an exclusive lock, go ahead and return
30488     ** SQLITE_BUSY.
30489     */
30490     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30491       if( (pX->exclMask & mask)!=0 ){
30492         rc = SQLITE_BUSY;
30493         break;
30494       }
30495       allShared |= pX->sharedMask;
30496     }
30497
30498     /* Get shared locks at the system level, if necessary */
30499     if( rc==SQLITE_OK ){
30500       if( (allShared & mask)==0 ){
30501         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
30502       }else{
30503         rc = SQLITE_OK;
30504       }
30505     }
30506
30507     /* Get the local shared locks */
30508     if( rc==SQLITE_OK ){
30509       p->sharedMask |= mask;
30510     }
30511   }else{
30512     /* Make sure no sibling connections hold locks that will block this
30513     ** lock.  If any do, return SQLITE_BUSY right away.
30514     */
30515     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30516       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30517         rc = SQLITE_BUSY;
30518         break;
30519       }
30520     }
30521   
30522     /* Get the exclusive locks at the system level.  Then if successful
30523     ** also mark the local connection as being locked.
30524     */
30525     if( rc==SQLITE_OK ){
30526       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
30527       if( rc==SQLITE_OK ){
30528         assert( (p->sharedMask & mask)==0 );
30529         p->exclMask |= mask;
30530       }
30531     }
30532   }
30533   sqlite3_mutex_leave(pShmNode->mutex);
30534   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
30535            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
30536            rc ? "failed" : "ok"));
30537   return rc;
30538 }
30539
30540 /*
30541 ** Implement a memory barrier or memory fence on shared memory.  
30542 **
30543 ** All loads and stores begun before the barrier must complete before
30544 ** any load or store begun after the barrier.
30545 */
30546 static void winShmBarrier(
30547   sqlite3_file *fd          /* Database holding the shared memory */
30548 ){
30549   UNUSED_PARAMETER(fd);
30550   /* MemoryBarrier(); // does not work -- do not know why not */
30551   winShmEnterMutex();
30552   winShmLeaveMutex();
30553 }
30554
30555 /*
30556 ** This function is called to obtain a pointer to region iRegion of the 
30557 ** shared-memory associated with the database file fd. Shared-memory regions 
30558 ** are numbered starting from zero. Each shared-memory region is szRegion 
30559 ** bytes in size.
30560 **
30561 ** If an error occurs, an error code is returned and *pp is set to NULL.
30562 **
30563 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
30564 ** region has not been allocated (by any client, including one running in a
30565 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
30566 ** isWrite is non-zero and the requested shared-memory region has not yet 
30567 ** been allocated, it is allocated by this function.
30568 **
30569 ** If the shared-memory region has already been allocated or is allocated by
30570 ** this call as described above, then it is mapped into this processes 
30571 ** address space (if it is not already), *pp is set to point to the mapped 
30572 ** memory and SQLITE_OK returned.
30573 */
30574 static int winShmMap(
30575   sqlite3_file *fd,               /* Handle open on database file */
30576   int iRegion,                    /* Region to retrieve */
30577   int szRegion,                   /* Size of regions */
30578   int isWrite,                    /* True to extend file if necessary */
30579   void volatile **pp              /* OUT: Mapped memory */
30580 ){
30581   winFile *pDbFd = (winFile*)fd;
30582   winShm *p = pDbFd->pShm;
30583   winShmNode *pShmNode;
30584   int rc = SQLITE_OK;
30585
30586   if( !p ){
30587     rc = winOpenSharedMemory(pDbFd);
30588     if( rc!=SQLITE_OK ) return rc;
30589     p = pDbFd->pShm;
30590   }
30591   pShmNode = p->pShmNode;
30592
30593   sqlite3_mutex_enter(pShmNode->mutex);
30594   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30595
30596   if( pShmNode->nRegion<=iRegion ){
30597     struct ShmRegion *apNew;           /* New aRegion[] array */
30598     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30599     sqlite3_int64 sz;                  /* Current size of wal-index file */
30600
30601     pShmNode->szRegion = szRegion;
30602
30603     /* The requested region is not mapped into this processes address space.
30604     ** Check to see if it has been allocated (i.e. if the wal-index file is
30605     ** large enough to contain the requested region).
30606     */
30607     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
30608     if( rc!=SQLITE_OK ){
30609       rc = SQLITE_IOERR_SHMSIZE;
30610       goto shmpage_out;
30611     }
30612
30613     if( sz<nByte ){
30614       /* The requested memory region does not exist. If isWrite is set to
30615       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
30616       **
30617       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
30618       ** the requested memory region.
30619       */
30620       if( !isWrite ) goto shmpage_out;
30621       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
30622       if( rc!=SQLITE_OK ){
30623         rc = SQLITE_IOERR_SHMSIZE;
30624         goto shmpage_out;
30625       }
30626     }
30627
30628     /* Map the requested memory region into this processes address space. */
30629     apNew = (struct ShmRegion *)sqlite3_realloc(
30630         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
30631     );
30632     if( !apNew ){
30633       rc = SQLITE_IOERR_NOMEM;
30634       goto shmpage_out;
30635     }
30636     pShmNode->aRegion = apNew;
30637
30638     while( pShmNode->nRegion<=iRegion ){
30639       HANDLE hMap;                /* file-mapping handle */
30640       void *pMap = 0;             /* Mapped memory region */
30641      
30642       hMap = CreateFileMapping(pShmNode->hFile.h, 
30643           NULL, PAGE_READWRITE, 0, nByte, NULL
30644       );
30645       if( hMap ){
30646         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30647             0, 0, nByte
30648         );
30649       }
30650       if( !pMap ){
30651         pShmNode->lastErrno = GetLastError();
30652         rc = SQLITE_IOERR;
30653         if( hMap ) CloseHandle(hMap);
30654         goto shmpage_out;
30655       }
30656
30657       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
30658       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
30659       pShmNode->nRegion++;
30660     }
30661   }
30662
30663 shmpage_out:
30664   if( pShmNode->nRegion>iRegion ){
30665     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30666     *pp = (void *)&p[iRegion*szRegion];
30667   }else{
30668     *pp = 0;
30669   }
30670   sqlite3_mutex_leave(pShmNode->mutex);
30671   return rc;
30672 }
30673
30674 #else
30675 # define winShmMap     0
30676 # define winShmLock    0
30677 # define winShmBarrier 0
30678 # define winShmUnmap   0
30679 #endif /* #ifndef SQLITE_OMIT_WAL */
30680
30681 /*
30682 ** Here ends the implementation of all sqlite3_file methods.
30683 **
30684 ********************** End sqlite3_file Methods *******************************
30685 ******************************************************************************/
30686
30687 /*
30688 ** This vector defines all the methods that can operate on an
30689 ** sqlite3_file for win32.
30690 */
30691 static const sqlite3_io_methods winIoMethod = {
30692   2,                              /* iVersion */
30693   winClose,                       /* xClose */
30694   winRead,                        /* xRead */
30695   winWrite,                       /* xWrite */
30696   winTruncate,                    /* xTruncate */
30697   winSync,                        /* xSync */
30698   winFileSize,                    /* xFileSize */
30699   winLock,                        /* xLock */
30700   winUnlock,                      /* xUnlock */
30701   winCheckReservedLock,           /* xCheckReservedLock */
30702   winFileControl,                 /* xFileControl */
30703   winSectorSize,                  /* xSectorSize */
30704   winDeviceCharacteristics,       /* xDeviceCharacteristics */
30705   winShmMap,                      /* xShmMap */
30706   winShmLock,                     /* xShmLock */
30707   winShmBarrier,                  /* xShmBarrier */
30708   winShmUnmap                     /* xShmUnmap */
30709 };
30710
30711 /****************************************************************************
30712 **************************** sqlite3_vfs methods ****************************
30713 **
30714 ** This division contains the implementation of methods on the
30715 ** sqlite3_vfs object.
30716 */
30717
30718 /*
30719 ** Convert a UTF-8 filename into whatever form the underlying
30720 ** operating system wants filenames in.  Space to hold the result
30721 ** is obtained from malloc and must be freed by the calling
30722 ** function.
30723 */
30724 static void *convertUtf8Filename(const char *zFilename){
30725   void *zConverted = 0;
30726   if( isNT() ){
30727     zConverted = utf8ToUnicode(zFilename);
30728 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30729 */
30730 #if SQLITE_OS_WINCE==0
30731   }else{
30732     zConverted = utf8ToMbcs(zFilename);
30733 #endif
30734   }
30735   /* caller will handle out of memory */
30736   return zConverted;
30737 }
30738
30739 /*
30740 ** Create a temporary file name in zBuf.  zBuf must be big enough to
30741 ** hold at pVfs->mxPathname characters.
30742 */
30743 static int getTempname(int nBuf, char *zBuf){
30744   static char zChars[] =
30745     "abcdefghijklmnopqrstuvwxyz"
30746     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30747     "0123456789";
30748   size_t i, j;
30749   char zTempPath[MAX_PATH+1];
30750
30751   /* It's odd to simulate an io-error here, but really this is just
30752   ** using the io-error infrastructure to test that SQLite handles this
30753   ** function failing. 
30754   */
30755   SimulateIOError( return SQLITE_IOERR );
30756
30757   if( sqlite3_temp_directory ){
30758     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
30759   }else if( isNT() ){
30760     char *zMulti;
30761     WCHAR zWidePath[MAX_PATH];
30762     GetTempPathW(MAX_PATH-30, zWidePath);
30763     zMulti = unicodeToUtf8(zWidePath);
30764     if( zMulti ){
30765       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
30766       free(zMulti);
30767     }else{
30768       return SQLITE_NOMEM;
30769     }
30770 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30771 ** Since the ASCII version of these Windows API do not exist for WINCE,
30772 ** it's important to not reference them for WINCE builds.
30773 */
30774 #if SQLITE_OS_WINCE==0
30775   }else{
30776     char *zUtf8;
30777     char zMbcsPath[MAX_PATH];
30778     GetTempPathA(MAX_PATH-30, zMbcsPath);
30779     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
30780     if( zUtf8 ){
30781       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
30782       free(zUtf8);
30783     }else{
30784       return SQLITE_NOMEM;
30785     }
30786 #endif
30787   }
30788
30789   /* Check that the output buffer is large enough for the temporary file 
30790   ** name. If it is not, return SQLITE_ERROR.
30791   */
30792   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
30793     return SQLITE_ERROR;
30794   }
30795
30796   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
30797   zTempPath[i] = 0;
30798
30799   sqlite3_snprintf(nBuf-17, zBuf,
30800                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
30801   j = sqlite3Strlen30(zBuf);
30802   sqlite3_randomness(15, &zBuf[j]);
30803   for(i=0; i<15; i++, j++){
30804     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30805   }
30806   zBuf[j] = 0;
30807
30808   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
30809   return SQLITE_OK; 
30810 }
30811
30812 /*
30813 ** The return value of getLastErrorMsg
30814 ** is zero if the error message fits in the buffer, or non-zero
30815 ** otherwise (if the message was truncated).
30816 */
30817 static int getLastErrorMsg(int nBuf, char *zBuf){
30818   /* FormatMessage returns 0 on failure.  Otherwise it
30819   ** returns the number of TCHARs written to the output
30820   ** buffer, excluding the terminating null char.
30821   */
30822   DWORD error = GetLastError();
30823   DWORD dwLen = 0;
30824   char *zOut = 0;
30825
30826   if( isNT() ){
30827     WCHAR *zTempWide = NULL;
30828     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30829                            NULL,
30830                            error,
30831                            0,
30832                            (LPWSTR) &zTempWide,
30833                            0,
30834                            0);
30835     if( dwLen > 0 ){
30836       /* allocate a buffer and convert to UTF8 */
30837       zOut = unicodeToUtf8(zTempWide);
30838       /* free the system buffer allocated by FormatMessage */
30839       LocalFree(zTempWide);
30840     }
30841 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30842 ** Since the ASCII version of these Windows API do not exist for WINCE,
30843 ** it's important to not reference them for WINCE builds.
30844 */
30845 #if SQLITE_OS_WINCE==0
30846   }else{
30847     char *zTemp = NULL;
30848     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30849                            NULL,
30850                            error,
30851                            0,
30852                            (LPSTR) &zTemp,
30853                            0,
30854                            0);
30855     if( dwLen > 0 ){
30856       /* allocate a buffer and convert to UTF8 */
30857       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
30858       /* free the system buffer allocated by FormatMessage */
30859       LocalFree(zTemp);
30860     }
30861 #endif
30862   }
30863   if( 0 == dwLen ){
30864     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
30865   }else{
30866     /* copy a maximum of nBuf chars to output buffer */
30867     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
30868     /* free the UTF8 buffer */
30869     free(zOut);
30870   }
30871   return 0;
30872 }
30873
30874 /*
30875 ** Open a file.
30876 */
30877 static int winOpen(
30878   sqlite3_vfs *pVfs,        /* Not used */
30879   const char *zName,        /* Name of the file (UTF-8) */
30880   sqlite3_file *id,         /* Write the SQLite file handle here */
30881   int flags,                /* Open mode flags */
30882   int *pOutFlags            /* Status return flags */
30883 ){
30884   HANDLE h;
30885   DWORD dwDesiredAccess;
30886   DWORD dwShareMode;
30887   DWORD dwCreationDisposition;
30888   DWORD dwFlagsAndAttributes = 0;
30889 #if SQLITE_OS_WINCE
30890   int isTemp = 0;
30891 #endif
30892   winFile *pFile = (winFile*)id;
30893   void *zConverted;                 /* Filename in OS encoding */
30894   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
30895   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
30896
30897   assert( id!=0 );
30898   UNUSED_PARAMETER(pVfs);
30899
30900   pFile->h = INVALID_HANDLE_VALUE;
30901
30902   /* If the second argument to this function is NULL, generate a 
30903   ** temporary file name to use 
30904   */
30905   if( !zUtf8Name ){
30906     int rc = getTempname(MAX_PATH+1, zTmpname);
30907     if( rc!=SQLITE_OK ){
30908       return rc;
30909     }
30910     zUtf8Name = zTmpname;
30911   }
30912
30913   /* Convert the filename to the system encoding. */
30914   zConverted = convertUtf8Filename(zUtf8Name);
30915   if( zConverted==0 ){
30916     return SQLITE_NOMEM;
30917   }
30918
30919   if( flags & SQLITE_OPEN_READWRITE ){
30920     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
30921   }else{
30922     dwDesiredAccess = GENERIC_READ;
30923   }
30924   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
30925   ** created. SQLite doesn't use it to indicate "exclusive access" 
30926   ** as it is usually understood.
30927   */
30928   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
30929   if( flags & SQLITE_OPEN_EXCLUSIVE ){
30930     /* Creates a new file, only if it does not already exist. */
30931     /* If the file exists, it fails. */
30932     dwCreationDisposition = CREATE_NEW;
30933   }else if( flags & SQLITE_OPEN_CREATE ){
30934     /* Open existing file, or create if it doesn't exist */
30935     dwCreationDisposition = OPEN_ALWAYS;
30936   }else{
30937     /* Opens a file, only if it exists. */
30938     dwCreationDisposition = OPEN_EXISTING;
30939   }
30940   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
30941   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30942 #if SQLITE_OS_WINCE
30943     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
30944     isTemp = 1;
30945 #else
30946     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
30947                                | FILE_ATTRIBUTE_HIDDEN
30948                                | FILE_FLAG_DELETE_ON_CLOSE;
30949 #endif
30950   }else{
30951     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
30952   }
30953   /* Reports from the internet are that performance is always
30954   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
30955 #if SQLITE_OS_WINCE
30956   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
30957 #endif
30958   if( isNT() ){
30959     h = CreateFileW((WCHAR*)zConverted,
30960        dwDesiredAccess,
30961        dwShareMode,
30962        NULL,
30963        dwCreationDisposition,
30964        dwFlagsAndAttributes,
30965        NULL
30966     );
30967 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30968 ** Since the ASCII version of these Windows API do not exist for WINCE,
30969 ** it's important to not reference them for WINCE builds.
30970 */
30971 #if SQLITE_OS_WINCE==0
30972   }else{
30973     h = CreateFileA((char*)zConverted,
30974        dwDesiredAccess,
30975        dwShareMode,
30976        NULL,
30977        dwCreationDisposition,
30978        dwFlagsAndAttributes,
30979        NULL
30980     );
30981 #endif
30982   }
30983   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
30984            h, zName, dwDesiredAccess, 
30985            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
30986   if( h==INVALID_HANDLE_VALUE ){
30987     pFile->lastErrno = GetLastError();
30988     free(zConverted);
30989     if( flags & SQLITE_OPEN_READWRITE ){
30990       return winOpen(pVfs, zName, id, 
30991              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
30992     }else{
30993       return SQLITE_CANTOPEN_BKPT;
30994     }
30995   }
30996   if( pOutFlags ){
30997     if( flags & SQLITE_OPEN_READWRITE ){
30998       *pOutFlags = SQLITE_OPEN_READWRITE;
30999     }else{
31000       *pOutFlags = SQLITE_OPEN_READONLY;
31001     }
31002   }
31003   memset(pFile, 0, sizeof(*pFile));
31004   pFile->pMethod = &winIoMethod;
31005   pFile->h = h;
31006   pFile->lastErrno = NO_ERROR;
31007   pFile->pVfs = pVfs;
31008   pFile->pShm = 0;
31009   pFile->zPath = zName;
31010   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31011 #if SQLITE_OS_WINCE
31012   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31013                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
31014        && !winceCreateLock(zName, pFile)
31015   ){
31016     CloseHandle(h);
31017     free(zConverted);
31018     return SQLITE_CANTOPEN_BKPT;
31019   }
31020   if( isTemp ){
31021     pFile->zDeleteOnClose = zConverted;
31022   }else
31023 #endif
31024   {
31025     free(zConverted);
31026   }
31027   OpenCounter(+1);
31028   return SQLITE_OK;
31029 }
31030
31031 /*
31032 ** Delete the named file.
31033 **
31034 ** Note that windows does not allow a file to be deleted if some other
31035 ** process has it open.  Sometimes a virus scanner or indexing program
31036 ** will open a journal file shortly after it is created in order to do
31037 ** whatever it does.  While this other process is holding the
31038 ** file open, we will be unable to delete it.  To work around this
31039 ** problem, we delay 100 milliseconds and try to delete again.  Up
31040 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31041 ** up and returning an error.
31042 */
31043 #define MX_DELETION_ATTEMPTS 5
31044 static int winDelete(
31045   sqlite3_vfs *pVfs,          /* Not used on win32 */
31046   const char *zFilename,      /* Name of file to delete */
31047   int syncDir                 /* Not used on win32 */
31048 ){
31049   int cnt = 0;
31050   DWORD rc;
31051   DWORD error = 0;
31052   void *zConverted;
31053   UNUSED_PARAMETER(pVfs);
31054   UNUSED_PARAMETER(syncDir);
31055
31056   SimulateIOError(return SQLITE_IOERR_DELETE);
31057   zConverted = convertUtf8Filename(zFilename);
31058   if( zConverted==0 ){
31059     return SQLITE_NOMEM;
31060   }
31061   if( isNT() ){
31062     do{
31063       DeleteFileW(zConverted);
31064     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31065                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31066            && (++cnt < MX_DELETION_ATTEMPTS)
31067            && (Sleep(100), 1) );
31068 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31069 ** Since the ASCII version of these Windows API do not exist for WINCE,
31070 ** it's important to not reference them for WINCE builds.
31071 */
31072 #if SQLITE_OS_WINCE==0
31073   }else{
31074     do{
31075       DeleteFileA(zConverted);
31076     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31077                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31078            && (++cnt < MX_DELETION_ATTEMPTS)
31079            && (Sleep(100), 1) );
31080 #endif
31081   }
31082   free(zConverted);
31083   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31084        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31085          "ok" : "failed" ));
31086  
31087   return (   (rc == INVALID_FILE_ATTRIBUTES) 
31088           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31089 }
31090
31091 /*
31092 ** Check the existance and status of a file.
31093 */
31094 static int winAccess(
31095   sqlite3_vfs *pVfs,         /* Not used on win32 */
31096   const char *zFilename,     /* Name of file to check */
31097   int flags,                 /* Type of test to make on this file */
31098   int *pResOut               /* OUT: Result */
31099 ){
31100   DWORD attr;
31101   int rc = 0;
31102   void *zConverted;
31103   UNUSED_PARAMETER(pVfs);
31104
31105   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31106   zConverted = convertUtf8Filename(zFilename);
31107   if( zConverted==0 ){
31108     return SQLITE_NOMEM;
31109   }
31110   if( isNT() ){
31111     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31112     memset(&sAttrData, 0, sizeof(sAttrData));
31113     if( GetFileAttributesExW((WCHAR*)zConverted,
31114                              GetFileExInfoStandard, 
31115                              &sAttrData) ){
31116       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31117       ** as if it does not exist.
31118       */
31119       if(    flags==SQLITE_ACCESS_EXISTS
31120           && sAttrData.nFileSizeHigh==0 
31121           && sAttrData.nFileSizeLow==0 ){
31122         attr = INVALID_FILE_ATTRIBUTES;
31123       }else{
31124         attr = sAttrData.dwFileAttributes;
31125       }
31126     }else{
31127       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31128         free(zConverted);
31129         return SQLITE_IOERR_ACCESS;
31130       }else{
31131         attr = INVALID_FILE_ATTRIBUTES;
31132       }
31133     }
31134 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31135 ** Since the ASCII version of these Windows API do not exist for WINCE,
31136 ** it's important to not reference them for WINCE builds.
31137 */
31138 #if SQLITE_OS_WINCE==0
31139   }else{
31140     attr = GetFileAttributesA((char*)zConverted);
31141 #endif
31142   }
31143   free(zConverted);
31144   switch( flags ){
31145     case SQLITE_ACCESS_READ:
31146     case SQLITE_ACCESS_EXISTS:
31147       rc = attr!=INVALID_FILE_ATTRIBUTES;
31148       break;
31149     case SQLITE_ACCESS_READWRITE:
31150       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31151       break;
31152     default:
31153       assert(!"Invalid flags argument");
31154   }
31155   *pResOut = rc;
31156   return SQLITE_OK;
31157 }
31158
31159
31160 /*
31161 ** Turn a relative pathname into a full pathname.  Write the full
31162 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
31163 ** bytes in size.
31164 */
31165 static int winFullPathname(
31166   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31167   const char *zRelative,        /* Possibly relative input path */
31168   int nFull,                    /* Size of output buffer in bytes */
31169   char *zFull                   /* Output buffer */
31170 ){
31171   
31172 #if defined(__CYGWIN__)
31173   SimulateIOError( return SQLITE_ERROR );
31174   UNUSED_PARAMETER(nFull);
31175   cygwin_conv_to_full_win32_path(zRelative, zFull);
31176   return SQLITE_OK;
31177 #endif
31178
31179 #if SQLITE_OS_WINCE
31180   SimulateIOError( return SQLITE_ERROR );
31181   UNUSED_PARAMETER(nFull);
31182   /* WinCE has no concept of a relative pathname, or so I am told. */
31183   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31184   return SQLITE_OK;
31185 #endif
31186
31187 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
31188   int nByte;
31189   void *zConverted;
31190   char *zOut;
31191
31192   /* It's odd to simulate an io-error here, but really this is just
31193   ** using the io-error infrastructure to test that SQLite handles this
31194   ** function failing. This function could fail if, for example, the
31195   ** current working directory has been unlinked.
31196   */
31197   SimulateIOError( return SQLITE_ERROR );
31198   UNUSED_PARAMETER(nFull);
31199   zConverted = convertUtf8Filename(zRelative);
31200   if( isNT() ){
31201     WCHAR *zTemp;
31202     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
31203     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31204     if( zTemp==0 ){
31205       free(zConverted);
31206       return SQLITE_NOMEM;
31207     }
31208     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
31209     free(zConverted);
31210     zOut = unicodeToUtf8(zTemp);
31211     free(zTemp);
31212 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31213 ** Since the ASCII version of these Windows API do not exist for WINCE,
31214 ** it's important to not reference them for WINCE builds.
31215 */
31216 #if SQLITE_OS_WINCE==0
31217   }else{
31218     char *zTemp;
31219     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
31220     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31221     if( zTemp==0 ){
31222       free(zConverted);
31223       return SQLITE_NOMEM;
31224     }
31225     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
31226     free(zConverted);
31227     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31228     free(zTemp);
31229 #endif
31230   }
31231   if( zOut ){
31232     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
31233     free(zOut);
31234     return SQLITE_OK;
31235   }else{
31236     return SQLITE_NOMEM;
31237   }
31238 #endif
31239 }
31240
31241 /*
31242 ** Get the sector size of the device used to store
31243 ** file.
31244 */
31245 static int getSectorSize(
31246     sqlite3_vfs *pVfs,
31247     const char *zRelative     /* UTF-8 file name */
31248 ){
31249   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31250   /* GetDiskFreeSpace is not supported under WINCE */
31251 #if SQLITE_OS_WINCE
31252   UNUSED_PARAMETER(pVfs);
31253   UNUSED_PARAMETER(zRelative);
31254 #else
31255   char zFullpath[MAX_PATH+1];
31256   int rc;
31257   DWORD dwRet = 0;
31258   DWORD dwDummy;
31259
31260   /*
31261   ** We need to get the full path name of the file
31262   ** to get the drive letter to look up the sector
31263   ** size.
31264   */
31265   SimulateIOErrorBenign(1);
31266   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31267   SimulateIOErrorBenign(0);
31268   if( rc == SQLITE_OK )
31269   {
31270     void *zConverted = convertUtf8Filename(zFullpath);
31271     if( zConverted ){
31272       if( isNT() ){
31273         /* trim path to just drive reference */
31274         WCHAR *p = zConverted;
31275         for(;*p;p++){
31276           if( *p == '\\' ){
31277             *p = '\0';
31278             break;
31279           }
31280         }
31281         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
31282                                   &dwDummy,
31283                                   &bytesPerSector,
31284                                   &dwDummy,
31285                                   &dwDummy);
31286       }else{
31287         /* trim path to just drive reference */
31288         char *p = (char *)zConverted;
31289         for(;*p;p++){
31290           if( *p == '\\' ){
31291             *p = '\0';
31292             break;
31293           }
31294         }
31295         dwRet = GetDiskFreeSpaceA((char*)zConverted,
31296                                   &dwDummy,
31297                                   &bytesPerSector,
31298                                   &dwDummy,
31299                                   &dwDummy);
31300       }
31301       free(zConverted);
31302     }
31303     if( !dwRet ){
31304       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31305     }
31306   }
31307 #endif
31308   return (int) bytesPerSector; 
31309 }
31310
31311 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31312 /*
31313 ** Interfaces for opening a shared library, finding entry points
31314 ** within the shared library, and closing the shared library.
31315 */
31316 /*
31317 ** Interfaces for opening a shared library, finding entry points
31318 ** within the shared library, and closing the shared library.
31319 */
31320 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
31321   HANDLE h;
31322   void *zConverted = convertUtf8Filename(zFilename);
31323   UNUSED_PARAMETER(pVfs);
31324   if( zConverted==0 ){
31325     return 0;
31326   }
31327   if( isNT() ){
31328     h = LoadLibraryW((WCHAR*)zConverted);
31329 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31330 ** Since the ASCII version of these Windows API do not exist for WINCE,
31331 ** it's important to not reference them for WINCE builds.
31332 */
31333 #if SQLITE_OS_WINCE==0
31334   }else{
31335     h = LoadLibraryA((char*)zConverted);
31336 #endif
31337   }
31338   free(zConverted);
31339   return (void*)h;
31340 }
31341 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
31342   UNUSED_PARAMETER(pVfs);
31343   getLastErrorMsg(nBuf, zBufOut);
31344 }
31345 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
31346   UNUSED_PARAMETER(pVfs);
31347 #if SQLITE_OS_WINCE
31348   /* The GetProcAddressA() routine is only available on wince. */
31349   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
31350 #else
31351   /* All other windows platforms expect GetProcAddress() to take
31352   ** an Ansi string regardless of the _UNICODE setting */
31353   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
31354 #endif
31355 }
31356 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
31357   UNUSED_PARAMETER(pVfs);
31358   FreeLibrary((HANDLE)pHandle);
31359 }
31360 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31361   #define winDlOpen  0
31362   #define winDlError 0
31363   #define winDlSym   0
31364   #define winDlClose 0
31365 #endif
31366
31367
31368 /*
31369 ** Write up to nBuf bytes of randomness into zBuf.
31370 */
31371 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31372   int n = 0;
31373   UNUSED_PARAMETER(pVfs);
31374 #if defined(SQLITE_TEST)
31375   n = nBuf;
31376   memset(zBuf, 0, nBuf);
31377 #else
31378   if( sizeof(SYSTEMTIME)<=nBuf-n ){
31379     SYSTEMTIME x;
31380     GetSystemTime(&x);
31381     memcpy(&zBuf[n], &x, sizeof(x));
31382     n += sizeof(x);
31383   }
31384   if( sizeof(DWORD)<=nBuf-n ){
31385     DWORD pid = GetCurrentProcessId();
31386     memcpy(&zBuf[n], &pid, sizeof(pid));
31387     n += sizeof(pid);
31388   }
31389   if( sizeof(DWORD)<=nBuf-n ){
31390     DWORD cnt = GetTickCount();
31391     memcpy(&zBuf[n], &cnt, sizeof(cnt));
31392     n += sizeof(cnt);
31393   }
31394   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
31395     LARGE_INTEGER i;
31396     QueryPerformanceCounter(&i);
31397     memcpy(&zBuf[n], &i, sizeof(i));
31398     n += sizeof(i);
31399   }
31400 #endif
31401   return n;
31402 }
31403
31404
31405 /*
31406 ** Sleep for a little while.  Return the amount of time slept.
31407 */
31408 static int winSleep(sqlite3_vfs *pVfs, int microsec){
31409   Sleep((microsec+999)/1000);
31410   UNUSED_PARAMETER(pVfs);
31411   return ((microsec+999)/1000)*1000;
31412 }
31413
31414 /*
31415 ** The following variable, if set to a non-zero value, is interpreted as
31416 ** the number of seconds since 1970 and is used to set the result of
31417 ** sqlite3OsCurrentTime() during testing.
31418 */
31419 #ifdef SQLITE_TEST
31420 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31421 #endif
31422
31423 /*
31424 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
31425 ** the current time and date as a Julian Day number times 86_400_000.  In
31426 ** other words, write into *piNow the number of milliseconds since the Julian
31427 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31428 ** proleptic Gregorian calendar.
31429 **
31430 ** On success, return 0.  Return 1 if the time and date cannot be found.
31431 */
31432 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
31433   /* FILETIME structure is a 64-bit value representing the number of 
31434      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
31435   */
31436   FILETIME ft;
31437   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
31438 #ifdef SQLITE_TEST
31439   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31440 #endif
31441   /* 2^32 - to avoid use of LL and warnings in gcc */
31442   static const sqlite3_int64 max32BitValue = 
31443       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
31444
31445 #if SQLITE_OS_WINCE
31446   SYSTEMTIME time;
31447   GetSystemTime(&time);
31448   /* if SystemTimeToFileTime() fails, it returns zero. */
31449   if (!SystemTimeToFileTime(&time,&ft)){
31450     return 1;
31451   }
31452 #else
31453   GetSystemTimeAsFileTime( &ft );
31454 #endif
31455
31456   *piNow = winFiletimeEpoch +
31457             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
31458                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
31459
31460 #ifdef SQLITE_TEST
31461   if( sqlite3_current_time ){
31462     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31463   }
31464 #endif
31465   UNUSED_PARAMETER(pVfs);
31466   return 0;
31467 }
31468
31469 /*
31470 ** Find the current time (in Universal Coordinated Time).  Write the
31471 ** current time and date as a Julian Day number into *prNow and
31472 ** return 0.  Return 1 if the time and date cannot be found.
31473 */
31474 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31475   int rc;
31476   sqlite3_int64 i;
31477   rc = winCurrentTimeInt64(pVfs, &i);
31478   if( !rc ){
31479     *prNow = i/86400000.0;
31480   }
31481   return rc;
31482 }
31483
31484 /*
31485 ** The idea is that this function works like a combination of
31486 ** GetLastError() and FormatMessage() on windows (or errno and
31487 ** strerror_r() on unix). After an error is returned by an OS
31488 ** function, SQLite calls this function with zBuf pointing to
31489 ** a buffer of nBuf bytes. The OS layer should populate the
31490 ** buffer with a nul-terminated UTF-8 encoded error message
31491 ** describing the last IO error to have occurred within the calling
31492 ** thread.
31493 **
31494 ** If the error message is too large for the supplied buffer,
31495 ** it should be truncated. The return value of xGetLastError
31496 ** is zero if the error message fits in the buffer, or non-zero
31497 ** otherwise (if the message was truncated). If non-zero is returned,
31498 ** then it is not necessary to include the nul-terminator character
31499 ** in the output buffer.
31500 **
31501 ** Not supplying an error message will have no adverse effect
31502 ** on SQLite. It is fine to have an implementation that never
31503 ** returns an error message:
31504 **
31505 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31506 **     assert(zBuf[0]=='\0');
31507 **     return 0;
31508 **   }
31509 **
31510 ** However if an error message is supplied, it will be incorporated
31511 ** by sqlite into the error message available to the user using
31512 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
31513 */
31514 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31515   UNUSED_PARAMETER(pVfs);
31516   return getLastErrorMsg(nBuf, zBuf);
31517 }
31518
31519
31520
31521 /*
31522 ** Initialize and deinitialize the operating system interface.
31523 */
31524 SQLITE_API int sqlite3_os_init(void){
31525   static sqlite3_vfs winVfs = {
31526     2,                   /* iVersion */
31527     sizeof(winFile),     /* szOsFile */
31528     MAX_PATH,            /* mxPathname */
31529     0,                   /* pNext */
31530     "win32",             /* zName */
31531     0,                   /* pAppData */
31532     winOpen,             /* xOpen */
31533     winDelete,           /* xDelete */
31534     winAccess,           /* xAccess */
31535     winFullPathname,     /* xFullPathname */
31536     winDlOpen,           /* xDlOpen */
31537     winDlError,          /* xDlError */
31538     winDlSym,            /* xDlSym */
31539     winDlClose,          /* xDlClose */
31540     winRandomness,       /* xRandomness */
31541     winSleep,            /* xSleep */
31542     winCurrentTime,      /* xCurrentTime */
31543     winGetLastError,     /* xGetLastError */
31544     winCurrentTimeInt64, /* xCurrentTimeInt64 */
31545   };
31546
31547   sqlite3_vfs_register(&winVfs, 1);
31548   return SQLITE_OK; 
31549 }
31550 SQLITE_API int sqlite3_os_end(void){ 
31551   return SQLITE_OK;
31552 }
31553
31554 #endif /* SQLITE_OS_WIN */
31555
31556 /************** End of os_win.c **********************************************/
31557 /************** Begin file bitvec.c ******************************************/
31558 /*
31559 ** 2008 February 16
31560 **
31561 ** The author disclaims copyright to this source code.  In place of
31562 ** a legal notice, here is a blessing:
31563 **
31564 **    May you do good and not evil.
31565 **    May you find forgiveness for yourself and forgive others.
31566 **    May you share freely, never taking more than you give.
31567 **
31568 *************************************************************************
31569 ** This file implements an object that represents a fixed-length
31570 ** bitmap.  Bits are numbered starting with 1.
31571 **
31572 ** A bitmap is used to record which pages of a database file have been
31573 ** journalled during a transaction, or which pages have the "dont-write"
31574 ** property.  Usually only a few pages are meet either condition.
31575 ** So the bitmap is usually sparse and has low cardinality.
31576 ** But sometimes (for example when during a DROP of a large table) most
31577 ** or all of the pages in a database can get journalled.  In those cases, 
31578 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
31579 ** to handle both cases well.
31580 **
31581 ** The size of the bitmap is fixed when the object is created.
31582 **
31583 ** All bits are clear when the bitmap is created.  Individual bits
31584 ** may be set or cleared one at a time.
31585 **
31586 ** Test operations are about 100 times more common that set operations.
31587 ** Clear operations are exceedingly rare.  There are usually between
31588 ** 5 and 500 set operations per Bitvec object, though the number of sets can
31589 ** sometimes grow into tens of thousands or larger.  The size of the
31590 ** Bitvec object is the number of pages in the database file at the
31591 ** start of a transaction, and is thus usually less than a few thousand,
31592 ** but can be as large as 2 billion for a really big database.
31593 */
31594
31595 /* Size of the Bitvec structure in bytes. */
31596 #define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
31597
31598 /* Round the union size down to the nearest pointer boundary, since that's how 
31599 ** it will be aligned within the Bitvec struct. */
31600 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
31601
31602 /* Type of the array "element" for the bitmap representation. 
31603 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
31604 ** Setting this to the "natural word" size of your CPU may improve
31605 ** performance. */
31606 #define BITVEC_TELEM     u8
31607 /* Size, in bits, of the bitmap element. */
31608 #define BITVEC_SZELEM    8
31609 /* Number of elements in a bitmap array. */
31610 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
31611 /* Number of bits in the bitmap array. */
31612 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
31613
31614 /* Number of u32 values in hash table. */
31615 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
31616 /* Maximum number of entries in hash table before 
31617 ** sub-dividing and re-hashing. */
31618 #define BITVEC_MXHASH    (BITVEC_NINT/2)
31619 /* Hashing function for the aHash representation.
31620 ** Empirical testing showed that the *37 multiplier 
31621 ** (an arbitrary prime)in the hash function provided 
31622 ** no fewer collisions than the no-op *1. */
31623 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
31624
31625 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
31626
31627
31628 /*
31629 ** A bitmap is an instance of the following structure.
31630 **
31631 ** This bitmap records the existance of zero or more bits
31632 ** with values between 1 and iSize, inclusive.
31633 **
31634 ** There are three possible representations of the bitmap.
31635 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
31636 ** bitmap.  The least significant bit is bit 1.
31637 **
31638 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
31639 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
31640 **
31641 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
31642 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
31643 ** handles up to iDivisor separate values of i.  apSub[0] holds
31644 ** values between 1 and iDivisor.  apSub[1] holds values between
31645 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
31646 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
31647 ** to hold deal with values between 1 and iDivisor.
31648 */
31649 struct Bitvec {
31650   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
31651   u32 nSet;       /* Number of bits that are set - only valid for aHash
31652                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
31653                   ** this would be 125. */
31654   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
31655                   /* Should >=0 for apSub element. */
31656                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
31657                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
31658   union {
31659     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
31660     u32 aHash[BITVEC_NINT];      /* Hash table representation */
31661     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
31662   } u;
31663 };
31664
31665 /*
31666 ** Create a new bitmap object able to handle bits between 0 and iSize,
31667 ** inclusive.  Return a pointer to the new object.  Return NULL if 
31668 ** malloc fails.
31669 */
31670 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
31671   Bitvec *p;
31672   assert( sizeof(*p)==BITVEC_SZ );
31673   p = sqlite3MallocZero( sizeof(*p) );
31674   if( p ){
31675     p->iSize = iSize;
31676   }
31677   return p;
31678 }
31679
31680 /*
31681 ** Check to see if the i-th bit is set.  Return true or false.
31682 ** If p is NULL (if the bitmap has not been created) or if
31683 ** i is out of range, then return false.
31684 */
31685 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
31686   if( p==0 ) return 0;
31687   if( i>p->iSize || i==0 ) return 0;
31688   i--;
31689   while( p->iDivisor ){
31690     u32 bin = i/p->iDivisor;
31691     i = i%p->iDivisor;
31692     p = p->u.apSub[bin];
31693     if (!p) {
31694       return 0;
31695     }
31696   }
31697   if( p->iSize<=BITVEC_NBIT ){
31698     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
31699   } else{
31700     u32 h = BITVEC_HASH(i++);
31701     while( p->u.aHash[h] ){
31702       if( p->u.aHash[h]==i ) return 1;
31703       h = (h+1) % BITVEC_NINT;
31704     }
31705     return 0;
31706   }
31707 }
31708
31709 /*
31710 ** Set the i-th bit.  Return 0 on success and an error code if
31711 ** anything goes wrong.
31712 **
31713 ** This routine might cause sub-bitmaps to be allocated.  Failing
31714 ** to get the memory needed to hold the sub-bitmap is the only
31715 ** that can go wrong with an insert, assuming p and i are valid.
31716 **
31717 ** The calling function must ensure that p is a valid Bitvec object
31718 ** and that the value for "i" is within range of the Bitvec object.
31719 ** Otherwise the behavior is undefined.
31720 */
31721 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
31722   u32 h;
31723   if( p==0 ) return SQLITE_OK;
31724   assert( i>0 );
31725   assert( i<=p->iSize );
31726   i--;
31727   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
31728     u32 bin = i/p->iDivisor;
31729     i = i%p->iDivisor;
31730     if( p->u.apSub[bin]==0 ){
31731       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
31732       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
31733     }
31734     p = p->u.apSub[bin];
31735   }
31736   if( p->iSize<=BITVEC_NBIT ){
31737     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
31738     return SQLITE_OK;
31739   }
31740   h = BITVEC_HASH(i++);
31741   /* if there wasn't a hash collision, and this doesn't */
31742   /* completely fill the hash, then just add it without */
31743   /* worring about sub-dividing and re-hashing. */
31744   if( !p->u.aHash[h] ){
31745     if (p->nSet<(BITVEC_NINT-1)) {
31746       goto bitvec_set_end;
31747     } else {
31748       goto bitvec_set_rehash;
31749     }
31750   }
31751   /* there was a collision, check to see if it's already */
31752   /* in hash, if not, try to find a spot for it */
31753   do {
31754     if( p->u.aHash[h]==i ) return SQLITE_OK;
31755     h++;
31756     if( h>=BITVEC_NINT ) h = 0;
31757   } while( p->u.aHash[h] );
31758   /* we didn't find it in the hash.  h points to the first */
31759   /* available free spot. check to see if this is going to */
31760   /* make our hash too "full".  */
31761 bitvec_set_rehash:
31762   if( p->nSet>=BITVEC_MXHASH ){
31763     unsigned int j;
31764     int rc;
31765     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
31766     if( aiValues==0 ){
31767       return SQLITE_NOMEM;
31768     }else{
31769       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31770       memset(p->u.apSub, 0, sizeof(p->u.apSub));
31771       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
31772       rc = sqlite3BitvecSet(p, i);
31773       for(j=0; j<BITVEC_NINT; j++){
31774         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
31775       }
31776       sqlite3StackFree(0, aiValues);
31777       return rc;
31778     }
31779   }
31780 bitvec_set_end:
31781   p->nSet++;
31782   p->u.aHash[h] = i;
31783   return SQLITE_OK;
31784 }
31785
31786 /*
31787 ** Clear the i-th bit.
31788 **
31789 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
31790 ** that BitvecClear can use to rebuilt its hash table.
31791 */
31792 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
31793   if( p==0 ) return;
31794   assert( i>0 );
31795   i--;
31796   while( p->iDivisor ){
31797     u32 bin = i/p->iDivisor;
31798     i = i%p->iDivisor;
31799     p = p->u.apSub[bin];
31800     if (!p) {
31801       return;
31802     }
31803   }
31804   if( p->iSize<=BITVEC_NBIT ){
31805     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
31806   }else{
31807     unsigned int j;
31808     u32 *aiValues = pBuf;
31809     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31810     memset(p->u.aHash, 0, sizeof(p->u.aHash));
31811     p->nSet = 0;
31812     for(j=0; j<BITVEC_NINT; j++){
31813       if( aiValues[j] && aiValues[j]!=(i+1) ){
31814         u32 h = BITVEC_HASH(aiValues[j]-1);
31815         p->nSet++;
31816         while( p->u.aHash[h] ){
31817           h++;
31818           if( h>=BITVEC_NINT ) h = 0;
31819         }
31820         p->u.aHash[h] = aiValues[j];
31821       }
31822     }
31823   }
31824 }
31825
31826 /*
31827 ** Destroy a bitmap object.  Reclaim all memory used.
31828 */
31829 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
31830   if( p==0 ) return;
31831   if( p->iDivisor ){
31832     unsigned int i;
31833     for(i=0; i<BITVEC_NPTR; i++){
31834       sqlite3BitvecDestroy(p->u.apSub[i]);
31835     }
31836   }
31837   sqlite3_free(p);
31838 }
31839
31840 /*
31841 ** Return the value of the iSize parameter specified when Bitvec *p
31842 ** was created.
31843 */
31844 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
31845   return p->iSize;
31846 }
31847
31848 #ifndef SQLITE_OMIT_BUILTIN_TEST
31849 /*
31850 ** Let V[] be an array of unsigned characters sufficient to hold
31851 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
31852 ** Then the following macros can be used to set, clear, or test
31853 ** individual bits within V.
31854 */
31855 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
31856 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
31857 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
31858
31859 /*
31860 ** This routine runs an extensive test of the Bitvec code.
31861 **
31862 ** The input is an array of integers that acts as a program
31863 ** to test the Bitvec.  The integers are opcodes followed
31864 ** by 0, 1, or 3 operands, depending on the opcode.  Another
31865 ** opcode follows immediately after the last operand.
31866 **
31867 ** There are 6 opcodes numbered from 0 through 5.  0 is the
31868 ** "halt" opcode and causes the test to end.
31869 **
31870 **    0          Halt and return the number of errors
31871 **    1 N S X    Set N bits beginning with S and incrementing by X
31872 **    2 N S X    Clear N bits beginning with S and incrementing by X
31873 **    3 N        Set N randomly chosen bits
31874 **    4 N        Clear N randomly chosen bits
31875 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
31876 **
31877 ** The opcodes 1 through 4 perform set and clear operations are performed
31878 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
31879 ** Opcode 5 works on the linear array only, not on the Bitvec.
31880 ** Opcode 5 is used to deliberately induce a fault in order to
31881 ** confirm that error detection works.
31882 **
31883 ** At the conclusion of the test the linear array is compared
31884 ** against the Bitvec object.  If there are any differences,
31885 ** an error is returned.  If they are the same, zero is returned.
31886 **
31887 ** If a memory allocation error occurs, return -1.
31888 */
31889 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
31890   Bitvec *pBitvec = 0;
31891   unsigned char *pV = 0;
31892   int rc = -1;
31893   int i, nx, pc, op;
31894   void *pTmpSpace;
31895
31896   /* Allocate the Bitvec to be tested and a linear array of
31897   ** bits to act as the reference */
31898   pBitvec = sqlite3BitvecCreate( sz );
31899   pV = sqlite3_malloc( (sz+7)/8 + 1 );
31900   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
31901   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
31902   memset(pV, 0, (sz+7)/8 + 1);
31903
31904   /* NULL pBitvec tests */
31905   sqlite3BitvecSet(0, 1);
31906   sqlite3BitvecClear(0, 1, pTmpSpace);
31907
31908   /* Run the program */
31909   pc = 0;
31910   while( (op = aOp[pc])!=0 ){
31911     switch( op ){
31912       case 1:
31913       case 2:
31914       case 5: {
31915         nx = 4;
31916         i = aOp[pc+2] - 1;
31917         aOp[pc+2] += aOp[pc+3];
31918         break;
31919       }
31920       case 3:
31921       case 4: 
31922       default: {
31923         nx = 2;
31924         sqlite3_randomness(sizeof(i), &i);
31925         break;
31926       }
31927     }
31928     if( (--aOp[pc+1]) > 0 ) nx = 0;
31929     pc += nx;
31930     i = (i & 0x7fffffff)%sz;
31931     if( (op & 1)!=0 ){
31932       SETBIT(pV, (i+1));
31933       if( op!=5 ){
31934         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
31935       }
31936     }else{
31937       CLEARBIT(pV, (i+1));
31938       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
31939     }
31940   }
31941
31942   /* Test to make sure the linear array exactly matches the
31943   ** Bitvec object.  Start with the assumption that they do
31944   ** match (rc==0).  Change rc to non-zero if a discrepancy
31945   ** is found.
31946   */
31947   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
31948           + sqlite3BitvecTest(pBitvec, 0)
31949           + (sqlite3BitvecSize(pBitvec) - sz);
31950   for(i=1; i<=sz; i++){
31951     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
31952       rc = i;
31953       break;
31954     }
31955   }
31956
31957   /* Free allocated structure */
31958 bitvec_end:
31959   sqlite3_free(pTmpSpace);
31960   sqlite3_free(pV);
31961   sqlite3BitvecDestroy(pBitvec);
31962   return rc;
31963 }
31964 #endif /* SQLITE_OMIT_BUILTIN_TEST */
31965
31966 /************** End of bitvec.c **********************************************/
31967 /************** Begin file pcache.c ******************************************/
31968 /*
31969 ** 2008 August 05
31970 **
31971 ** The author disclaims copyright to this source code.  In place of
31972 ** a legal notice, here is a blessing:
31973 **
31974 **    May you do good and not evil.
31975 **    May you find forgiveness for yourself and forgive others.
31976 **    May you share freely, never taking more than you give.
31977 **
31978 *************************************************************************
31979 ** This file implements that page cache.
31980 */
31981
31982 /*
31983 ** A complete page cache is an instance of this structure.
31984 */
31985 struct PCache {
31986   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
31987   PgHdr *pSynced;                     /* Last synced page in dirty page list */
31988   int nRef;                           /* Number of referenced pages */
31989   int nMax;                           /* Configured cache size */
31990   int szPage;                         /* Size of every page in this cache */
31991   int szExtra;                        /* Size of extra space for each page */
31992   int bPurgeable;                     /* True if pages are on backing store */
31993   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
31994   void *pStress;                      /* Argument to xStress */
31995   sqlite3_pcache *pCache;             /* Pluggable cache module */
31996   PgHdr *pPage1;                      /* Reference to page 1 */
31997 };
31998
31999 /*
32000 ** Some of the assert() macros in this code are too expensive to run
32001 ** even during normal debugging.  Use them only rarely on long-running
32002 ** tests.  Enable the expensive asserts using the
32003 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32004 */
32005 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32006 # define expensive_assert(X)  assert(X)
32007 #else
32008 # define expensive_assert(X)
32009 #endif
32010
32011 /********************************** Linked List Management ********************/
32012
32013 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32014 /*
32015 ** Check that the pCache->pSynced variable is set correctly. If it
32016 ** is not, either fail an assert or return zero. Otherwise, return
32017 ** non-zero. This is only used in debugging builds, as follows:
32018 **
32019 **   expensive_assert( pcacheCheckSynced(pCache) );
32020 */
32021 static int pcacheCheckSynced(PCache *pCache){
32022   PgHdr *p;
32023   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32024     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32025   }
32026   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32027 }
32028 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32029
32030 /*
32031 ** Remove page pPage from the list of dirty pages.
32032 */
32033 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32034   PCache *p = pPage->pCache;
32035
32036   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32037   assert( pPage->pDirtyPrev || pPage==p->pDirty );
32038
32039   /* Update the PCache1.pSynced variable if necessary. */
32040   if( p->pSynced==pPage ){
32041     PgHdr *pSynced = pPage->pDirtyPrev;
32042     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32043       pSynced = pSynced->pDirtyPrev;
32044     }
32045     p->pSynced = pSynced;
32046   }
32047
32048   if( pPage->pDirtyNext ){
32049     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32050   }else{
32051     assert( pPage==p->pDirtyTail );
32052     p->pDirtyTail = pPage->pDirtyPrev;
32053   }
32054   if( pPage->pDirtyPrev ){
32055     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32056   }else{
32057     assert( pPage==p->pDirty );
32058     p->pDirty = pPage->pDirtyNext;
32059   }
32060   pPage->pDirtyNext = 0;
32061   pPage->pDirtyPrev = 0;
32062
32063   expensive_assert( pcacheCheckSynced(p) );
32064 }
32065
32066 /*
32067 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32068 ** pPage).
32069 */
32070 static void pcacheAddToDirtyList(PgHdr *pPage){
32071   PCache *p = pPage->pCache;
32072
32073   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32074
32075   pPage->pDirtyNext = p->pDirty;
32076   if( pPage->pDirtyNext ){
32077     assert( pPage->pDirtyNext->pDirtyPrev==0 );
32078     pPage->pDirtyNext->pDirtyPrev = pPage;
32079   }
32080   p->pDirty = pPage;
32081   if( !p->pDirtyTail ){
32082     p->pDirtyTail = pPage;
32083   }
32084   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32085     p->pSynced = pPage;
32086   }
32087   expensive_assert( pcacheCheckSynced(p) );
32088 }
32089
32090 /*
32091 ** Wrapper around the pluggable caches xUnpin method. If the cache is
32092 ** being used for an in-memory database, this function is a no-op.
32093 */
32094 static void pcacheUnpin(PgHdr *p){
32095   PCache *pCache = p->pCache;
32096   if( pCache->bPurgeable ){
32097     if( p->pgno==1 ){
32098       pCache->pPage1 = 0;
32099     }
32100     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32101   }
32102 }
32103
32104 /*************************************************** General Interfaces ******
32105 **
32106 ** Initialize and shutdown the page cache subsystem. Neither of these 
32107 ** functions are threadsafe.
32108 */
32109 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32110   if( sqlite3GlobalConfig.pcache.xInit==0 ){
32111     sqlite3PCacheSetDefault();
32112   }
32113   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32114 }
32115 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32116   if( sqlite3GlobalConfig.pcache.xShutdown ){
32117     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32118   }
32119 }
32120
32121 /*
32122 ** Return the size in bytes of a PCache object.
32123 */
32124 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32125
32126 /*
32127 ** Create a new PCache object. Storage space to hold the object
32128 ** has already been allocated and is passed in as the p pointer. 
32129 ** The caller discovers how much space needs to be allocated by 
32130 ** calling sqlite3PcacheSize().
32131 */
32132 SQLITE_PRIVATE void sqlite3PcacheOpen(
32133   int szPage,                  /* Size of every page */
32134   int szExtra,                 /* Extra space associated with each page */
32135   int bPurgeable,              /* True if pages are on backing store */
32136   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32137   void *pStress,               /* Argument to xStress */
32138   PCache *p                    /* Preallocated space for the PCache */
32139 ){
32140   memset(p, 0, sizeof(PCache));
32141   p->szPage = szPage;
32142   p->szExtra = szExtra;
32143   p->bPurgeable = bPurgeable;
32144   p->xStress = xStress;
32145   p->pStress = pStress;
32146   p->nMax = 100;
32147 }
32148
32149 /*
32150 ** Change the page size for PCache object. The caller must ensure that there
32151 ** are no outstanding page references when this function is called.
32152 */
32153 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
32154   assert( pCache->nRef==0 && pCache->pDirty==0 );
32155   if( pCache->pCache ){
32156     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32157     pCache->pCache = 0;
32158     pCache->pPage1 = 0;
32159   }
32160   pCache->szPage = szPage;
32161 }
32162
32163 /*
32164 ** Try to obtain a page from the cache.
32165 */
32166 SQLITE_PRIVATE int sqlite3PcacheFetch(
32167   PCache *pCache,       /* Obtain the page from this cache */
32168   Pgno pgno,            /* Page number to obtain */
32169   int createFlag,       /* If true, create page if it does not exist already */
32170   PgHdr **ppPage        /* Write the page here */
32171 ){
32172   PgHdr *pPage = 0;
32173   int eCreate;
32174
32175   assert( pCache!=0 );
32176   assert( createFlag==1 || createFlag==0 );
32177   assert( pgno>0 );
32178
32179   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
32180   ** allocate it now.
32181   */
32182   if( !pCache->pCache && createFlag ){
32183     sqlite3_pcache *p;
32184     int nByte;
32185     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
32186     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
32187     if( !p ){
32188       return SQLITE_NOMEM;
32189     }
32190     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
32191     pCache->pCache = p;
32192   }
32193
32194   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
32195   if( pCache->pCache ){
32196     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
32197   }
32198
32199   if( !pPage && eCreate==1 ){
32200     PgHdr *pPg;
32201
32202     /* Find a dirty page to write-out and recycle. First try to find a 
32203     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
32204     ** cleared), but if that is not possible settle for any other 
32205     ** unreferenced dirty page.
32206     */
32207     expensive_assert( pcacheCheckSynced(pCache) );
32208     for(pPg=pCache->pSynced; 
32209         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
32210         pPg=pPg->pDirtyPrev
32211     );
32212     pCache->pSynced = pPg;
32213     if( !pPg ){
32214       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
32215     }
32216     if( pPg ){
32217       int rc;
32218       rc = pCache->xStress(pCache->pStress, pPg);
32219       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
32220         return rc;
32221       }
32222     }
32223
32224     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
32225   }
32226
32227   if( pPage ){
32228     if( !pPage->pData ){
32229       memset(pPage, 0, sizeof(PgHdr));
32230       pPage->pData = (void *)&pPage[1];
32231       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32232       memset(pPage->pExtra, 0, pCache->szExtra);
32233       pPage->pCache = pCache;
32234       pPage->pgno = pgno;
32235     }
32236     assert( pPage->pCache==pCache );
32237     assert( pPage->pgno==pgno );
32238     assert( pPage->pData==(void *)&pPage[1] );
32239     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
32240
32241     if( 0==pPage->nRef ){
32242       pCache->nRef++;
32243     }
32244     pPage->nRef++;
32245     if( pgno==1 ){
32246       pCache->pPage1 = pPage;
32247     }
32248   }
32249   *ppPage = pPage;
32250   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
32251 }
32252
32253 /*
32254 ** Decrement the reference count on a page. If the page is clean and the
32255 ** reference count drops to 0, then it is made elible for recycling.
32256 */
32257 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
32258   assert( p->nRef>0 );
32259   p->nRef--;
32260   if( p->nRef==0 ){
32261     PCache *pCache = p->pCache;
32262     pCache->nRef--;
32263     if( (p->flags&PGHDR_DIRTY)==0 ){
32264       pcacheUnpin(p);
32265     }else{
32266       /* Move the page to the head of the dirty list. */
32267       pcacheRemoveFromDirtyList(p);
32268       pcacheAddToDirtyList(p);
32269     }
32270   }
32271 }
32272
32273 /*
32274 ** Increase the reference count of a supplied page by 1.
32275 */
32276 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
32277   assert(p->nRef>0);
32278   p->nRef++;
32279 }
32280
32281 /*
32282 ** Drop a page from the cache. There must be exactly one reference to the
32283 ** page. This function deletes that reference, so after it returns the
32284 ** page pointed to by p is invalid.
32285 */
32286 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
32287   PCache *pCache;
32288   assert( p->nRef==1 );
32289   if( p->flags&PGHDR_DIRTY ){
32290     pcacheRemoveFromDirtyList(p);
32291   }
32292   pCache = p->pCache;
32293   pCache->nRef--;
32294   if( p->pgno==1 ){
32295     pCache->pPage1 = 0;
32296   }
32297   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
32298 }
32299
32300 /*
32301 ** Make sure the page is marked as dirty. If it isn't dirty already,
32302 ** make it so.
32303 */
32304 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
32305   p->flags &= ~PGHDR_DONT_WRITE;
32306   assert( p->nRef>0 );
32307   if( 0==(p->flags & PGHDR_DIRTY) ){
32308     p->flags |= PGHDR_DIRTY;
32309     pcacheAddToDirtyList( p);
32310   }
32311 }
32312
32313 /*
32314 ** Make sure the page is marked as clean. If it isn't clean already,
32315 ** make it so.
32316 */
32317 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
32318   if( (p->flags & PGHDR_DIRTY) ){
32319     pcacheRemoveFromDirtyList(p);
32320     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
32321     if( p->nRef==0 ){
32322       pcacheUnpin(p);
32323     }
32324   }
32325 }
32326
32327 /*
32328 ** Make every page in the cache clean.
32329 */
32330 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
32331   PgHdr *p;
32332   while( (p = pCache->pDirty)!=0 ){
32333     sqlite3PcacheMakeClean(p);
32334   }
32335 }
32336
32337 /*
32338 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
32339 */
32340 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
32341   PgHdr *p;
32342   for(p=pCache->pDirty; p; p=p->pDirtyNext){
32343     p->flags &= ~PGHDR_NEED_SYNC;
32344   }
32345   pCache->pSynced = pCache->pDirtyTail;
32346 }
32347
32348 /*
32349 ** Change the page number of page p to newPgno. 
32350 */
32351 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
32352   PCache *pCache = p->pCache;
32353   assert( p->nRef>0 );
32354   assert( newPgno>0 );
32355   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
32356   p->pgno = newPgno;
32357   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
32358     pcacheRemoveFromDirtyList(p);
32359     pcacheAddToDirtyList(p);
32360   }
32361 }
32362
32363 /*
32364 ** Drop every cache entry whose page number is greater than "pgno". The
32365 ** caller must ensure that there are no outstanding references to any pages
32366 ** other than page 1 with a page number greater than pgno.
32367 **
32368 ** If there is a reference to page 1 and the pgno parameter passed to this
32369 ** function is 0, then the data area associated with page 1 is zeroed, but
32370 ** the page object is not dropped.
32371 */
32372 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
32373   if( pCache->pCache ){
32374     PgHdr *p;
32375     PgHdr *pNext;
32376     for(p=pCache->pDirty; p; p=pNext){
32377       pNext = p->pDirtyNext;
32378       /* This routine never gets call with a positive pgno except right
32379       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
32380       ** it must be that pgno==0.
32381       */
32382       assert( p->pgno>0 );
32383       if( ALWAYS(p->pgno>pgno) ){
32384         assert( p->flags&PGHDR_DIRTY );
32385         sqlite3PcacheMakeClean(p);
32386       }
32387     }
32388     if( pgno==0 && pCache->pPage1 ){
32389       memset(pCache->pPage1->pData, 0, pCache->szPage);
32390       pgno = 1;
32391     }
32392     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
32393   }
32394 }
32395
32396 /*
32397 ** Close a cache.
32398 */
32399 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
32400   if( pCache->pCache ){
32401     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32402   }
32403 }
32404
32405 /* 
32406 ** Discard the contents of the cache.
32407 */
32408 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
32409   sqlite3PcacheTruncate(pCache, 0);
32410 }
32411
32412 /*
32413 ** Merge two lists of pages connected by pDirty and in pgno order.
32414 ** Do not both fixing the pDirtyPrev pointers.
32415 */
32416 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
32417   PgHdr result, *pTail;
32418   pTail = &result;
32419   while( pA && pB ){
32420     if( pA->pgno<pB->pgno ){
32421       pTail->pDirty = pA;
32422       pTail = pA;
32423       pA = pA->pDirty;
32424     }else{
32425       pTail->pDirty = pB;
32426       pTail = pB;
32427       pB = pB->pDirty;
32428     }
32429   }
32430   if( pA ){
32431     pTail->pDirty = pA;
32432   }else if( pB ){
32433     pTail->pDirty = pB;
32434   }else{
32435     pTail->pDirty = 0;
32436   }
32437   return result.pDirty;
32438 }
32439
32440 /*
32441 ** Sort the list of pages in accending order by pgno.  Pages are
32442 ** connected by pDirty pointers.  The pDirtyPrev pointers are
32443 ** corrupted by this sort.
32444 **
32445 ** Since there cannot be more than 2^31 distinct pages in a database,
32446 ** there cannot be more than 31 buckets required by the merge sorter.
32447 ** One extra bucket is added to catch overflow in case something
32448 ** ever changes to make the previous sentence incorrect.
32449 */
32450 #define N_SORT_BUCKET  32
32451 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
32452   PgHdr *a[N_SORT_BUCKET], *p;
32453   int i;
32454   memset(a, 0, sizeof(a));
32455   while( pIn ){
32456     p = pIn;
32457     pIn = p->pDirty;
32458     p->pDirty = 0;
32459     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
32460       if( a[i]==0 ){
32461         a[i] = p;
32462         break;
32463       }else{
32464         p = pcacheMergeDirtyList(a[i], p);
32465         a[i] = 0;
32466       }
32467     }
32468     if( NEVER(i==N_SORT_BUCKET-1) ){
32469       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
32470       ** the input list.  But that is impossible.
32471       */
32472       a[i] = pcacheMergeDirtyList(a[i], p);
32473     }
32474   }
32475   p = a[0];
32476   for(i=1; i<N_SORT_BUCKET; i++){
32477     p = pcacheMergeDirtyList(p, a[i]);
32478   }
32479   return p;
32480 }
32481
32482 /*
32483 ** Return a list of all dirty pages in the cache, sorted by page number.
32484 */
32485 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
32486   PgHdr *p;
32487   for(p=pCache->pDirty; p; p=p->pDirtyNext){
32488     p->pDirty = p->pDirtyNext;
32489   }
32490   return pcacheSortDirtyList(pCache->pDirty);
32491 }
32492
32493 /* 
32494 ** Return the total number of referenced pages held by the cache.
32495 */
32496 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
32497   return pCache->nRef;
32498 }
32499
32500 /*
32501 ** Return the number of references to the page supplied as an argument.
32502 */
32503 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
32504   return p->nRef;
32505 }
32506
32507 /* 
32508 ** Return the total number of pages in the cache.
32509 */
32510 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
32511   int nPage = 0;
32512   if( pCache->pCache ){
32513     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
32514   }
32515   return nPage;
32516 }
32517
32518 #ifdef SQLITE_TEST
32519 /*
32520 ** Get the suggested cache-size value.
32521 */
32522 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
32523   return pCache->nMax;
32524 }
32525 #endif
32526
32527 /*
32528 ** Set the suggested cache-size value.
32529 */
32530 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
32531   pCache->nMax = mxPage;
32532   if( pCache->pCache ){
32533     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
32534   }
32535 }
32536
32537 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
32538 /*
32539 ** For all dirty pages currently in the cache, invoke the specified
32540 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
32541 ** defined.
32542 */
32543 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
32544   PgHdr *pDirty;
32545   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
32546     xIter(pDirty);
32547   }
32548 }
32549 #endif
32550
32551 /************** End of pcache.c **********************************************/
32552 /************** Begin file pcache1.c *****************************************/
32553 /*
32554 ** 2008 November 05
32555 **
32556 ** The author disclaims copyright to this source code.  In place of
32557 ** a legal notice, here is a blessing:
32558 **
32559 **    May you do good and not evil.
32560 **    May you find forgiveness for yourself and forgive others.
32561 **    May you share freely, never taking more than you give.
32562 **
32563 *************************************************************************
32564 **
32565 ** This file implements the default page cache implementation (the
32566 ** sqlite3_pcache interface). It also contains part of the implementation
32567 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
32568 ** If the default page cache implementation is overriden, then neither of
32569 ** these two features are available.
32570 */
32571
32572
32573 typedef struct PCache1 PCache1;
32574 typedef struct PgHdr1 PgHdr1;
32575 typedef struct PgFreeslot PgFreeslot;
32576
32577 /* Pointers to structures of this type are cast and returned as 
32578 ** opaque sqlite3_pcache* handles
32579 */
32580 struct PCache1 {
32581   /* Cache configuration parameters. Page size (szPage) and the purgeable
32582   ** flag (bPurgeable) are set when the cache is created. nMax may be 
32583   ** modified at any time by a call to the pcache1CacheSize() method.
32584   ** The global mutex must be held when accessing nMax.
32585   */
32586   int szPage;                         /* Size of allocated pages in bytes */
32587   int bPurgeable;                     /* True if cache is purgeable */
32588   unsigned int nMin;                  /* Minimum number of pages reserved */
32589   unsigned int nMax;                  /* Configured "cache_size" value */
32590
32591   /* Hash table of all pages. The following variables may only be accessed
32592   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
32593   ** and pcache1LeaveMutex()).
32594   */
32595   unsigned int nRecyclable;           /* Number of pages in the LRU list */
32596   unsigned int nPage;                 /* Total number of pages in apHash */
32597   unsigned int nHash;                 /* Number of slots in apHash[] */
32598   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
32599
32600   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
32601 };
32602
32603 /*
32604 ** Each cache entry is represented by an instance of the following 
32605 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
32606 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
32607 ** macro below).
32608 */
32609 struct PgHdr1 {
32610   unsigned int iKey;             /* Key value (page number) */
32611   PgHdr1 *pNext;                 /* Next in hash table chain */
32612   PCache1 *pCache;               /* Cache that currently owns this page */
32613   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
32614   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
32615 };
32616
32617 /*
32618 ** Free slots in the allocator used to divide up the buffer provided using
32619 ** the SQLITE_CONFIG_PAGECACHE mechanism.
32620 */
32621 struct PgFreeslot {
32622   PgFreeslot *pNext;  /* Next free slot */
32623 };
32624
32625 /*
32626 ** Global data used by this cache.
32627 */
32628 static SQLITE_WSD struct PCacheGlobal {
32629   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
32630
32631   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
32632   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
32633   int nCurrentPage;                   /* Number of purgeable pages allocated */
32634   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
32635
32636   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
32637   int szSlot;                         /* Size of each free slot */
32638   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
32639   PgFreeslot *pFree;                  /* Free page blocks */
32640   int isInit;                         /* True if initialized */
32641 } pcache1_g;
32642
32643 /*
32644 ** All code in this file should access the global structure above via the
32645 ** alias "pcache1". This ensures that the WSD emulation is used when
32646 ** compiling for systems that do not support real WSD.
32647 */
32648 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
32649
32650 /*
32651 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
32652 ** bytes of data are located directly before it in memory (i.e. the total
32653 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
32654 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
32655 ** an argument and returns a pointer to the associated block of szPage
32656 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
32657 ** a pointer to a block of szPage bytes of data and the return value is
32658 ** a pointer to the associated PgHdr1 structure.
32659 **
32660 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
32661 */
32662 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
32663 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
32664
32665 /*
32666 ** Macros to enter and leave the global LRU mutex.
32667 */
32668 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
32669 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
32670
32671 /******************************************************************************/
32672 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
32673
32674 /*
32675 ** This function is called during initialization if a static buffer is 
32676 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
32677 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
32678 ** enough to contain 'n' buffers of 'sz' bytes each.
32679 */
32680 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
32681   if( pcache1.isInit ){
32682     PgFreeslot *p;
32683     sz = ROUNDDOWN8(sz);
32684     pcache1.szSlot = sz;
32685     pcache1.pStart = pBuf;
32686     pcache1.pFree = 0;
32687     while( n-- ){
32688       p = (PgFreeslot*)pBuf;
32689       p->pNext = pcache1.pFree;
32690       pcache1.pFree = p;
32691       pBuf = (void*)&((char*)pBuf)[sz];
32692     }
32693     pcache1.pEnd = pBuf;
32694   }
32695 }
32696
32697 /*
32698 ** Malloc function used within this file to allocate space from the buffer
32699 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
32700 ** such buffer exists or there is no space left in it, this function falls 
32701 ** back to sqlite3Malloc().
32702 */
32703 static void *pcache1Alloc(int nByte){
32704   void *p;
32705   assert( sqlite3_mutex_held(pcache1.mutex) );
32706   if( nByte<=pcache1.szSlot && pcache1.pFree ){
32707     assert( pcache1.isInit );
32708     p = (PgHdr1 *)pcache1.pFree;
32709     pcache1.pFree = pcache1.pFree->pNext;
32710     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
32711     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32712   }else{
32713
32714     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
32715     ** global pcache mutex and unlock the pager-cache object pCache. This is 
32716     ** so that if the attempt to allocate a new buffer causes the the 
32717     ** configured soft-heap-limit to be breached, it will be possible to
32718     ** reclaim memory from this pager-cache.
32719     */
32720     pcache1LeaveMutex();
32721     p = sqlite3Malloc(nByte);
32722     pcache1EnterMutex();
32723     if( p ){
32724       int sz = sqlite3MallocSize(p);
32725       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
32726     }
32727     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
32728   }
32729   return p;
32730 }
32731
32732 /*
32733 ** Free an allocated buffer obtained from pcache1Alloc().
32734 */
32735 static void pcache1Free(void *p){
32736   assert( sqlite3_mutex_held(pcache1.mutex) );
32737   if( p==0 ) return;
32738   if( p>=pcache1.pStart && p<pcache1.pEnd ){
32739     PgFreeslot *pSlot;
32740     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
32741     pSlot = (PgFreeslot*)p;
32742     pSlot->pNext = pcache1.pFree;
32743     pcache1.pFree = pSlot;
32744   }else{
32745     int iSize;
32746     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
32747     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
32748     iSize = sqlite3MallocSize(p);
32749     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
32750     sqlite3_free(p);
32751   }
32752 }
32753
32754 /*
32755 ** Allocate a new page object initially associated with cache pCache.
32756 */
32757 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
32758   int nByte = sizeof(PgHdr1) + pCache->szPage;
32759   void *pPg = pcache1Alloc(nByte);
32760   PgHdr1 *p;
32761   if( pPg ){
32762     p = PAGE_TO_PGHDR1(pCache, pPg);
32763     if( pCache->bPurgeable ){
32764       pcache1.nCurrentPage++;
32765     }
32766   }else{
32767     p = 0;
32768   }
32769   return p;
32770 }
32771
32772 /*
32773 ** Free a page object allocated by pcache1AllocPage().
32774 **
32775 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
32776 ** that the current implementation happens to never call this routine
32777 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
32778 */
32779 static void pcache1FreePage(PgHdr1 *p){
32780   if( ALWAYS(p) ){
32781     if( p->pCache->bPurgeable ){
32782       pcache1.nCurrentPage--;
32783     }
32784     pcache1Free(PGHDR1_TO_PAGE(p));
32785   }
32786 }
32787
32788 /*
32789 ** Malloc function used by SQLite to obtain space from the buffer configured
32790 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
32791 ** exists, this function falls back to sqlite3Malloc().
32792 */
32793 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
32794   void *p;
32795   pcache1EnterMutex();
32796   p = pcache1Alloc(sz);
32797   pcache1LeaveMutex();
32798   return p;
32799 }
32800
32801 /*
32802 ** Free an allocated buffer obtained from sqlite3PageMalloc().
32803 */
32804 SQLITE_PRIVATE void sqlite3PageFree(void *p){
32805   pcache1EnterMutex();
32806   pcache1Free(p);
32807   pcache1LeaveMutex();
32808 }
32809
32810 /******************************************************************************/
32811 /******** General Implementation Functions ************************************/
32812
32813 /*
32814 ** This function is used to resize the hash table used by the cache passed
32815 ** as the first argument.
32816 **
32817 ** The global mutex must be held when this function is called.
32818 */
32819 static int pcache1ResizeHash(PCache1 *p){
32820   PgHdr1 **apNew;
32821   unsigned int nNew;
32822   unsigned int i;
32823
32824   assert( sqlite3_mutex_held(pcache1.mutex) );
32825
32826   nNew = p->nHash*2;
32827   if( nNew<256 ){
32828     nNew = 256;
32829   }
32830
32831   pcache1LeaveMutex();
32832   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
32833   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
32834   if( p->nHash ){ sqlite3EndBenignMalloc(); }
32835   pcache1EnterMutex();
32836   if( apNew ){
32837     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
32838     for(i=0; i<p->nHash; i++){
32839       PgHdr1 *pPage;
32840       PgHdr1 *pNext = p->apHash[i];
32841       while( (pPage = pNext)!=0 ){
32842         unsigned int h = pPage->iKey % nNew;
32843         pNext = pPage->pNext;
32844         pPage->pNext = apNew[h];
32845         apNew[h] = pPage;
32846       }
32847     }
32848     sqlite3_free(p->apHash);
32849     p->apHash = apNew;
32850     p->nHash = nNew;
32851   }
32852
32853   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
32854 }
32855
32856 /*
32857 ** This function is used internally to remove the page pPage from the 
32858 ** global LRU list, if is part of it. If pPage is not part of the global
32859 ** LRU list, then this function is a no-op.
32860 **
32861 ** The global mutex must be held when this function is called.
32862 */
32863 static void pcache1PinPage(PgHdr1 *pPage){
32864   assert( sqlite3_mutex_held(pcache1.mutex) );
32865   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
32866     if( pPage->pLruPrev ){
32867       pPage->pLruPrev->pLruNext = pPage->pLruNext;
32868     }
32869     if( pPage->pLruNext ){
32870       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
32871     }
32872     if( pcache1.pLruHead==pPage ){
32873       pcache1.pLruHead = pPage->pLruNext;
32874     }
32875     if( pcache1.pLruTail==pPage ){
32876       pcache1.pLruTail = pPage->pLruPrev;
32877     }
32878     pPage->pLruNext = 0;
32879     pPage->pLruPrev = 0;
32880     pPage->pCache->nRecyclable--;
32881   }
32882 }
32883
32884
32885 /*
32886 ** Remove the page supplied as an argument from the hash table 
32887 ** (PCache1.apHash structure) that it is currently stored in.
32888 **
32889 ** The global mutex must be held when this function is called.
32890 */
32891 static void pcache1RemoveFromHash(PgHdr1 *pPage){
32892   unsigned int h;
32893   PCache1 *pCache = pPage->pCache;
32894   PgHdr1 **pp;
32895
32896   h = pPage->iKey % pCache->nHash;
32897   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
32898   *pp = (*pp)->pNext;
32899
32900   pCache->nPage--;
32901 }
32902
32903 /*
32904 ** If there are currently more than pcache.nMaxPage pages allocated, try
32905 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
32906 */
32907 static void pcache1EnforceMaxPage(void){
32908   assert( sqlite3_mutex_held(pcache1.mutex) );
32909   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
32910     PgHdr1 *p = pcache1.pLruTail;
32911     pcache1PinPage(p);
32912     pcache1RemoveFromHash(p);
32913     pcache1FreePage(p);
32914   }
32915 }
32916
32917 /*
32918 ** Discard all pages from cache pCache with a page number (key value) 
32919 ** greater than or equal to iLimit. Any pinned pages that meet this 
32920 ** criteria are unpinned before they are discarded.
32921 **
32922 ** The global mutex must be held when this function is called.
32923 */
32924 static void pcache1TruncateUnsafe(
32925   PCache1 *pCache, 
32926   unsigned int iLimit 
32927 ){
32928   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
32929   unsigned int h;
32930   assert( sqlite3_mutex_held(pcache1.mutex) );
32931   for(h=0; h<pCache->nHash; h++){
32932     PgHdr1 **pp = &pCache->apHash[h]; 
32933     PgHdr1 *pPage;
32934     while( (pPage = *pp)!=0 ){
32935       if( pPage->iKey>=iLimit ){
32936         pCache->nPage--;
32937         *pp = pPage->pNext;
32938         pcache1PinPage(pPage);
32939         pcache1FreePage(pPage);
32940       }else{
32941         pp = &pPage->pNext;
32942         TESTONLY( nPage++; )
32943       }
32944     }
32945   }
32946   assert( pCache->nPage==nPage );
32947 }
32948
32949 /******************************************************************************/
32950 /******** sqlite3_pcache Methods **********************************************/
32951
32952 /*
32953 ** Implementation of the sqlite3_pcache.xInit method.
32954 */
32955 static int pcache1Init(void *NotUsed){
32956   UNUSED_PARAMETER(NotUsed);
32957   assert( pcache1.isInit==0 );
32958   memset(&pcache1, 0, sizeof(pcache1));
32959   if( sqlite3GlobalConfig.bCoreMutex ){
32960     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
32961   }
32962   pcache1.isInit = 1;
32963   return SQLITE_OK;
32964 }
32965
32966 /*
32967 ** Implementation of the sqlite3_pcache.xShutdown method.
32968 ** Note that the static mutex allocated in xInit does 
32969 ** not need to be freed.
32970 */
32971 static void pcache1Shutdown(void *NotUsed){
32972   UNUSED_PARAMETER(NotUsed);
32973   assert( pcache1.isInit!=0 );
32974   memset(&pcache1, 0, sizeof(pcache1));
32975 }
32976
32977 /*
32978 ** Implementation of the sqlite3_pcache.xCreate method.
32979 **
32980 ** Allocate a new cache.
32981 */
32982 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
32983   PCache1 *pCache;
32984
32985   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
32986   if( pCache ){
32987     memset(pCache, 0, sizeof(PCache1));
32988     pCache->szPage = szPage;
32989     pCache->bPurgeable = (bPurgeable ? 1 : 0);
32990     if( bPurgeable ){
32991       pCache->nMin = 10;
32992       pcache1EnterMutex();
32993       pcache1.nMinPage += pCache->nMin;
32994       pcache1LeaveMutex();
32995     }
32996   }
32997   return (sqlite3_pcache *)pCache;
32998 }
32999
33000 /*
33001 ** Implementation of the sqlite3_pcache.xCachesize method. 
33002 **
33003 ** Configure the cache_size limit for a cache.
33004 */
33005 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
33006   PCache1 *pCache = (PCache1 *)p;
33007   if( pCache->bPurgeable ){
33008     pcache1EnterMutex();
33009     pcache1.nMaxPage += (nMax - pCache->nMax);
33010     pCache->nMax = nMax;
33011     pcache1EnforceMaxPage();
33012     pcache1LeaveMutex();
33013   }
33014 }
33015
33016 /*
33017 ** Implementation of the sqlite3_pcache.xPagecount method. 
33018 */
33019 static int pcache1Pagecount(sqlite3_pcache *p){
33020   int n;
33021   pcache1EnterMutex();
33022   n = ((PCache1 *)p)->nPage;
33023   pcache1LeaveMutex();
33024   return n;
33025 }
33026
33027 /*
33028 ** Implementation of the sqlite3_pcache.xFetch method. 
33029 **
33030 ** Fetch a page by key value.
33031 **
33032 ** Whether or not a new page may be allocated by this function depends on
33033 ** the value of the createFlag argument.  0 means do not allocate a new
33034 ** page.  1 means allocate a new page if space is easily available.  2 
33035 ** means to try really hard to allocate a new page.
33036 **
33037 ** For a non-purgeable cache (a cache used as the storage for an in-memory
33038 ** database) there is really no difference between createFlag 1 and 2.  So
33039 ** the calling function (pcache.c) will never have a createFlag of 1 on
33040 ** a non-purgable cache.
33041 **
33042 ** There are three different approaches to obtaining space for a page,
33043 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
33044 **
33045 **   1. Regardless of the value of createFlag, the cache is searched for a 
33046 **      copy of the requested page. If one is found, it is returned.
33047 **
33048 **   2. If createFlag==0 and the page is not already in the cache, NULL is
33049 **      returned.
33050 **
33051 **   3. If createFlag is 1, and the page is not already in the cache,
33052 **      and if either of the following are true, return NULL:
33053 **
33054 **       (a) the number of pages pinned by the cache is greater than
33055 **           PCache1.nMax, or
33056 **       (b) the number of pages pinned by the cache is greater than
33057 **           the sum of nMax for all purgeable caches, less the sum of 
33058 **           nMin for all other purgeable caches. 
33059 **
33060 **   4. If none of the first three conditions apply and the cache is marked
33061 **      as purgeable, and if one of the following is true:
33062 **
33063 **       (a) The number of pages allocated for the cache is already 
33064 **           PCache1.nMax, or
33065 **
33066 **       (b) The number of pages allocated for all purgeable caches is
33067 **           already equal to or greater than the sum of nMax for all
33068 **           purgeable caches,
33069 **
33070 **      then attempt to recycle a page from the LRU list. If it is the right
33071 **      size, return the recycled buffer. Otherwise, free the buffer and
33072 **      proceed to step 5. 
33073 **
33074 **   5. Otherwise, allocate and return a new page buffer.
33075 */
33076 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
33077   unsigned int nPinned;
33078   PCache1 *pCache = (PCache1 *)p;
33079   PgHdr1 *pPage = 0;
33080
33081   assert( pCache->bPurgeable || createFlag!=1 );
33082   pcache1EnterMutex();
33083   if( createFlag==1 ) sqlite3BeginBenignMalloc();
33084
33085   /* Search the hash table for an existing entry. */
33086   if( pCache->nHash>0 ){
33087     unsigned int h = iKey % pCache->nHash;
33088     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
33089   }
33090
33091   if( pPage || createFlag==0 ){
33092     pcache1PinPage(pPage);
33093     goto fetch_out;
33094   }
33095
33096   /* Step 3 of header comment. */
33097   nPinned = pCache->nPage - pCache->nRecyclable;
33098   if( createFlag==1 && (
33099         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33100      || nPinned>=(pCache->nMax * 9 / 10)
33101   )){
33102     goto fetch_out;
33103   }
33104
33105   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
33106     goto fetch_out;
33107   }
33108
33109   /* Step 4. Try to recycle a page buffer if appropriate. */
33110   if( pCache->bPurgeable && pcache1.pLruTail && (
33111      (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
33112   )){
33113     pPage = pcache1.pLruTail;
33114     pcache1RemoveFromHash(pPage);
33115     pcache1PinPage(pPage);
33116     if( pPage->pCache->szPage!=pCache->szPage ){
33117       pcache1FreePage(pPage);
33118       pPage = 0;
33119     }else{
33120       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
33121     }
33122   }
33123
33124   /* Step 5. If a usable page buffer has still not been found, 
33125   ** attempt to allocate a new one. 
33126   */
33127   if( !pPage ){
33128     pPage = pcache1AllocPage(pCache);
33129   }
33130
33131   if( pPage ){
33132     unsigned int h = iKey % pCache->nHash;
33133     pCache->nPage++;
33134     pPage->iKey = iKey;
33135     pPage->pNext = pCache->apHash[h];
33136     pPage->pCache = pCache;
33137     pPage->pLruPrev = 0;
33138     pPage->pLruNext = 0;
33139     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
33140     pCache->apHash[h] = pPage;
33141   }
33142
33143 fetch_out:
33144   if( pPage && iKey>pCache->iMaxKey ){
33145     pCache->iMaxKey = iKey;
33146   }
33147   if( createFlag==1 ) sqlite3EndBenignMalloc();
33148   pcache1LeaveMutex();
33149   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
33150 }
33151
33152
33153 /*
33154 ** Implementation of the sqlite3_pcache.xUnpin method.
33155 **
33156 ** Mark a page as unpinned (eligible for asynchronous recycling).
33157 */
33158 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
33159   PCache1 *pCache = (PCache1 *)p;
33160   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33161  
33162   assert( pPage->pCache==pCache );
33163   pcache1EnterMutex();
33164
33165   /* It is an error to call this function if the page is already 
33166   ** part of the global LRU list.
33167   */
33168   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
33169   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
33170
33171   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
33172     pcache1RemoveFromHash(pPage);
33173     pcache1FreePage(pPage);
33174   }else{
33175     /* Add the page to the global LRU list. Normally, the page is added to
33176     ** the head of the list (last page to be recycled). However, if the 
33177     ** reuseUnlikely flag passed to this function is true, the page is added
33178     ** to the tail of the list (first page to be recycled).
33179     */
33180     if( pcache1.pLruHead ){
33181       pcache1.pLruHead->pLruPrev = pPage;
33182       pPage->pLruNext = pcache1.pLruHead;
33183       pcache1.pLruHead = pPage;
33184     }else{
33185       pcache1.pLruTail = pPage;
33186       pcache1.pLruHead = pPage;
33187     }
33188     pCache->nRecyclable++;
33189   }
33190
33191   pcache1LeaveMutex();
33192 }
33193
33194 /*
33195 ** Implementation of the sqlite3_pcache.xRekey method. 
33196 */
33197 static void pcache1Rekey(
33198   sqlite3_pcache *p,
33199   void *pPg,
33200   unsigned int iOld,
33201   unsigned int iNew
33202 ){
33203   PCache1 *pCache = (PCache1 *)p;
33204   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33205   PgHdr1 **pp;
33206   unsigned int h; 
33207   assert( pPage->iKey==iOld );
33208   assert( pPage->pCache==pCache );
33209
33210   pcache1EnterMutex();
33211
33212   h = iOld%pCache->nHash;
33213   pp = &pCache->apHash[h];
33214   while( (*pp)!=pPage ){
33215     pp = &(*pp)->pNext;
33216   }
33217   *pp = pPage->pNext;
33218
33219   h = iNew%pCache->nHash;
33220   pPage->iKey = iNew;
33221   pPage->pNext = pCache->apHash[h];
33222   pCache->apHash[h] = pPage;
33223   if( iNew>pCache->iMaxKey ){
33224     pCache->iMaxKey = iNew;
33225   }
33226
33227   pcache1LeaveMutex();
33228 }
33229
33230 /*
33231 ** Implementation of the sqlite3_pcache.xTruncate method. 
33232 **
33233 ** Discard all unpinned pages in the cache with a page number equal to
33234 ** or greater than parameter iLimit. Any pinned pages with a page number
33235 ** equal to or greater than iLimit are implicitly unpinned.
33236 */
33237 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
33238   PCache1 *pCache = (PCache1 *)p;
33239   pcache1EnterMutex();
33240   if( iLimit<=pCache->iMaxKey ){
33241     pcache1TruncateUnsafe(pCache, iLimit);
33242     pCache->iMaxKey = iLimit-1;
33243   }
33244   pcache1LeaveMutex();
33245 }
33246
33247 /*
33248 ** Implementation of the sqlite3_pcache.xDestroy method. 
33249 **
33250 ** Destroy a cache allocated using pcache1Create().
33251 */
33252 static void pcache1Destroy(sqlite3_pcache *p){
33253   PCache1 *pCache = (PCache1 *)p;
33254   pcache1EnterMutex();
33255   pcache1TruncateUnsafe(pCache, 0);
33256   pcache1.nMaxPage -= pCache->nMax;
33257   pcache1.nMinPage -= pCache->nMin;
33258   pcache1EnforceMaxPage();
33259   pcache1LeaveMutex();
33260   sqlite3_free(pCache->apHash);
33261   sqlite3_free(pCache);
33262 }
33263
33264 /*
33265 ** This function is called during initialization (sqlite3_initialize()) to
33266 ** install the default pluggable cache module, assuming the user has not
33267 ** already provided an alternative.
33268 */
33269 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
33270   static const sqlite3_pcache_methods defaultMethods = {
33271     0,                       /* pArg */
33272     pcache1Init,             /* xInit */
33273     pcache1Shutdown,         /* xShutdown */
33274     pcache1Create,           /* xCreate */
33275     pcache1Cachesize,        /* xCachesize */
33276     pcache1Pagecount,        /* xPagecount */
33277     pcache1Fetch,            /* xFetch */
33278     pcache1Unpin,            /* xUnpin */
33279     pcache1Rekey,            /* xRekey */
33280     pcache1Truncate,         /* xTruncate */
33281     pcache1Destroy           /* xDestroy */
33282   };
33283   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
33284 }
33285
33286 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33287 /*
33288 ** This function is called to free superfluous dynamically allocated memory
33289 ** held by the pager system. Memory in use by any SQLite pager allocated
33290 ** by the current thread may be sqlite3_free()ed.
33291 **
33292 ** nReq is the number of bytes of memory required. Once this much has
33293 ** been released, the function returns. The return value is the total number 
33294 ** of bytes of memory released.
33295 */
33296 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
33297   int nFree = 0;
33298   if( pcache1.pStart==0 ){
33299     PgHdr1 *p;
33300     pcache1EnterMutex();
33301     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
33302       nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
33303       pcache1PinPage(p);
33304       pcache1RemoveFromHash(p);
33305       pcache1FreePage(p);
33306     }
33307     pcache1LeaveMutex();
33308   }
33309   return nFree;
33310 }
33311 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33312
33313 #ifdef SQLITE_TEST
33314 /*
33315 ** This function is used by test procedures to inspect the internal state
33316 ** of the global cache.
33317 */
33318 SQLITE_PRIVATE void sqlite3PcacheStats(
33319   int *pnCurrent,      /* OUT: Total number of pages cached */
33320   int *pnMax,          /* OUT: Global maximum cache size */
33321   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
33322   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
33323 ){
33324   PgHdr1 *p;
33325   int nRecyclable = 0;
33326   for(p=pcache1.pLruHead; p; p=p->pLruNext){
33327     nRecyclable++;
33328   }
33329   *pnCurrent = pcache1.nCurrentPage;
33330   *pnMax = pcache1.nMaxPage;
33331   *pnMin = pcache1.nMinPage;
33332   *pnRecyclable = nRecyclable;
33333 }
33334 #endif
33335
33336 /************** End of pcache1.c *********************************************/
33337 /************** Begin file rowset.c ******************************************/
33338 /*
33339 ** 2008 December 3
33340 **
33341 ** The author disclaims copyright to this source code.  In place of
33342 ** a legal notice, here is a blessing:
33343 **
33344 **    May you do good and not evil.
33345 **    May you find forgiveness for yourself and forgive others.
33346 **    May you share freely, never taking more than you give.
33347 **
33348 *************************************************************************
33349 **
33350 ** This module implements an object we call a "RowSet".
33351 **
33352 ** The RowSet object is a collection of rowids.  Rowids
33353 ** are inserted into the RowSet in an arbitrary order.  Inserts
33354 ** can be intermixed with tests to see if a given rowid has been
33355 ** previously inserted into the RowSet.
33356 **
33357 ** After all inserts are finished, it is possible to extract the
33358 ** elements of the RowSet in sorted order.  Once this extraction
33359 ** process has started, no new elements may be inserted.
33360 **
33361 ** Hence, the primitive operations for a RowSet are:
33362 **
33363 **    CREATE
33364 **    INSERT
33365 **    TEST
33366 **    SMALLEST
33367 **    DESTROY
33368 **
33369 ** The CREATE and DESTROY primitives are the constructor and destructor,
33370 ** obviously.  The INSERT primitive adds a new element to the RowSet.
33371 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
33372 ** extracts the least value from the RowSet.
33373 **
33374 ** The INSERT primitive might allocate additional memory.  Memory is
33375 ** allocated in chunks so most INSERTs do no allocation.  There is an 
33376 ** upper bound on the size of allocated memory.  No memory is freed
33377 ** until DESTROY.
33378 **
33379 ** The TEST primitive includes a "batch" number.  The TEST primitive
33380 ** will only see elements that were inserted before the last change
33381 ** in the batch number.  In other words, if an INSERT occurs between
33382 ** two TESTs where the TESTs have the same batch nubmer, then the
33383 ** value added by the INSERT will not be visible to the second TEST.
33384 ** The initial batch number is zero, so if the very first TEST contains
33385 ** a non-zero batch number, it will see all prior INSERTs.
33386 **
33387 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
33388 ** that is attempted.
33389 **
33390 ** The cost of an INSERT is roughly constant.  (Sometime new memory
33391 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
33392 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
33393 ** The cost of a TEST using the same batch number is O(logN).  The cost
33394 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
33395 ** primitives are constant time.  The cost of DESTROY is O(N).
33396 **
33397 ** There is an added cost of O(N) when switching between TEST and
33398 ** SMALLEST primitives.
33399 */
33400
33401
33402 /*
33403 ** Target size for allocation chunks.
33404 */
33405 #define ROWSET_ALLOCATION_SIZE 1024
33406
33407 /*
33408 ** The number of rowset entries per allocation chunk.
33409 */
33410 #define ROWSET_ENTRY_PER_CHUNK  \
33411                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
33412
33413 /*
33414 ** Each entry in a RowSet is an instance of the following object.
33415 */
33416 struct RowSetEntry {            
33417   i64 v;                        /* ROWID value for this entry */
33418   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
33419   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
33420 };
33421
33422 /*
33423 ** RowSetEntry objects are allocated in large chunks (instances of the
33424 ** following structure) to reduce memory allocation overhead.  The
33425 ** chunks are kept on a linked list so that they can be deallocated
33426 ** when the RowSet is destroyed.
33427 */
33428 struct RowSetChunk {
33429   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
33430   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
33431 };
33432
33433 /*
33434 ** A RowSet in an instance of the following structure.
33435 **
33436 ** A typedef of this structure if found in sqliteInt.h.
33437 */
33438 struct RowSet {
33439   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
33440   sqlite3 *db;                   /* The database connection */
33441   struct RowSetEntry *pEntry;    /* List of entries using pRight */
33442   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
33443   struct RowSetEntry *pFresh;    /* Source of new entry objects */
33444   struct RowSetEntry *pTree;     /* Binary tree of entries */
33445   u16 nFresh;                    /* Number of objects on pFresh */
33446   u8 isSorted;                   /* True if pEntry is sorted */
33447   u8 iBatch;                     /* Current insert batch */
33448 };
33449
33450 /*
33451 ** Turn bulk memory into a RowSet object.  N bytes of memory
33452 ** are available at pSpace.  The db pointer is used as a memory context
33453 ** for any subsequent allocations that need to occur.
33454 ** Return a pointer to the new RowSet object.
33455 **
33456 ** It must be the case that N is sufficient to make a Rowset.  If not
33457 ** an assertion fault occurs.
33458 ** 
33459 ** If N is larger than the minimum, use the surplus as an initial
33460 ** allocation of entries available to be filled.
33461 */
33462 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
33463   RowSet *p;
33464   assert( N >= ROUND8(sizeof(*p)) );
33465   p = pSpace;
33466   p->pChunk = 0;
33467   p->db = db;
33468   p->pEntry = 0;
33469   p->pLast = 0;
33470   p->pTree = 0;
33471   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
33472   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
33473   p->isSorted = 1;
33474   p->iBatch = 0;
33475   return p;
33476 }
33477
33478 /*
33479 ** Deallocate all chunks from a RowSet.  This frees all memory that
33480 ** the RowSet has allocated over its lifetime.  This routine is
33481 ** the destructor for the RowSet.
33482 */
33483 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
33484   struct RowSetChunk *pChunk, *pNextChunk;
33485   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
33486     pNextChunk = pChunk->pNextChunk;
33487     sqlite3DbFree(p->db, pChunk);
33488   }
33489   p->pChunk = 0;
33490   p->nFresh = 0;
33491   p->pEntry = 0;
33492   p->pLast = 0;
33493   p->pTree = 0;
33494   p->isSorted = 1;
33495 }
33496
33497 /*
33498 ** Insert a new value into a RowSet.
33499 **
33500 ** The mallocFailed flag of the database connection is set if a
33501 ** memory allocation fails.
33502 */
33503 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
33504   struct RowSetEntry *pEntry;  /* The new entry */
33505   struct RowSetEntry *pLast;   /* The last prior entry */
33506   assert( p!=0 );
33507   if( p->nFresh==0 ){
33508     struct RowSetChunk *pNew;
33509     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
33510     if( pNew==0 ){
33511       return;
33512     }
33513     pNew->pNextChunk = p->pChunk;
33514     p->pChunk = pNew;
33515     p->pFresh = pNew->aEntry;
33516     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
33517   }
33518   pEntry = p->pFresh++;
33519   p->nFresh--;
33520   pEntry->v = rowid;
33521   pEntry->pRight = 0;
33522   pLast = p->pLast;
33523   if( pLast ){
33524     if( p->isSorted && rowid<=pLast->v ){
33525       p->isSorted = 0;
33526     }
33527     pLast->pRight = pEntry;
33528   }else{
33529     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
33530     p->pEntry = pEntry;
33531   }
33532   p->pLast = pEntry;
33533 }
33534
33535 /*
33536 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
33537 **
33538 ** The input lists are connected via pRight pointers and are 
33539 ** assumed to each already be in sorted order.
33540 */
33541 static struct RowSetEntry *rowSetMerge(
33542   struct RowSetEntry *pA,    /* First sorted list to be merged */
33543   struct RowSetEntry *pB     /* Second sorted list to be merged */
33544 ){
33545   struct RowSetEntry head;
33546   struct RowSetEntry *pTail;
33547
33548   pTail = &head;
33549   while( pA && pB ){
33550     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33551     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
33552     if( pA->v<pB->v ){
33553       pTail->pRight = pA;
33554       pA = pA->pRight;
33555       pTail = pTail->pRight;
33556     }else if( pB->v<pA->v ){
33557       pTail->pRight = pB;
33558       pB = pB->pRight;
33559       pTail = pTail->pRight;
33560     }else{
33561       pA = pA->pRight;
33562     }
33563   }
33564   if( pA ){
33565     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33566     pTail->pRight = pA;
33567   }else{
33568     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
33569     pTail->pRight = pB;
33570   }
33571   return head.pRight;
33572 }
33573
33574 /*
33575 ** Sort all elements on the pEntry list of the RowSet into ascending order.
33576 */ 
33577 static void rowSetSort(RowSet *p){
33578   unsigned int i;
33579   struct RowSetEntry *pEntry;
33580   struct RowSetEntry *aBucket[40];
33581
33582   assert( p->isSorted==0 );
33583   memset(aBucket, 0, sizeof(aBucket));
33584   while( p->pEntry ){
33585     pEntry = p->pEntry;
33586     p->pEntry = pEntry->pRight;
33587     pEntry->pRight = 0;
33588     for(i=0; aBucket[i]; i++){
33589       pEntry = rowSetMerge(aBucket[i], pEntry);
33590       aBucket[i] = 0;
33591     }
33592     aBucket[i] = pEntry;
33593   }
33594   pEntry = 0;
33595   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
33596     pEntry = rowSetMerge(pEntry, aBucket[i]);
33597   }
33598   p->pEntry = pEntry;
33599   p->pLast = 0;
33600   p->isSorted = 1;
33601 }
33602
33603
33604 /*
33605 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
33606 ** Convert this tree into a linked list connected by the pRight pointers
33607 ** and return pointers to the first and last elements of the new list.
33608 */
33609 static void rowSetTreeToList(
33610   struct RowSetEntry *pIn,         /* Root of the input tree */
33611   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
33612   struct RowSetEntry **ppLast      /* Write tail of the output list here */
33613 ){
33614   assert( pIn!=0 );
33615   if( pIn->pLeft ){
33616     struct RowSetEntry *p;
33617     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
33618     p->pRight = pIn;
33619   }else{
33620     *ppFirst = pIn;
33621   }
33622   if( pIn->pRight ){
33623     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
33624   }else{
33625     *ppLast = pIn;
33626   }
33627   assert( (*ppLast)->pRight==0 );
33628 }
33629
33630
33631 /*
33632 ** Convert a sorted list of elements (connected by pRight) into a binary
33633 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
33634 ** node taken from the head of *ppList.  A depth of 2 means a tree with
33635 ** three nodes.  And so forth.
33636 **
33637 ** Use as many entries from the input list as required and update the
33638 ** *ppList to point to the unused elements of the list.  If the input
33639 ** list contains too few elements, then construct an incomplete tree
33640 ** and leave *ppList set to NULL.
33641 **
33642 ** Return a pointer to the root of the constructed binary tree.
33643 */
33644 static struct RowSetEntry *rowSetNDeepTree(
33645   struct RowSetEntry **ppList,
33646   int iDepth
33647 ){
33648   struct RowSetEntry *p;         /* Root of the new tree */
33649   struct RowSetEntry *pLeft;     /* Left subtree */
33650   if( *ppList==0 ){
33651     return 0;
33652   }
33653   if( iDepth==1 ){
33654     p = *ppList;
33655     *ppList = p->pRight;
33656     p->pLeft = p->pRight = 0;
33657     return p;
33658   }
33659   pLeft = rowSetNDeepTree(ppList, iDepth-1);
33660   p = *ppList;
33661   if( p==0 ){
33662     return pLeft;
33663   }
33664   p->pLeft = pLeft;
33665   *ppList = p->pRight;
33666   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
33667   return p;
33668 }
33669
33670 /*
33671 ** Convert a sorted list of elements into a binary tree. Make the tree
33672 ** as deep as it needs to be in order to contain the entire list.
33673 */
33674 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
33675   int iDepth;           /* Depth of the tree so far */
33676   struct RowSetEntry *p;       /* Current tree root */
33677   struct RowSetEntry *pLeft;   /* Left subtree */
33678
33679   assert( pList!=0 );
33680   p = pList;
33681   pList = p->pRight;
33682   p->pLeft = p->pRight = 0;
33683   for(iDepth=1; pList; iDepth++){
33684     pLeft = p;
33685     p = pList;
33686     pList = p->pRight;
33687     p->pLeft = pLeft;
33688     p->pRight = rowSetNDeepTree(&pList, iDepth);
33689   }
33690   return p;
33691 }
33692
33693 /*
33694 ** Convert the list in p->pEntry into a sorted list if it is not
33695 ** sorted already.  If there is a binary tree on p->pTree, then
33696 ** convert it into a list too and merge it into the p->pEntry list.
33697 */
33698 static void rowSetToList(RowSet *p){
33699   if( !p->isSorted ){
33700     rowSetSort(p);
33701   }
33702   if( p->pTree ){
33703     struct RowSetEntry *pHead, *pTail;
33704     rowSetTreeToList(p->pTree, &pHead, &pTail);
33705     p->pTree = 0;
33706     p->pEntry = rowSetMerge(p->pEntry, pHead);
33707   }
33708 }
33709
33710 /*
33711 ** Extract the smallest element from the RowSet.
33712 ** Write the element into *pRowid.  Return 1 on success.  Return
33713 ** 0 if the RowSet is already empty.
33714 **
33715 ** After this routine has been called, the sqlite3RowSetInsert()
33716 ** routine may not be called again.  
33717 */
33718 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
33719   rowSetToList(p);
33720   if( p->pEntry ){
33721     *pRowid = p->pEntry->v;
33722     p->pEntry = p->pEntry->pRight;
33723     if( p->pEntry==0 ){
33724       sqlite3RowSetClear(p);
33725     }
33726     return 1;
33727   }else{
33728     return 0;
33729   }
33730 }
33731
33732 /*
33733 ** Check to see if element iRowid was inserted into the the rowset as
33734 ** part of any insert batch prior to iBatch.  Return 1 or 0.
33735 */
33736 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
33737   struct RowSetEntry *p;
33738   if( iBatch!=pRowSet->iBatch ){
33739     if( pRowSet->pEntry ){
33740       rowSetToList(pRowSet);
33741       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
33742       pRowSet->pEntry = 0;
33743       pRowSet->pLast = 0;
33744     }
33745     pRowSet->iBatch = iBatch;
33746   }
33747   p = pRowSet->pTree;
33748   while( p ){
33749     if( p->v<iRowid ){
33750       p = p->pRight;
33751     }else if( p->v>iRowid ){
33752       p = p->pLeft;
33753     }else{
33754       return 1;
33755     }
33756   }
33757   return 0;
33758 }
33759
33760 /************** End of rowset.c **********************************************/
33761 /************** Begin file pager.c *******************************************/
33762 /*
33763 ** 2001 September 15
33764 **
33765 ** The author disclaims copyright to this source code.  In place of
33766 ** a legal notice, here is a blessing:
33767 **
33768 **    May you do good and not evil.
33769 **    May you find forgiveness for yourself and forgive others.
33770 **    May you share freely, never taking more than you give.
33771 **
33772 *************************************************************************
33773 ** This is the implementation of the page cache subsystem or "pager".
33774 ** 
33775 ** The pager is used to access a database disk file.  It implements
33776 ** atomic commit and rollback through the use of a journal file that
33777 ** is separate from the database file.  The pager also implements file
33778 ** locking to prevent two processes from writing the same database
33779 ** file simultaneously, or one process from reading the database while
33780 ** another is writing.
33781 */
33782 #ifndef SQLITE_OMIT_DISKIO
33783 /************** Include wal.h in the middle of pager.c ***********************/
33784 /************** Begin file wal.h *********************************************/
33785 /*
33786 ** 2010 February 1
33787 **
33788 ** The author disclaims copyright to this source code.  In place of
33789 ** a legal notice, here is a blessing:
33790 **
33791 **    May you do good and not evil.
33792 **    May you find forgiveness for yourself and forgive others.
33793 **    May you share freely, never taking more than you give.
33794 **
33795 *************************************************************************
33796 ** This header file defines the interface to the write-ahead logging 
33797 ** system. Refer to the comments below and the header comment attached to 
33798 ** the implementation of each function in log.c for further details.
33799 */
33800
33801 #ifndef _WAL_H_
33802 #define _WAL_H_
33803
33804
33805 #ifdef SQLITE_OMIT_WAL
33806 # define sqlite3WalOpen(x,y,z)                 0
33807 # define sqlite3WalClose(w,x,y,z)              0
33808 # define sqlite3WalBeginReadTransaction(y,z)   0
33809 # define sqlite3WalEndReadTransaction(z)
33810 # define sqlite3WalRead(v,w,x,y,z)             0
33811 # define sqlite3WalDbsize(y,z)
33812 # define sqlite3WalBeginWriteTransaction(y)    0
33813 # define sqlite3WalEndWriteTransaction(x)      0
33814 # define sqlite3WalUndo(x,y,z)                 0
33815 # define sqlite3WalSavepoint(y,z)
33816 # define sqlite3WalSavepointUndo(y,z)          0
33817 # define sqlite3WalFrames(u,v,w,x,y,z)         0
33818 # define sqlite3WalCheckpoint(u,v,w,x)         0
33819 # define sqlite3WalCallback(z)                 0
33820 # define sqlite3WalExclusiveMode(y,z)          0
33821 #else
33822
33823 #define WAL_SAVEPOINT_NDATA 4
33824
33825 /* Connection to a write-ahead log (WAL) file. 
33826 ** There is one object of this type for each pager. 
33827 */
33828 typedef struct Wal Wal;
33829
33830 /* Open and close a connection to a write-ahead log. */
33831 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
33832 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
33833
33834 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
33835 ** snapshot is like a read-transaction.  It is the state of the database
33836 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
33837 ** preserves the current state even if the other threads or processes
33838 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
33839 ** transaction and releases the lock.
33840 */
33841 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
33842 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
33843
33844 /* Read a page from the write-ahead log, if it is present. */
33845 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
33846
33847 /* Return the size of the database as it existed at the beginning
33848 ** of the snapshot */
33849 SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno);
33850
33851 /* Obtain or release the WRITER lock. */
33852 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
33853 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
33854
33855 /* Undo any frames written (but not committed) to the log */
33856 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
33857
33858 /* Return an integer that records the current (uncommitted) write
33859 ** position in the WAL */
33860 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
33861
33862 /* Move the write position of the WAL back to iFrame.  Called in
33863 ** response to a ROLLBACK TO command. */
33864 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
33865
33866 /* Write a frame or frames to the log. */
33867 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
33868
33869 /* Copy pages from the log to the database file */ 
33870 SQLITE_PRIVATE int sqlite3WalCheckpoint(
33871   Wal *pWal,                      /* Write-ahead log connection */
33872   int sync_flags,                 /* Flags to sync db file with (or 0) */
33873   int nBuf,                       /* Size of buffer nBuf */
33874   u8 *zBuf                        /* Temporary buffer to use */
33875 );
33876
33877 /* Return the value to pass to a sqlite3_wal_hook callback, the
33878 ** number of frames in the WAL at the point of the last commit since
33879 ** sqlite3WalCallback() was called.  If no commits have occurred since
33880 ** the last call, then return 0.
33881 */
33882 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
33883
33884 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
33885 ** by the pager layer on the database file.
33886 */
33887 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
33888
33889 #endif /* ifndef SQLITE_OMIT_WAL */
33890 #endif /* _WAL_H_ */
33891
33892 /************** End of wal.h *************************************************/
33893 /************** Continuing where we left off in pager.c **********************/
33894
33895 /*
33896 ******************** NOTES ON THE DESIGN OF THE PAGER ************************
33897 **
33898 ** Within this comment block, a page is deemed to have been synced
33899 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
33900 ** Otherwise, the page is not synced until the xSync method of the VFS
33901 ** is called successfully on the file containing the page.
33902 **
33903 ** Definition:  A page of the database file is said to be "overwriteable" if
33904 ** one or more of the following are true about the page:
33905 ** 
33906 **     (a)  The original content of the page as it was at the beginning of
33907 **          the transaction has been written into the rollback journal and
33908 **          synced.
33909 ** 
33910 **     (b)  The page was a freelist leaf page at the start of the transaction.
33911 ** 
33912 **     (c)  The page number is greater than the largest page that existed in
33913 **          the database file at the start of the transaction.
33914 ** 
33915 ** (1) A page of the database file is never overwritten unless one of the
33916 **     following are true:
33917 ** 
33918 **     (a) The page and all other pages on the same sector are overwriteable.
33919 ** 
33920 **     (b) The atomic page write optimization is enabled, and the entire
33921 **         transaction other than the update of the transaction sequence
33922 **         number consists of a single page change.
33923 ** 
33924 ** (2) The content of a page written into the rollback journal exactly matches
33925 **     both the content in the database when the rollback journal was written
33926 **     and the content in the database at the beginning of the current
33927 **     transaction.
33928 ** 
33929 ** (3) Writes to the database file are an integer multiple of the page size
33930 **     in length and are aligned to a page boundary.
33931 ** 
33932 ** (4) Reads from the database file are either aligned on a page boundary and
33933 **     an integer multiple of the page size in length or are taken from the
33934 **     first 100 bytes of the database file.
33935 ** 
33936 ** (5) All writes to the database file are synced prior to the rollback journal
33937 **     being deleted, truncated, or zeroed.
33938 ** 
33939 ** (6) If a master journal file is used, then all writes to the database file
33940 **     are synced prior to the master journal being deleted.
33941 ** 
33942 ** Definition: Two databases (or the same database at two points it time)
33943 ** are said to be "logically equivalent" if they give the same answer to
33944 ** all queries.  Note in particular the the content of freelist leaf
33945 ** pages can be changed arbitarily without effecting the logical equivalence
33946 ** of the database.
33947 ** 
33948 ** (7) At any time, if any subset, including the empty set and the total set,
33949 **     of the unsynced changes to a rollback journal are removed and the 
33950 **     journal is rolled back, the resulting database file will be logical
33951 **     equivalent to the database file at the beginning of the transaction.
33952 ** 
33953 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
33954 **     is called to restore the database file to the same size it was at
33955 **     the beginning of the transaction.  (In some VFSes, the xTruncate
33956 **     method is a no-op, but that does not change the fact the SQLite will
33957 **     invoke it.)
33958 ** 
33959 ** (9) Whenever the database file is modified, at least one bit in the range
33960 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
33961 **     the EXCLUSIVE lock.
33962 **
33963 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
33964 **      than one billion transactions.
33965 **
33966 ** (11) A database file is well-formed at the beginning and at the conclusion
33967 **      of every transaction.
33968 **
33969 ** (12) An EXCLUSIVE lock is held on the database file when writing to
33970 **      the database file.
33971 **
33972 ** (13) A SHARED lock is held on the database file while reading any
33973 **      content out of the database file.
33974 */
33975
33976 /*
33977 ** Macros for troubleshooting.  Normally turned off
33978 */
33979 #if 0
33980 int sqlite3PagerTrace=1;  /* True to enable tracing */
33981 #define sqlite3DebugPrintf printf
33982 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
33983 #else
33984 #define PAGERTRACE(X)
33985 #endif
33986
33987 /*
33988 ** The following two macros are used within the PAGERTRACE() macros above
33989 ** to print out file-descriptors. 
33990 **
33991 ** PAGERID() takes a pointer to a Pager struct as its argument. The
33992 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
33993 ** struct as its argument.
33994 */
33995 #define PAGERID(p) ((int)(p->fd))
33996 #define FILEHANDLEID(fd) ((int)fd)
33997
33998 /*
33999 ** The page cache as a whole is always in one of the following
34000 ** states:
34001 **
34002 **   PAGER_UNLOCK        The page cache is not currently reading or 
34003 **                       writing the database file.  There is no
34004 **                       data held in memory.  This is the initial
34005 **                       state.
34006 **
34007 **   PAGER_SHARED        The page cache is reading the database.
34008 **                       Writing is not permitted.  There can be
34009 **                       multiple readers accessing the same database
34010 **                       file at the same time.
34011 **
34012 **   PAGER_RESERVED      This process has reserved the database for writing
34013 **                       but has not yet made any changes.  Only one process
34014 **                       at a time can reserve the database.  The original
34015 **                       database file has not been modified so other
34016 **                       processes may still be reading the on-disk
34017 **                       database file.
34018 **
34019 **   PAGER_EXCLUSIVE     The page cache is writing the database.
34020 **                       Access is exclusive.  No other processes or
34021 **                       threads can be reading or writing while one
34022 **                       process is writing.
34023 **
34024 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
34025 **                       after all dirty pages have been written to the
34026 **                       database file and the file has been synced to
34027 **                       disk. All that remains to do is to remove or
34028 **                       truncate the journal file and the transaction 
34029 **                       will be committed.
34030 **
34031 ** The page cache comes up in PAGER_UNLOCK.  The first time a
34032 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
34033 ** After all pages have been released using sqlite_page_unref(),
34034 ** the state transitions back to PAGER_UNLOCK.  The first time
34035 ** that sqlite3PagerWrite() is called, the state transitions to
34036 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
34037 ** called on an outstanding page which means that the pager must
34038 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
34039 ** PAGER_RESERVED means that there is an open rollback journal.
34040 ** The transition to PAGER_EXCLUSIVE occurs before any changes
34041 ** are made to the database file, though writes to the rollback
34042 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
34043 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
34044 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
34045 */
34046 #define PAGER_UNLOCK      0
34047 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
34048 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
34049 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
34050 #define PAGER_SYNCED      5
34051
34052 /*
34053 ** A macro used for invoking the codec if there is one
34054 */
34055 #ifdef SQLITE_HAS_CODEC
34056 # define CODEC1(P,D,N,X,E) \
34057     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
34058 # define CODEC2(P,D,N,X,E,O) \
34059     if( P->xCodec==0 ){ O=(char*)D; }else \
34060     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
34061 #else
34062 # define CODEC1(P,D,N,X,E)   /* NO-OP */
34063 # define CODEC2(P,D,N,X,E,O) O=(char*)D
34064 #endif
34065
34066 /*
34067 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
34068 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
34069 ** This could conceivably cause corruption following a power failure on
34070 ** such a system. This is currently an undocumented limit.
34071 */
34072 #define MAX_SECTOR_SIZE 0x10000
34073
34074 /*
34075 ** An instance of the following structure is allocated for each active
34076 ** savepoint and statement transaction in the system. All such structures
34077 ** are stored in the Pager.aSavepoint[] array, which is allocated and
34078 ** resized using sqlite3Realloc().
34079 **
34080 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
34081 ** set to 0. If a journal-header is written into the main journal while
34082 ** the savepoint is active, then iHdrOffset is set to the byte offset 
34083 ** immediately following the last journal record written into the main
34084 ** journal before the journal-header. This is required during savepoint
34085 ** rollback (see pagerPlaybackSavepoint()).
34086 */
34087 typedef struct PagerSavepoint PagerSavepoint;
34088 struct PagerSavepoint {
34089   i64 iOffset;                 /* Starting offset in main journal */
34090   i64 iHdrOffset;              /* See above */
34091   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
34092   Pgno nOrig;                  /* Original number of pages in file */
34093   Pgno iSubRec;                /* Index of first record in sub-journal */
34094 #ifndef SQLITE_OMIT_WAL
34095   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
34096 #endif
34097 };
34098
34099 /*
34100 ** A open page cache is an instance of the following structure.
34101 **
34102 ** errCode
34103 **
34104 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
34105 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
34106 **   and is returned as the result of every major pager API call.  The
34107 **   SQLITE_FULL return code is slightly different. It persists only until the
34108 **   next successful rollback is performed on the pager cache. Also,
34109 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
34110 **   APIs, they may still be used successfully.
34111 **
34112 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
34113 **
34114 **   Managing the size of the database file in pages is a little complicated.
34115 **   The variable Pager.dbSize contains the number of pages that the database
34116 **   image currently contains. As the database image grows or shrinks this
34117 **   variable is updated. The variable Pager.dbFileSize contains the number
34118 **   of pages in the database file. This may be different from Pager.dbSize
34119 **   if some pages have been appended to the database image but not yet written
34120 **   out from the cache to the actual file on disk. Or if the image has been
34121 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
34122 **   contains the number of pages in the database image when the current
34123 **   transaction was opened. The contents of all three of these variables is
34124 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
34125 **
34126 **   TODO: Under what conditions is dbSizeValid set? Cleared?
34127 **
34128 ** changeCountDone
34129 **
34130 **   This boolean variable is used to make sure that the change-counter 
34131 **   (the 4-byte header field at byte offset 24 of the database file) is 
34132 **   not updated more often than necessary. 
34133 **
34134 **   It is set to true when the change-counter field is updated, which 
34135 **   can only happen if an exclusive lock is held on the database file.
34136 **   It is cleared (set to false) whenever an exclusive lock is 
34137 **   relinquished on the database file. Each time a transaction is committed,
34138 **   The changeCountDone flag is inspected. If it is true, the work of
34139 **   updating the change-counter is omitted for the current transaction.
34140 **
34141 **   This mechanism means that when running in exclusive mode, a connection 
34142 **   need only update the change-counter once, for the first transaction
34143 **   committed.
34144 **
34145 ** dbModified
34146 **
34147 **   The dbModified flag is set whenever a database page is dirtied.
34148 **   It is cleared at the end of each transaction.
34149 **
34150 **   It is used when committing or otherwise ending a transaction. If
34151 **   the dbModified flag is clear then less work has to be done.
34152 **
34153 ** journalStarted
34154 **
34155 **   This flag is set whenever the the main journal is opened and
34156 **   initialized
34157 **
34158 **   The point of this flag is that it must be set after the 
34159 **   first journal header in a journal file has been synced to disk.
34160 **   After this has happened, new pages appended to the database 
34161 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
34162 **   to wait for a journal sync before they can be written out to
34163 **   the database file (see function pager_write()).
34164 **   
34165 ** setMaster
34166 **
34167 **   This variable is used to ensure that the master journal file name
34168 **   (if any) is only written into the journal file once.
34169 **
34170 **   When committing a transaction, the master journal file name (if any)
34171 **   may be written into the journal file while the pager is still in
34172 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
34173 **   then attempts to upgrade to an exclusive lock. If this attempt
34174 **   fails, then SQLITE_BUSY may be returned to the user and the user
34175 **   may attempt to commit the transaction again later (calling
34176 **   CommitPhaseOne() again). This flag is used to ensure that the 
34177 **   master journal name is only written to the journal file the first
34178 **   time CommitPhaseOne() is called.
34179 **
34180 ** doNotSpill, doNotSyncSpill
34181 **
34182 **   When enabled, cache spills are prohibited.  The doNotSpill variable
34183 **   inhibits all cache spill and doNotSyncSpill inhibits those spills that
34184 **   would require a journal sync.  The doNotSyncSpill is set and cleared 
34185 **   by sqlite3PagerWrite() in order to prevent a journal sync from happening 
34186 **   in between the journalling of two pages on the same sector.  The
34187 **   doNotSpill value set to prevent pagerStress() from trying to use
34188 **   the journal during a rollback.
34189 **
34190 ** needSync
34191 **
34192 **   TODO: It might be easier to set this variable in writeJournalHdr()
34193 **   and writeMasterJournal() only. Change its meaning to "unsynced data
34194 **   has been written to the journal".
34195 **
34196 ** subjInMemory
34197 **
34198 **   This is a boolean variable. If true, then any required sub-journal
34199 **   is opened as an in-memory journal file. If false, then in-memory
34200 **   sub-journals are only used for in-memory pager files.
34201 */
34202 struct Pager {
34203   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
34204   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
34205   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
34206   u8 useJournal;              /* Use a rollback journal on this file */
34207   u8 noReadlock;              /* Do not bother to obtain readlocks */
34208   u8 noSync;                  /* Do not sync the journal if true */
34209   u8 fullSync;                /* Do extra syncs of the journal for robustness */
34210   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
34211   u8 tempFile;                /* zFilename is a temporary file */
34212   u8 readOnly;                /* True for a read-only database */
34213   u8 memDb;                   /* True to inhibit all file I/O */
34214
34215   /* The following block contains those class members that are dynamically
34216   ** modified during normal operations. The other variables in this structure
34217   ** are either constant throughout the lifetime of the pager, or else
34218   ** used to store configuration parameters that affect the way the pager 
34219   ** operates.
34220   **
34221   ** The 'state' variable is described in more detail along with the
34222   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
34223   ** other variables in this block are described in the comment directly 
34224   ** above this class definition.
34225   */
34226   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
34227   u8 dbModified;              /* True if there are any changes to the Db */
34228   u8 needSync;                /* True if an fsync() is needed on the journal */
34229   u8 journalStarted;          /* True if header of journal is synced */
34230   u8 changeCountDone;         /* Set after incrementing the change-counter */
34231   u8 setMaster;               /* True if a m-j name has been written to jrnl */
34232   u8 doNotSpill;              /* Do not spill the cache when non-zero */
34233   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
34234   u8 dbSizeValid;             /* Set when dbSize is correct */
34235   u8 subjInMemory;            /* True to use in-memory sub-journals */
34236   Pgno dbSize;                /* Number of pages in the database */
34237   Pgno dbOrigSize;            /* dbSize before the current transaction */
34238   Pgno dbFileSize;            /* Number of pages in the database file */
34239   int errCode;                /* One of several kinds of errors */
34240   int nRec;                   /* Pages journalled since last j-header written */
34241   u32 cksumInit;              /* Quasi-random value added to every checksum */
34242   u32 nSubRec;                /* Number of records written to sub-journal */
34243   Bitvec *pInJournal;         /* One bit for each page in the database file */
34244   sqlite3_file *fd;           /* File descriptor for database */
34245   sqlite3_file *jfd;          /* File descriptor for main journal */
34246   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
34247   i64 journalOff;             /* Current write offset in the journal file */
34248   i64 journalHdr;             /* Byte offset to previous journal header */
34249   i64 journalSizeLimit;       /* Size limit for persistent journal files */
34250   PagerSavepoint *aSavepoint; /* Array of active savepoints */
34251   int nSavepoint;             /* Number of elements in aSavepoint[] */
34252   char dbFileVers[16];        /* Changes whenever database file changes */
34253   u32 sectorSize;             /* Assumed sector size during rollback */
34254
34255   u16 nExtra;                 /* Add this many bytes to each in-memory page */
34256   i16 nReserve;               /* Number of unused bytes at end of each page */
34257   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
34258   int pageSize;               /* Number of bytes in a page */
34259   Pgno mxPgno;                /* Maximum allowed size of the database */
34260   char *zFilename;            /* Name of the database file */
34261   char *zJournal;             /* Name of the journal file */
34262   int (*xBusyHandler)(void*); /* Function to call when busy */
34263   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
34264 #ifdef SQLITE_TEST
34265   int nHit, nMiss;            /* Cache hits and missing */
34266   int nRead, nWrite;          /* Database pages read/written */
34267 #endif
34268   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
34269 #ifdef SQLITE_HAS_CODEC
34270   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
34271   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
34272   void (*xCodecFree)(void*);             /* Destructor for the codec */
34273   void *pCodec;               /* First argument to xCodec... methods */
34274 #endif
34275   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
34276   PCache *pPCache;            /* Pointer to page cache object */
34277   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
34278 #ifndef SQLITE_OMIT_WAL
34279   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
34280   char *zWal;                 /* File name for write-ahead log */
34281 #endif
34282 };
34283
34284 /*
34285 ** The following global variables hold counters used for
34286 ** testing purposes only.  These variables do not exist in
34287 ** a non-testing build.  These variables are not thread-safe.
34288 */
34289 #ifdef SQLITE_TEST
34290 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
34291 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
34292 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
34293 # define PAGER_INCR(v)  v++
34294 #else
34295 # define PAGER_INCR(v)
34296 #endif
34297
34298
34299
34300 /*
34301 ** Journal files begin with the following magic string.  The data
34302 ** was obtained from /dev/random.  It is used only as a sanity check.
34303 **
34304 ** Since version 2.8.0, the journal format contains additional sanity
34305 ** checking information.  If the power fails while the journal is being
34306 ** written, semi-random garbage data might appear in the journal
34307 ** file after power is restored.  If an attempt is then made
34308 ** to roll the journal back, the database could be corrupted.  The additional
34309 ** sanity checking data is an attempt to discover the garbage in the
34310 ** journal and ignore it.
34311 **
34312 ** The sanity checking information for the new journal format consists
34313 ** of a 32-bit checksum on each page of data.  The checksum covers both
34314 ** the page number and the pPager->pageSize bytes of data for the page.
34315 ** This cksum is initialized to a 32-bit random value that appears in the
34316 ** journal file right after the header.  The random initializer is important,
34317 ** because garbage data that appears at the end of a journal is likely
34318 ** data that was once in other files that have now been deleted.  If the
34319 ** garbage data came from an obsolete journal file, the checksums might
34320 ** be correct.  But by initializing the checksum to random value which
34321 ** is different for every journal, we minimize that risk.
34322 */
34323 static const unsigned char aJournalMagic[] = {
34324   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
34325 };
34326
34327 /*
34328 ** The size of the of each page record in the journal is given by
34329 ** the following macro.
34330 */
34331 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
34332
34333 /*
34334 ** The journal header size for this pager. This is usually the same 
34335 ** size as a single disk sector. See also setSectorSize().
34336 */
34337 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
34338
34339 /*
34340 ** The macro MEMDB is true if we are dealing with an in-memory database.
34341 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
34342 ** the value of MEMDB will be a constant and the compiler will optimize
34343 ** out code that would never execute.
34344 */
34345 #ifdef SQLITE_OMIT_MEMORYDB
34346 # define MEMDB 0
34347 #else
34348 # define MEMDB pPager->memDb
34349 #endif
34350
34351 /*
34352 ** The maximum legal page number is (2^31 - 1).
34353 */
34354 #define PAGER_MAX_PGNO 2147483647
34355
34356 #ifndef NDEBUG 
34357 /*
34358 ** Usage:
34359 **
34360 **   assert( assert_pager_state(pPager) );
34361 */
34362 static int assert_pager_state(Pager *pPager){
34363
34364   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
34365   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
34366
34367   /* The changeCountDone flag is always set for temp-files */
34368   assert( pPager->tempFile==0 || pPager->changeCountDone );
34369
34370   return 1;
34371 }
34372 #endif
34373
34374 /*
34375 ** Return true if it is necessary to write page *pPg into the sub-journal.
34376 ** A page needs to be written into the sub-journal if there exists one
34377 ** or more open savepoints for which:
34378 **
34379 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
34380 **   * The bit corresponding to the page-number is not set in
34381 **     PagerSavepoint.pInSavepoint.
34382 */
34383 static int subjRequiresPage(PgHdr *pPg){
34384   Pgno pgno = pPg->pgno;
34385   Pager *pPager = pPg->pPager;
34386   int i;
34387   for(i=0; i<pPager->nSavepoint; i++){
34388     PagerSavepoint *p = &pPager->aSavepoint[i];
34389     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
34390       return 1;
34391     }
34392   }
34393   return 0;
34394 }
34395
34396 /*
34397 ** Return true if the page is already in the journal file.
34398 */
34399 static int pageInJournal(PgHdr *pPg){
34400   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
34401 }
34402
34403 /*
34404 ** Read a 32-bit integer from the given file descriptor.  Store the integer
34405 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
34406 ** error code is something goes wrong.
34407 **
34408 ** All values are stored on disk as big-endian.
34409 */
34410 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
34411   unsigned char ac[4];
34412   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
34413   if( rc==SQLITE_OK ){
34414     *pRes = sqlite3Get4byte(ac);
34415   }
34416   return rc;
34417 }
34418
34419 /*
34420 ** Write a 32-bit integer into a string buffer in big-endian byte order.
34421 */
34422 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
34423
34424 /*
34425 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
34426 ** on success or an error code is something goes wrong.
34427 */
34428 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
34429   char ac[4];
34430   put32bits(ac, val);
34431   return sqlite3OsWrite(fd, ac, 4, offset);
34432 }
34433
34434 /*
34435 ** The argument to this macro is a file descriptor (type sqlite3_file*).
34436 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
34437 **
34438 ** This is so that expressions can be written as:
34439 **
34440 **   if( isOpen(pPager->jfd) ){ ...
34441 **
34442 ** instead of
34443 **
34444 **   if( pPager->jfd->pMethods ){ ...
34445 */
34446 #define isOpen(pFd) ((pFd)->pMethods)
34447
34448 /*
34449 ** If file pFd is open, call sqlite3OsUnlock() on it.
34450 */
34451 static int osUnlock(sqlite3_file *pFd, int eLock){
34452   if( !isOpen(pFd) ){
34453     return SQLITE_OK;
34454   }
34455   return sqlite3OsUnlock(pFd, eLock);
34456 }
34457
34458 /*
34459 ** This function determines whether or not the atomic-write optimization
34460 ** can be used with this pager. The optimization can be used if:
34461 **
34462 **  (a) the value returned by OsDeviceCharacteristics() indicates that
34463 **      a database page may be written atomically, and
34464 **  (b) the value returned by OsSectorSize() is less than or equal
34465 **      to the page size.
34466 **
34467 ** The optimization is also always enabled for temporary files. It is
34468 ** an error to call this function if pPager is opened on an in-memory
34469 ** database.
34470 **
34471 ** If the optimization cannot be used, 0 is returned. If it can be used,
34472 ** then the value returned is the size of the journal file when it
34473 ** contains rollback data for exactly one page.
34474 */
34475 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
34476 static int jrnlBufferSize(Pager *pPager){
34477   assert( !MEMDB );
34478   if( !pPager->tempFile ){
34479     int dc;                           /* Device characteristics */
34480     int nSector;                      /* Sector size */
34481     int szPage;                       /* Page size */
34482
34483     assert( isOpen(pPager->fd) );
34484     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
34485     nSector = pPager->sectorSize;
34486     szPage = pPager->pageSize;
34487
34488     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34489     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34490     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
34491       return 0;
34492     }
34493   }
34494
34495   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
34496 }
34497 #endif
34498
34499 /*
34500 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
34501 ** on the cache using a hash function.  This is used for testing
34502 ** and debugging only.
34503 */
34504 #ifdef SQLITE_CHECK_PAGES
34505 /*
34506 ** Return a 32-bit hash of the page data for pPage.
34507 */
34508 static u32 pager_datahash(int nByte, unsigned char *pData){
34509   u32 hash = 0;
34510   int i;
34511   for(i=0; i<nByte; i++){
34512     hash = (hash*1039) + pData[i];
34513   }
34514   return hash;
34515 }
34516 static u32 pager_pagehash(PgHdr *pPage){
34517   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
34518 }
34519 static void pager_set_pagehash(PgHdr *pPage){
34520   pPage->pageHash = pager_pagehash(pPage);
34521 }
34522
34523 /*
34524 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
34525 ** is defined, and NDEBUG is not defined, an assert() statement checks
34526 ** that the page is either dirty or still matches the calculated page-hash.
34527 */
34528 #define CHECK_PAGE(x) checkPage(x)
34529 static void checkPage(PgHdr *pPg){
34530   Pager *pPager = pPg->pPager;
34531   assert( !pPg->pageHash || pPager->errCode
34532       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
34533 }
34534
34535 #else
34536 #define pager_datahash(X,Y)  0
34537 #define pager_pagehash(X)  0
34538 #define CHECK_PAGE(x)
34539 #endif  /* SQLITE_CHECK_PAGES */
34540
34541 /*
34542 ** When this is called the journal file for pager pPager must be open.
34543 ** This function attempts to read a master journal file name from the 
34544 ** end of the file and, if successful, copies it into memory supplied 
34545 ** by the caller. See comments above writeMasterJournal() for the format
34546 ** used to store a master journal file name at the end of a journal file.
34547 **
34548 ** zMaster must point to a buffer of at least nMaster bytes allocated by
34549 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
34550 ** enough space to write the master journal name). If the master journal
34551 ** name in the journal is longer than nMaster bytes (including a
34552 ** nul-terminator), then this is handled as if no master journal name
34553 ** were present in the journal.
34554 **
34555 ** If a master journal file name is present at the end of the journal
34556 ** file, then it is copied into the buffer pointed to by zMaster. A
34557 ** nul-terminator byte is appended to the buffer following the master
34558 ** journal file name.
34559 **
34560 ** If it is determined that no master journal file name is present 
34561 ** zMaster[0] is set to 0 and SQLITE_OK returned.
34562 **
34563 ** If an error occurs while reading from the journal file, an SQLite
34564 ** error code is returned.
34565 */
34566 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
34567   int rc;                    /* Return code */
34568   u32 len;                   /* Length in bytes of master journal name */
34569   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
34570   u32 cksum;                 /* MJ checksum value read from journal */
34571   u32 u;                     /* Unsigned loop counter */
34572   unsigned char aMagic[8];   /* A buffer to hold the magic header */
34573   zMaster[0] = '\0';
34574
34575   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
34576    || szJ<16
34577    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
34578    || len>=nMaster 
34579    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
34580    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
34581    || memcmp(aMagic, aJournalMagic, 8)
34582    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
34583   ){
34584     return rc;
34585   }
34586
34587   /* See if the checksum matches the master journal name */
34588   for(u=0; u<len; u++){
34589     cksum -= zMaster[u];
34590   }
34591   if( cksum ){
34592     /* If the checksum doesn't add up, then one or more of the disk sectors
34593     ** containing the master journal filename is corrupted. This means
34594     ** definitely roll back, so just return SQLITE_OK and report a (nul)
34595     ** master-journal filename.
34596     */
34597     len = 0;
34598   }
34599   zMaster[len] = '\0';
34600    
34601   return SQLITE_OK;
34602 }
34603
34604 /*
34605 ** Return the offset of the sector boundary at or immediately 
34606 ** following the value in pPager->journalOff, assuming a sector 
34607 ** size of pPager->sectorSize bytes.
34608 **
34609 ** i.e for a sector size of 512:
34610 **
34611 **   Pager.journalOff          Return value
34612 **   ---------------------------------------
34613 **   0                         0
34614 **   512                       512
34615 **   100                       512
34616 **   2000                      2048
34617 ** 
34618 */
34619 static i64 journalHdrOffset(Pager *pPager){
34620   i64 offset = 0;
34621   i64 c = pPager->journalOff;
34622   if( c ){
34623     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
34624   }
34625   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
34626   assert( offset>=c );
34627   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
34628   return offset;
34629 }
34630
34631 /*
34632 ** The journal file must be open when this function is called.
34633 **
34634 ** This function is a no-op if the journal file has not been written to
34635 ** within the current transaction (i.e. if Pager.journalOff==0).
34636 **
34637 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
34638 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
34639 ** zero the 28-byte header at the start of the journal file. In either case, 
34640 ** if the pager is not in no-sync mode, sync the journal file immediately 
34641 ** after writing or truncating it.
34642 **
34643 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
34644 ** following the truncation or zeroing described above the size of the 
34645 ** journal file in bytes is larger than this value, then truncate the
34646 ** journal file to Pager.journalSizeLimit bytes. The journal file does
34647 ** not need to be synced following this operation.
34648 **
34649 ** If an IO error occurs, abandon processing and return the IO error code.
34650 ** Otherwise, return SQLITE_OK.
34651 */
34652 static int zeroJournalHdr(Pager *pPager, int doTruncate){
34653   int rc = SQLITE_OK;                               /* Return code */
34654   assert( isOpen(pPager->jfd) );
34655   if( pPager->journalOff ){
34656     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
34657
34658     IOTRACE(("JZEROHDR %p\n", pPager))
34659     if( doTruncate || iLimit==0 ){
34660       rc = sqlite3OsTruncate(pPager->jfd, 0);
34661     }else{
34662       static const char zeroHdr[28] = {0};
34663       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
34664     }
34665     if( rc==SQLITE_OK && !pPager->noSync ){
34666       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
34667     }
34668
34669     /* At this point the transaction is committed but the write lock 
34670     ** is still held on the file. If there is a size limit configured for 
34671     ** the persistent journal and the journal file currently consumes more
34672     ** space than that limit allows for, truncate it now. There is no need
34673     ** to sync the file following this operation.
34674     */
34675     if( rc==SQLITE_OK && iLimit>0 ){
34676       i64 sz;
34677       rc = sqlite3OsFileSize(pPager->jfd, &sz);
34678       if( rc==SQLITE_OK && sz>iLimit ){
34679         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
34680       }
34681     }
34682   }
34683   return rc;
34684 }
34685
34686 /*
34687 ** The journal file must be open when this routine is called. A journal
34688 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
34689 ** current location.
34690 **
34691 ** The format for the journal header is as follows:
34692 ** - 8 bytes: Magic identifying journal format.
34693 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
34694 ** - 4 bytes: Random number used for page hash.
34695 ** - 4 bytes: Initial database page count.
34696 ** - 4 bytes: Sector size used by the process that wrote this journal.
34697 ** - 4 bytes: Database page size.
34698 ** 
34699 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
34700 */
34701 static int writeJournalHdr(Pager *pPager){
34702   int rc = SQLITE_OK;                 /* Return code */
34703   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
34704   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
34705   u32 nWrite;                         /* Bytes of header sector written */
34706   int ii;                             /* Loop counter */
34707
34708   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34709
34710   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
34711     nHeader = JOURNAL_HDR_SZ(pPager);
34712   }
34713
34714   /* If there are active savepoints and any of them were created 
34715   ** since the most recent journal header was written, update the 
34716   ** PagerSavepoint.iHdrOffset fields now.
34717   */
34718   for(ii=0; ii<pPager->nSavepoint; ii++){
34719     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
34720       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
34721     }
34722   }
34723
34724   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
34725
34726   /* 
34727   ** Write the nRec Field - the number of page records that follow this
34728   ** journal header. Normally, zero is written to this value at this time.
34729   ** After the records are added to the journal (and the journal synced, 
34730   ** if in full-sync mode), the zero is overwritten with the true number
34731   ** of records (see syncJournal()).
34732   **
34733   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
34734   ** reading the journal this value tells SQLite to assume that the
34735   ** rest of the journal file contains valid page records. This assumption
34736   ** is dangerous, as if a failure occurred whilst writing to the journal
34737   ** file it may contain some garbage data. There are two scenarios
34738   ** where this risk can be ignored:
34739   **
34740   **   * When the pager is in no-sync mode. Corruption can follow a
34741   **     power failure in this case anyway.
34742   **
34743   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
34744   **     that garbage data is never appended to the journal file.
34745   */
34746   assert( isOpen(pPager->fd) || pPager->noSync );
34747   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
34748    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
34749   ){
34750     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34751     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
34752   }else{
34753     memset(zHeader, 0, sizeof(aJournalMagic)+4);
34754   }
34755
34756   /* The random check-hash initialiser */ 
34757   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
34758   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
34759   /* The initial database size */
34760   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
34761   /* The assumed sector size for this process */
34762   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
34763
34764   /* The page size */
34765   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
34766
34767   /* Initializing the tail of the buffer is not necessary.  Everything
34768   ** works find if the following memset() is omitted.  But initializing
34769   ** the memory prevents valgrind from complaining, so we are willing to
34770   ** take the performance hit.
34771   */
34772   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
34773          nHeader-(sizeof(aJournalMagic)+20));
34774
34775   /* In theory, it is only necessary to write the 28 bytes that the 
34776   ** journal header consumes to the journal file here. Then increment the 
34777   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
34778   ** record is written to the following sector (leaving a gap in the file
34779   ** that will be implicitly filled in by the OS).
34780   **
34781   ** However it has been discovered that on some systems this pattern can 
34782   ** be significantly slower than contiguously writing data to the file,
34783   ** even if that means explicitly writing data to the block of 
34784   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
34785   ** is done. 
34786   **
34787   ** The loop is required here in case the sector-size is larger than the 
34788   ** database page size. Since the zHeader buffer is only Pager.pageSize
34789   ** bytes in size, more than one call to sqlite3OsWrite() may be required
34790   ** to populate the entire journal header sector.
34791   */ 
34792   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
34793     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
34794     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
34795     assert( pPager->journalHdr <= pPager->journalOff );
34796     pPager->journalOff += nHeader;
34797   }
34798
34799   return rc;
34800 }
34801
34802 /*
34803 ** The journal file must be open when this is called. A journal header file
34804 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
34805 ** file. The current location in the journal file is given by
34806 ** pPager->journalOff. See comments above function writeJournalHdr() for
34807 ** a description of the journal header format.
34808 **
34809 ** If the header is read successfully, *pNRec is set to the number of
34810 ** page records following this header and *pDbSize is set to the size of the
34811 ** database before the transaction began, in pages. Also, pPager->cksumInit
34812 ** is set to the value read from the journal header. SQLITE_OK is returned
34813 ** in this case.
34814 **
34815 ** If the journal header file appears to be corrupted, SQLITE_DONE is
34816 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
34817 ** cannot be read from the journal file an error code is returned.
34818 */
34819 static int readJournalHdr(
34820   Pager *pPager,               /* Pager object */
34821   int isHot,
34822   i64 journalSize,             /* Size of the open journal file in bytes */
34823   u32 *pNRec,                  /* OUT: Value read from the nRec field */
34824   u32 *pDbSize                 /* OUT: Value of original database size field */
34825 ){
34826   int rc;                      /* Return code */
34827   unsigned char aMagic[8];     /* A buffer to hold the magic header */
34828   i64 iHdrOff;                 /* Offset of journal header being read */
34829
34830   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34831
34832   /* Advance Pager.journalOff to the start of the next sector. If the
34833   ** journal file is too small for there to be a header stored at this
34834   ** point, return SQLITE_DONE.
34835   */
34836   pPager->journalOff = journalHdrOffset(pPager);
34837   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
34838     return SQLITE_DONE;
34839   }
34840   iHdrOff = pPager->journalOff;
34841
34842   /* Read in the first 8 bytes of the journal header. If they do not match
34843   ** the  magic string found at the start of each journal header, return
34844   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
34845   ** proceed.
34846   */
34847   if( isHot || iHdrOff!=pPager->journalHdr ){
34848     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
34849     if( rc ){
34850       return rc;
34851     }
34852     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
34853       return SQLITE_DONE;
34854     }
34855   }
34856
34857   /* Read the first three 32-bit fields of the journal header: The nRec
34858   ** field, the checksum-initializer and the database size at the start
34859   ** of the transaction. Return an error code if anything goes wrong.
34860   */
34861   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
34862    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
34863    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
34864   ){
34865     return rc;
34866   }
34867
34868   if( pPager->journalOff==0 ){
34869     u32 iPageSize;               /* Page-size field of journal header */
34870     u32 iSectorSize;             /* Sector-size field of journal header */
34871     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
34872
34873     /* Read the page-size and sector-size journal header fields. */
34874     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
34875      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
34876     ){
34877       return rc;
34878     }
34879
34880     /* Check that the values read from the page-size and sector-size fields
34881     ** are within range. To be 'in range', both values need to be a power
34882     ** of two greater than or equal to 512 or 32, and not greater than their 
34883     ** respective compile time maximum limits.
34884     */
34885     if( iPageSize<512                  || iSectorSize<32
34886      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
34887      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
34888     ){
34889       /* If the either the page-size or sector-size in the journal-header is 
34890       ** invalid, then the process that wrote the journal-header must have 
34891       ** crashed before the header was synced. In this case stop reading 
34892       ** the journal file here.
34893       */
34894       return SQLITE_DONE;
34895     }
34896
34897     /* Update the page-size to match the value read from the journal. 
34898     ** Use a testcase() macro to make sure that malloc failure within 
34899     ** PagerSetPagesize() is tested.
34900     */
34901     iPageSize16 = (u16)iPageSize;
34902     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
34903     testcase( rc!=SQLITE_OK );
34904     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
34905
34906     /* Update the assumed sector-size to match the value used by 
34907     ** the process that created this journal. If this journal was
34908     ** created by a process other than this one, then this routine
34909     ** is being called from within pager_playback(). The local value
34910     ** of Pager.sectorSize is restored at the end of that routine.
34911     */
34912     pPager->sectorSize = iSectorSize;
34913   }
34914
34915   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
34916   return rc;
34917 }
34918
34919
34920 /*
34921 ** Write the supplied master journal name into the journal file for pager
34922 ** pPager at the current location. The master journal name must be the last
34923 ** thing written to a journal file. If the pager is in full-sync mode, the
34924 ** journal file descriptor is advanced to the next sector boundary before
34925 ** anything is written. The format is:
34926 **
34927 **   + 4 bytes: PAGER_MJ_PGNO.
34928 **   + N bytes: Master journal filename in utf-8.
34929 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
34930 **   + 4 bytes: Master journal name checksum.
34931 **   + 8 bytes: aJournalMagic[].
34932 **
34933 ** The master journal page checksum is the sum of the bytes in the master
34934 ** journal name, where each byte is interpreted as a signed 8-bit integer.
34935 **
34936 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
34937 ** this call is a no-op.
34938 */
34939 static int writeMasterJournal(Pager *pPager, const char *zMaster){
34940   int rc;                          /* Return code */
34941   int nMaster;                     /* Length of string zMaster */
34942   i64 iHdrOff;                     /* Offset of header in journal file */
34943   i64 jrnlSize;                    /* Size of journal file on disk */
34944   u32 cksum = 0;                   /* Checksum of string zMaster */
34945
34946   if( !zMaster || pPager->setMaster
34947    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
34948    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
34949   ){
34950     return SQLITE_OK;
34951   }
34952   pPager->setMaster = 1;
34953   assert( isOpen(pPager->jfd) );
34954   assert( pPager->journalHdr <= pPager->journalOff );
34955
34956   /* Calculate the length in bytes and the checksum of zMaster */
34957   for(nMaster=0; zMaster[nMaster]; nMaster++){
34958     cksum += zMaster[nMaster];
34959   }
34960
34961   /* If in full-sync mode, advance to the next disk sector before writing
34962   ** the master journal name. This is in case the previous page written to
34963   ** the journal has already been synced.
34964   */
34965   if( pPager->fullSync ){
34966     pPager->journalOff = journalHdrOffset(pPager);
34967   }
34968   iHdrOff = pPager->journalOff;
34969
34970   /* Write the master journal data to the end of the journal file. If
34971   ** an error occurs, return the error code to the caller.
34972   */
34973   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
34974    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
34975    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
34976    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
34977    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
34978   ){
34979     return rc;
34980   }
34981   pPager->journalOff += (nMaster+20);
34982   pPager->needSync = !pPager->noSync;
34983
34984   /* If the pager is in peristent-journal mode, then the physical 
34985   ** journal-file may extend past the end of the master-journal name
34986   ** and 8 bytes of magic data just written to the file. This is 
34987   ** dangerous because the code to rollback a hot-journal file
34988   ** will not be able to find the master-journal name to determine 
34989   ** whether or not the journal is hot. 
34990   **
34991   ** Easiest thing to do in this scenario is to truncate the journal 
34992   ** file to the required size.
34993   */ 
34994   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
34995    && jrnlSize>pPager->journalOff
34996   ){
34997     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
34998   }
34999   return rc;
35000 }
35001
35002 /*
35003 ** Find a page in the hash table given its page number. Return
35004 ** a pointer to the page or NULL if the requested page is not 
35005 ** already in memory.
35006 */
35007 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
35008   PgHdr *p;                         /* Return value */
35009
35010   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
35011   ** fail, since no attempt to allocate dynamic memory will be made.
35012   */
35013   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
35014   return p;
35015 }
35016
35017 /*
35018 ** Unless the pager is in error-state, discard all in-memory pages. If
35019 ** the pager is in error-state, then this call is a no-op.
35020 **
35021 ** TODO: Why can we not reset the pager while in error state?
35022 */
35023 static void pager_reset(Pager *pPager){
35024   if( SQLITE_OK==pPager->errCode ){
35025     sqlite3BackupRestart(pPager->pBackup);
35026     sqlite3PcacheClear(pPager->pPCache);
35027     pPager->dbSizeValid = 0;
35028   }
35029 }
35030
35031 /*
35032 ** Free all structures in the Pager.aSavepoint[] array and set both
35033 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
35034 ** if it is open and the pager is not in exclusive mode.
35035 */
35036 static void releaseAllSavepoints(Pager *pPager){
35037   int ii;               /* Iterator for looping through Pager.aSavepoint */
35038   for(ii=0; ii<pPager->nSavepoint; ii++){
35039     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
35040   }
35041   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
35042     sqlite3OsClose(pPager->sjfd);
35043   }
35044   sqlite3_free(pPager->aSavepoint);
35045   pPager->aSavepoint = 0;
35046   pPager->nSavepoint = 0;
35047   pPager->nSubRec = 0;
35048 }
35049
35050 /*
35051 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
35052 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
35053 ** or SQLITE_NOMEM if a malloc failure occurs.
35054 */
35055 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
35056   int ii;                   /* Loop counter */
35057   int rc = SQLITE_OK;       /* Result code */
35058
35059   for(ii=0; ii<pPager->nSavepoint; ii++){
35060     PagerSavepoint *p = &pPager->aSavepoint[ii];
35061     if( pgno<=p->nOrig ){
35062       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
35063       testcase( rc==SQLITE_NOMEM );
35064       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35065     }
35066   }
35067   return rc;
35068 }
35069
35070 /*
35071 ** Return true if this pager uses a write-ahead log instead of the usual
35072 ** rollback journal. Otherwise false.
35073 */
35074 #ifndef SQLITE_OMIT_WAL
35075 static int pagerUseWal(Pager *pPager){
35076   return (pPager->pWal!=0);
35077 }
35078 #else
35079 # define pagerUseWal(x) 0
35080 # define pagerRollbackWal(x) 0
35081 # define pagerWalFrames(v,w,x,y,z) 0
35082 # define pagerOpenWalIfPresent(z) SQLITE_OK
35083 # define pagerBeginReadTransaction(z) SQLITE_OK
35084 #endif
35085
35086 /*
35087 ** Unlock the database file. This function is a no-op if the pager
35088 ** is in exclusive mode.
35089 **
35090 ** If the pager is currently in error state, discard the contents of 
35091 ** the cache and reset the Pager structure internal state. If there is
35092 ** an open journal-file, then the next time a shared-lock is obtained
35093 ** on the pager file (by this or any other process), it will be
35094 ** treated as a hot-journal and rolled back.
35095 */
35096 static void pager_unlock(Pager *pPager){
35097   if( !pPager->exclusiveMode ){
35098     int rc = SQLITE_OK;          /* Return code */
35099     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
35100
35101     /* If the operating system support deletion of open files, then
35102     ** close the journal file when dropping the database lock.  Otherwise
35103     ** another connection with journal_mode=delete might delete the file
35104     ** out from under us.
35105     */
35106     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
35107     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
35108     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
35109     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
35110     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
35111     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
35112     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
35113      || 1!=(pPager->journalMode & 5)
35114     ){
35115       sqlite3OsClose(pPager->jfd);
35116     }
35117
35118     sqlite3BitvecDestroy(pPager->pInJournal);
35119     pPager->pInJournal = 0;
35120     releaseAllSavepoints(pPager);
35121
35122     /* If the file is unlocked, somebody else might change it. The
35123     ** values stored in Pager.dbSize etc. might become invalid if
35124     ** this happens.  One can argue that this doesn't need to be cleared
35125     ** until the change-counter check fails in PagerSharedLock().
35126     ** Clearing the page size cache here is being conservative.
35127     */
35128     pPager->dbSizeValid = 0;
35129
35130     if( pagerUseWal(pPager) ){
35131       sqlite3WalEndReadTransaction(pPager->pWal);
35132     }else{
35133       rc = osUnlock(pPager->fd, NO_LOCK);
35134     }
35135     if( rc ){
35136       pPager->errCode = rc;
35137     }
35138     IOTRACE(("UNLOCK %p\n", pPager))
35139
35140     /* If Pager.errCode is set, the contents of the pager cache cannot be
35141     ** trusted. Now that the pager file is unlocked, the contents of the
35142     ** cache can be discarded and the error code safely cleared.
35143     */
35144     if( pPager->errCode ){
35145       if( rc==SQLITE_OK ){
35146         pPager->errCode = SQLITE_OK;
35147       }
35148       pager_reset(pPager);
35149     }
35150
35151     pPager->changeCountDone = 0;
35152     pPager->state = PAGER_UNLOCK;
35153     pPager->dbModified = 0;
35154   }
35155 }
35156
35157 /*
35158 ** This function should be called when an IOERR, CORRUPT or FULL error
35159 ** may have occurred. The first argument is a pointer to the pager 
35160 ** structure, the second the error-code about to be returned by a pager 
35161 ** API function. The value returned is a copy of the second argument 
35162 ** to this function. 
35163 **
35164 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
35165 ** the error becomes persistent. Until the persistent error is cleared,
35166 ** subsequent API calls on this Pager will immediately return the same 
35167 ** error code.
35168 **
35169 ** A persistent error indicates that the contents of the pager-cache 
35170 ** cannot be trusted. This state can be cleared by completely discarding 
35171 ** the contents of the pager-cache. If a transaction was active when
35172 ** the persistent error occurred, then the rollback journal may need
35173 ** to be replayed to restore the contents of the database file (as if
35174 ** it were a hot-journal).
35175 */
35176 static int pager_error(Pager *pPager, int rc){
35177   int rc2 = rc & 0xff;
35178   assert( rc==SQLITE_OK || !MEMDB );
35179   assert(
35180        pPager->errCode==SQLITE_FULL ||
35181        pPager->errCode==SQLITE_OK ||
35182        (pPager->errCode & 0xff)==SQLITE_IOERR
35183   );
35184   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
35185     pPager->errCode = rc;
35186   }
35187   return rc;
35188 }
35189
35190 /*
35191 ** Execute a rollback if a transaction is active and unlock the 
35192 ** database file. 
35193 **
35194 ** If the pager has already entered the error state, do not attempt 
35195 ** the rollback at this time. Instead, pager_unlock() is called. The
35196 ** call to pager_unlock() will discard all in-memory pages, unlock
35197 ** the database file and clear the error state. If this means that
35198 ** there is a hot-journal left in the file-system, the next connection
35199 ** to obtain a shared lock on the pager (which may be this one) will
35200 ** roll it back.
35201 **
35202 ** If the pager has not already entered the error state, but an IO or
35203 ** malloc error occurs during a rollback, then this will itself cause 
35204 ** the pager to enter the error state. Which will be cleared by the
35205 ** call to pager_unlock(), as described above.
35206 */
35207 static void pagerUnlockAndRollback(Pager *pPager){
35208   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
35209     sqlite3BeginBenignMalloc();
35210     sqlite3PagerRollback(pPager);
35211     sqlite3EndBenignMalloc();
35212   }
35213   pager_unlock(pPager);
35214 }
35215
35216 /*
35217 ** This routine ends a transaction. A transaction is usually ended by 
35218 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
35219 ** after rollback of a hot-journal, or if an error occurs while opening
35220 ** the journal file or writing the very first journal-header of a
35221 ** database transaction.
35222 ** 
35223 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
35224 ** routine is called, it is a no-op (returns SQLITE_OK).
35225 **
35226 ** Otherwise, any active savepoints are released.
35227 **
35228 ** If the journal file is open, then it is "finalized". Once a journal 
35229 ** file has been finalized it is not possible to use it to roll back a 
35230 ** transaction. Nor will it be considered to be a hot-journal by this
35231 ** or any other database connection. Exactly how a journal is finalized
35232 ** depends on whether or not the pager is running in exclusive mode and
35233 ** the current journal-mode (Pager.journalMode value), as follows:
35234 **
35235 **   journalMode==MEMORY
35236 **     Journal file descriptor is simply closed. This destroys an 
35237 **     in-memory journal.
35238 **
35239 **   journalMode==TRUNCATE
35240 **     Journal file is truncated to zero bytes in size.
35241 **
35242 **   journalMode==PERSIST
35243 **     The first 28 bytes of the journal file are zeroed. This invalidates
35244 **     the first journal header in the file, and hence the entire journal
35245 **     file. An invalid journal file cannot be rolled back.
35246 **
35247 **   journalMode==DELETE
35248 **     The journal file is closed and deleted using sqlite3OsDelete().
35249 **
35250 **     If the pager is running in exclusive mode, this method of finalizing
35251 **     the journal file is never used. Instead, if the journalMode is
35252 **     DELETE and the pager is in exclusive mode, the method described under
35253 **     journalMode==PERSIST is used instead.
35254 **
35255 ** After the journal is finalized, if running in non-exclusive mode, the
35256 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
35257 ** database file accordingly).
35258 **
35259 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
35260 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
35261 ** exclusive mode.
35262 **
35263 ** SQLITE_OK is returned if no error occurs. If an error occurs during
35264 ** any of the IO operations to finalize the journal file or unlock the
35265 ** database then the IO error code is returned to the user. If the 
35266 ** operation to finalize the journal file fails, then the code still
35267 ** tries to unlock the database file if not in exclusive mode. If the
35268 ** unlock operation fails as well, then the first error code related
35269 ** to the first error encountered (the journal finalization one) is
35270 ** returned.
35271 */
35272 static int pager_end_transaction(Pager *pPager, int hasMaster){
35273   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
35274   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
35275
35276   if( pPager->state<PAGER_RESERVED ){
35277     return SQLITE_OK;
35278   }
35279   releaseAllSavepoints(pPager);
35280
35281   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
35282   if( isOpen(pPager->jfd) ){
35283     assert( !pagerUseWal(pPager) );
35284
35285     /* Finalize the journal file. */
35286     if( sqlite3IsMemJournal(pPager->jfd) ){
35287       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
35288       sqlite3OsClose(pPager->jfd);
35289     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
35290       if( pPager->journalOff==0 ){
35291         rc = SQLITE_OK;
35292       }else{
35293         rc = sqlite3OsTruncate(pPager->jfd, 0);
35294       }
35295       pPager->journalOff = 0;
35296       pPager->journalStarted = 0;
35297     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
35298       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
35299     ){
35300       rc = zeroJournalHdr(pPager, hasMaster);
35301       pager_error(pPager, rc);
35302       pPager->journalOff = 0;
35303       pPager->journalStarted = 0;
35304     }else{
35305       /* This branch may be executed with Pager.journalMode==MEMORY if
35306       ** a hot-journal was just rolled back. In this case the journal
35307       ** file should be closed and deleted. If this connection writes to
35308       ** the database file, it will do so using an in-memory journal. 
35309       */
35310       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
35311            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
35312            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
35313       );
35314       sqlite3OsClose(pPager->jfd);
35315       if( !pPager->tempFile ){
35316         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
35317       }
35318     }
35319
35320 #ifdef SQLITE_CHECK_PAGES
35321     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
35322 #endif
35323   }
35324   sqlite3BitvecDestroy(pPager->pInJournal);
35325   pPager->pInJournal = 0;
35326   pPager->nRec = 0;
35327   sqlite3PcacheCleanAll(pPager->pPCache);
35328
35329   if( pagerUseWal(pPager) ){
35330     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
35331     assert( rc2==SQLITE_OK );
35332     pPager->state = PAGER_SHARED;
35333
35334     /* If the connection was in locking_mode=exclusive mode but is no longer,
35335     ** drop the EXCLUSIVE lock held on the database file.
35336     */
35337     if( !pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, 0) ){
35338       rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35339     }
35340   }else if( !pPager->exclusiveMode ){
35341     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35342     pPager->state = PAGER_SHARED;
35343     pPager->changeCountDone = 0;
35344   }else if( pPager->state==PAGER_SYNCED ){
35345     pPager->state = PAGER_EXCLUSIVE;
35346   }
35347   pPager->setMaster = 0;
35348   pPager->needSync = 0;
35349   pPager->dbModified = 0;
35350
35351   /* TODO: Is this optimal? Why is the db size invalidated here 
35352   ** when the database file is not unlocked? */
35353   pPager->dbOrigSize = 0;
35354   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
35355   if( !MEMDB ){
35356     pPager->dbSizeValid = 0;
35357   }
35358
35359   return (rc==SQLITE_OK?rc2:rc);
35360 }
35361
35362 /*
35363 ** Parameter aData must point to a buffer of pPager->pageSize bytes
35364 ** of data. Compute and return a checksum based ont the contents of the 
35365 ** page of data and the current value of pPager->cksumInit.
35366 **
35367 ** This is not a real checksum. It is really just the sum of the 
35368 ** random initial value (pPager->cksumInit) and every 200th byte
35369 ** of the page data, starting with byte offset (pPager->pageSize%200).
35370 ** Each byte is interpreted as an 8-bit unsigned integer.
35371 **
35372 ** Changing the formula used to compute this checksum results in an
35373 ** incompatible journal file format.
35374 **
35375 ** If journal corruption occurs due to a power failure, the most likely 
35376 ** scenario is that one end or the other of the record will be changed. 
35377 ** It is much less likely that the two ends of the journal record will be
35378 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
35379 ** though fast and simple, catches the mostly likely kind of corruption.
35380 */
35381 static u32 pager_cksum(Pager *pPager, const u8 *aData){
35382   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
35383   int i = pPager->pageSize-200;          /* Loop counter */
35384   while( i>0 ){
35385     cksum += aData[i];
35386     i -= 200;
35387   }
35388   return cksum;
35389 }
35390
35391 /*
35392 ** Report the current page size and number of reserved bytes back
35393 ** to the codec.
35394 */
35395 #ifdef SQLITE_HAS_CODEC
35396 static void pagerReportSize(Pager *pPager){
35397   if( pPager->xCodecSizeChng ){
35398     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
35399                            (int)pPager->nReserve);
35400   }
35401 }
35402 #else
35403 # define pagerReportSize(X)     /* No-op if we do not support a codec */
35404 #endif
35405
35406 /*
35407 ** Read a single page from either the journal file (if isMainJrnl==1) or
35408 ** from the sub-journal (if isMainJrnl==0) and playback that page.
35409 ** The page begins at offset *pOffset into the file. The *pOffset
35410 ** value is increased to the start of the next page in the journal.
35411 **
35412 ** The isMainJrnl flag is true if this is the main rollback journal and
35413 ** false for the statement journal.  The main rollback journal uses
35414 ** checksums - the statement journal does not.
35415 **
35416 ** If the page number of the page record read from the (sub-)journal file
35417 ** is greater than the current value of Pager.dbSize, then playback is
35418 ** skipped and SQLITE_OK is returned.
35419 **
35420 ** If pDone is not NULL, then it is a record of pages that have already
35421 ** been played back.  If the page at *pOffset has already been played back
35422 ** (if the corresponding pDone bit is set) then skip the playback.
35423 ** Make sure the pDone bit corresponding to the *pOffset page is set
35424 ** prior to returning.
35425 **
35426 ** If the page record is successfully read from the (sub-)journal file
35427 ** and played back, then SQLITE_OK is returned. If an IO error occurs
35428 ** while reading the record from the (sub-)journal file or while writing
35429 ** to the database file, then the IO error code is returned. If data
35430 ** is successfully read from the (sub-)journal file but appears to be
35431 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
35432 ** two circumstances:
35433 ** 
35434 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
35435 **   * If the record is being rolled back from the main journal file
35436 **     and the checksum field does not match the record content.
35437 **
35438 ** Neither of these two scenarios are possible during a savepoint rollback.
35439 **
35440 ** If this is a savepoint rollback, then memory may have to be dynamically
35441 ** allocated by this function. If this is the case and an allocation fails,
35442 ** SQLITE_NOMEM is returned.
35443 */
35444 static int pager_playback_one_page(
35445   Pager *pPager,                /* The pager being played back */
35446   i64 *pOffset,                 /* Offset of record to playback */
35447   Bitvec *pDone,                /* Bitvec of pages already played back */
35448   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
35449   int isSavepnt                 /* True for a savepoint rollback */
35450 ){
35451   int rc;
35452   PgHdr *pPg;                   /* An existing page in the cache */
35453   Pgno pgno;                    /* The page number of a page in journal */
35454   u32 cksum;                    /* Checksum used for sanity checking */
35455   char *aData;                  /* Temporary storage for the page */
35456   sqlite3_file *jfd;            /* The file descriptor for the journal file */
35457   int isSynced;                 /* True if journal page is synced */
35458
35459   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
35460   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
35461   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
35462   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
35463
35464   aData = pPager->pTmpSpace;
35465   assert( aData );         /* Temp storage must have already been allocated */
35466   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
35467
35468   /* Read the page number and page data from the journal or sub-journal
35469   ** file. Return an error code to the caller if an IO error occurs.
35470   */
35471   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
35472   rc = read32bits(jfd, *pOffset, &pgno);
35473   if( rc!=SQLITE_OK ) return rc;
35474   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
35475   if( rc!=SQLITE_OK ) return rc;
35476   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
35477
35478   /* Sanity checking on the page.  This is more important that I originally
35479   ** thought.  If a power failure occurs while the journal is being written,
35480   ** it could cause invalid data to be written into the journal.  We need to
35481   ** detect this invalid data (with high probability) and ignore it.
35482   */
35483   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
35484     assert( !isSavepnt );
35485     return SQLITE_DONE;
35486   }
35487   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
35488     return SQLITE_OK;
35489   }
35490   if( isMainJrnl ){
35491     rc = read32bits(jfd, (*pOffset)-4, &cksum);
35492     if( rc ) return rc;
35493     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
35494       return SQLITE_DONE;
35495     }
35496   }
35497
35498   /* If this page has already been played by before during the current
35499   ** rollback, then don't bother to play it back again.
35500   */
35501   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
35502     return rc;
35503   }
35504   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
35505
35506   /* When playing back page 1, restore the nReserve setting
35507   */
35508   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
35509     pPager->nReserve = ((u8*)aData)[20];
35510     pagerReportSize(pPager);
35511   }
35512
35513   /* If the pager is in RESERVED state, then there must be a copy of this
35514   ** page in the pager cache. In this case just update the pager cache,
35515   ** not the database file. The page is left marked dirty in this case.
35516   **
35517   ** An exception to the above rule: If the database is in no-sync mode
35518   ** and a page is moved during an incremental vacuum then the page may
35519   ** not be in the pager cache. Later: if a malloc() or IO error occurs
35520   ** during a Movepage() call, then the page may not be in the cache
35521   ** either. So the condition described in the above paragraph is not
35522   ** assert()able.
35523   **
35524   ** If in EXCLUSIVE state, then we update the pager cache if it exists
35525   ** and the main file. The page is then marked not dirty.
35526   **
35527   ** Ticket #1171:  The statement journal might contain page content that is
35528   ** different from the page content at the start of the transaction.
35529   ** This occurs when a page is changed prior to the start of a statement
35530   ** then changed again within the statement.  When rolling back such a
35531   ** statement we must not write to the original database unless we know
35532   ** for certain that original page contents are synced into the main rollback
35533   ** journal.  Otherwise, a power loss might leave modified data in the
35534   ** database file without an entry in the rollback journal that can
35535   ** restore the database to its original form.  Two conditions must be
35536   ** met before writing to the database files. (1) the database must be
35537   ** locked.  (2) we know that the original page content is fully synced
35538   ** in the main journal either because the page is not in cache or else
35539   ** the page is marked as needSync==0.
35540   **
35541   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
35542   ** is possible to fail a statement on a database that does not yet exist.
35543   ** Do not attempt to write if database file has never been opened.
35544   */
35545   if( pagerUseWal(pPager) ){
35546     pPg = 0;
35547   }else{
35548     pPg = pager_lookup(pPager, pgno);
35549   }
35550   assert( pPg || !MEMDB );
35551   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
35552            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
35553            (isMainJrnl?"main-journal":"sub-journal")
35554   ));
35555   if( isMainJrnl ){
35556     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
35557   }else{
35558     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
35559   }
35560   if( (pPager->state>=PAGER_EXCLUSIVE)
35561    && isOpen(pPager->fd)
35562    && isSynced
35563   ){
35564     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
35565     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
35566     assert( !pagerUseWal(pPager) );
35567     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
35568     if( pgno>pPager->dbFileSize ){
35569       pPager->dbFileSize = pgno;
35570     }
35571     if( pPager->pBackup ){
35572       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
35573       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
35574       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
35575     }
35576   }else if( !isMainJrnl && pPg==0 ){
35577     /* If this is a rollback of a savepoint and data was not written to
35578     ** the database and the page is not in-memory, there is a potential
35579     ** problem. When the page is next fetched by the b-tree layer, it 
35580     ** will be read from the database file, which may or may not be 
35581     ** current. 
35582     **
35583     ** There are a couple of different ways this can happen. All are quite
35584     ** obscure. When running in synchronous mode, this can only happen 
35585     ** if the page is on the free-list at the start of the transaction, then
35586     ** populated, then moved using sqlite3PagerMovepage().
35587     **
35588     ** The solution is to add an in-memory page to the cache containing
35589     ** the data just read from the sub-journal. Mark the page as dirty 
35590     ** and if the pager requires a journal-sync, then mark the page as 
35591     ** requiring a journal-sync before it is written.
35592     */
35593     assert( isSavepnt );
35594     assert( pPager->doNotSpill==0 );
35595     pPager->doNotSpill++;
35596     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
35597     assert( pPager->doNotSpill==1 );
35598     pPager->doNotSpill--;
35599     if( rc!=SQLITE_OK ) return rc;
35600     pPg->flags &= ~PGHDR_NEED_READ;
35601     sqlite3PcacheMakeDirty(pPg);
35602   }
35603   if( pPg ){
35604     /* No page should ever be explicitly rolled back that is in use, except
35605     ** for page 1 which is held in use in order to keep the lock on the
35606     ** database active. However such a page may be rolled back as a result
35607     ** of an internal error resulting in an automatic call to
35608     ** sqlite3PagerRollback().
35609     */
35610     void *pData;
35611     pData = pPg->pData;
35612     memcpy(pData, (u8*)aData, pPager->pageSize);
35613     pPager->xReiniter(pPg);
35614     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
35615       /* If the contents of this page were just restored from the main 
35616       ** journal file, then its content must be as they were when the 
35617       ** transaction was first opened. In this case we can mark the page
35618       ** as clean, since there will be no need to write it out to the
35619       ** database.
35620       **
35621       ** There is one exception to this rule. If the page is being rolled
35622       ** back as part of a savepoint (or statement) rollback from an 
35623       ** unsynced portion of the main journal file, then it is not safe
35624       ** to mark the page as clean. This is because marking the page as
35625       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
35626       ** already in the journal file (recorded in Pager.pInJournal) and
35627       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
35628       ** again within this transaction, it will be marked as dirty but
35629       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
35630       ** be written out into the database file before its journal file
35631       ** segment is synced. If a crash occurs during or following this,
35632       ** database corruption may ensue.
35633       */
35634       assert( !pagerUseWal(pPager) );
35635       sqlite3PcacheMakeClean(pPg);
35636     }
35637 #ifdef SQLITE_CHECK_PAGES
35638     pPg->pageHash = pager_pagehash(pPg);
35639 #endif
35640     /* If this was page 1, then restore the value of Pager.dbFileVers.
35641     ** Do this before any decoding. */
35642     if( pgno==1 ){
35643       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
35644     }
35645
35646     /* Decode the page just read from disk */
35647     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
35648     sqlite3PcacheRelease(pPg);
35649   }
35650   return rc;
35651 }
35652
35653 /*
35654 ** Parameter zMaster is the name of a master journal file. A single journal
35655 ** file that referred to the master journal file has just been rolled back.
35656 ** This routine checks if it is possible to delete the master journal file,
35657 ** and does so if it is.
35658 **
35659 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
35660 ** available for use within this function.
35661 **
35662 ** When a master journal file is created, it is populated with the names 
35663 ** of all of its child journals, one after another, formatted as utf-8 
35664 ** encoded text. The end of each child journal file is marked with a 
35665 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
35666 ** file for a transaction involving two databases might be:
35667 **
35668 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
35669 **
35670 ** A master journal file may only be deleted once all of its child 
35671 ** journals have been rolled back.
35672 **
35673 ** This function reads the contents of the master-journal file into 
35674 ** memory and loops through each of the child journal names. For
35675 ** each child journal, it checks if:
35676 **
35677 **   * if the child journal exists, and if so
35678 **   * if the child journal contains a reference to master journal 
35679 **     file zMaster
35680 **
35681 ** If a child journal can be found that matches both of the criteria
35682 ** above, this function returns without doing anything. Otherwise, if
35683 ** no such child journal can be found, file zMaster is deleted from
35684 ** the file-system using sqlite3OsDelete().
35685 **
35686 ** If an IO error within this function, an error code is returned. This
35687 ** function allocates memory by calling sqlite3Malloc(). If an allocation
35688 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
35689 ** occur, SQLITE_OK is returned.
35690 **
35691 ** TODO: This function allocates a single block of memory to load
35692 ** the entire contents of the master journal file. This could be
35693 ** a couple of kilobytes or so - potentially larger than the page 
35694 ** size.
35695 */
35696 static int pager_delmaster(Pager *pPager, const char *zMaster){
35697   sqlite3_vfs *pVfs = pPager->pVfs;
35698   int rc;                   /* Return code */
35699   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
35700   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
35701   char *zMasterJournal = 0; /* Contents of master journal file */
35702   i64 nMasterJournal;       /* Size of master journal file */
35703   char *zJournal;           /* Pointer to one journal within MJ file */
35704   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
35705   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
35706
35707   /* Allocate space for both the pJournal and pMaster file descriptors.
35708   ** If successful, open the master journal file for reading.
35709   */
35710   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
35711   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
35712   if( !pMaster ){
35713     rc = SQLITE_NOMEM;
35714   }else{
35715     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
35716     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
35717   }
35718   if( rc!=SQLITE_OK ) goto delmaster_out;
35719
35720   /* Load the entire master journal file into space obtained from
35721   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
35722   ** sufficient space (in zMasterPtr) to hold the names of master
35723   ** journal files extracted from regular rollback-journals.
35724   */
35725   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
35726   if( rc!=SQLITE_OK ) goto delmaster_out;
35727   nMasterPtr = pVfs->mxPathname+1;
35728   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
35729   if( !zMasterJournal ){
35730     rc = SQLITE_NOMEM;
35731     goto delmaster_out;
35732   }
35733   zMasterPtr = &zMasterJournal[nMasterJournal+1];
35734   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
35735   if( rc!=SQLITE_OK ) goto delmaster_out;
35736   zMasterJournal[nMasterJournal] = 0;
35737
35738   zJournal = zMasterJournal;
35739   while( (zJournal-zMasterJournal)<nMasterJournal ){
35740     int exists;
35741     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
35742     if( rc!=SQLITE_OK ){
35743       goto delmaster_out;
35744     }
35745     if( exists ){
35746       /* One of the journals pointed to by the master journal exists.
35747       ** Open it and check if it points at the master journal. If
35748       ** so, return without deleting the master journal file.
35749       */
35750       int c;
35751       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
35752       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
35753       if( rc!=SQLITE_OK ){
35754         goto delmaster_out;
35755       }
35756
35757       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
35758       sqlite3OsClose(pJournal);
35759       if( rc!=SQLITE_OK ){
35760         goto delmaster_out;
35761       }
35762
35763       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
35764       if( c ){
35765         /* We have a match. Do not delete the master journal file. */
35766         goto delmaster_out;
35767       }
35768     }
35769     zJournal += (sqlite3Strlen30(zJournal)+1);
35770   }
35771  
35772   sqlite3OsClose(pMaster);
35773   rc = sqlite3OsDelete(pVfs, zMaster, 0);
35774
35775 delmaster_out:
35776   sqlite3_free(zMasterJournal);
35777   if( pMaster ){
35778     sqlite3OsClose(pMaster);
35779     assert( !isOpen(pJournal) );
35780     sqlite3_free(pMaster);
35781   }
35782   return rc;
35783 }
35784
35785
35786 /*
35787 ** This function is used to change the actual size of the database 
35788 ** file in the file-system. This only happens when committing a transaction,
35789 ** or rolling back a transaction (including rolling back a hot-journal).
35790 **
35791 ** If the main database file is not open, or an exclusive lock is not
35792 ** held, this function is a no-op. Otherwise, the size of the file is
35793 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
35794 ** on disk is currently larger than nPage pages, then use the VFS
35795 ** xTruncate() method to truncate it.
35796 **
35797 ** Or, it might might be the case that the file on disk is smaller than 
35798 ** nPage pages. Some operating system implementations can get confused if 
35799 ** you try to truncate a file to some size that is larger than it 
35800 ** currently is, so detect this case and write a single zero byte to 
35801 ** the end of the new file instead.
35802 **
35803 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
35804 ** the database file, return the error code to the caller.
35805 */
35806 static int pager_truncate(Pager *pPager, Pgno nPage){
35807   int rc = SQLITE_OK;
35808   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
35809     i64 currentSize, newSize;
35810     /* TODO: Is it safe to use Pager.dbFileSize here? */
35811     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
35812     newSize = pPager->pageSize*(i64)nPage;
35813     if( rc==SQLITE_OK && currentSize!=newSize ){
35814       if( currentSize>newSize ){
35815         rc = sqlite3OsTruncate(pPager->fd, newSize);
35816       }else{
35817         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
35818       }
35819       if( rc==SQLITE_OK ){
35820         pPager->dbFileSize = nPage;
35821       }
35822     }
35823   }
35824   return rc;
35825 }
35826
35827 /*
35828 ** Set the value of the Pager.sectorSize variable for the given
35829 ** pager based on the value returned by the xSectorSize method
35830 ** of the open database file. The sector size will be used used 
35831 ** to determine the size and alignment of journal header and 
35832 ** master journal pointers within created journal files.
35833 **
35834 ** For temporary files the effective sector size is always 512 bytes.
35835 **
35836 ** Otherwise, for non-temporary files, the effective sector size is
35837 ** the value returned by the xSectorSize() method rounded up to 32 if
35838 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
35839 ** is greater than MAX_SECTOR_SIZE.
35840 */
35841 static void setSectorSize(Pager *pPager){
35842   assert( isOpen(pPager->fd) || pPager->tempFile );
35843
35844   if( !pPager->tempFile ){
35845     /* Sector size doesn't matter for temporary files. Also, the file
35846     ** may not have been opened yet, in which case the OsSectorSize()
35847     ** call will segfault.
35848     */
35849     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
35850   }
35851   if( pPager->sectorSize<32 ){
35852     pPager->sectorSize = 512;
35853   }
35854   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
35855     assert( MAX_SECTOR_SIZE>=512 );
35856     pPager->sectorSize = MAX_SECTOR_SIZE;
35857   }
35858 }
35859
35860 /*
35861 ** Playback the journal and thus restore the database file to
35862 ** the state it was in before we started making changes.  
35863 **
35864 ** The journal file format is as follows: 
35865 **
35866 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
35867 **  (2)  4 byte big-endian integer which is the number of valid page records
35868 **       in the journal.  If this value is 0xffffffff, then compute the
35869 **       number of page records from the journal size.
35870 **  (3)  4 byte big-endian integer which is the initial value for the 
35871 **       sanity checksum.
35872 **  (4)  4 byte integer which is the number of pages to truncate the
35873 **       database to during a rollback.
35874 **  (5)  4 byte big-endian integer which is the sector size.  The header
35875 **       is this many bytes in size.
35876 **  (6)  4 byte big-endian integer which is the page size.
35877 **  (7)  zero padding out to the next sector size.
35878 **  (8)  Zero or more pages instances, each as follows:
35879 **        +  4 byte page number.
35880 **        +  pPager->pageSize bytes of data.
35881 **        +  4 byte checksum
35882 **
35883 ** When we speak of the journal header, we mean the first 7 items above.
35884 ** Each entry in the journal is an instance of the 8th item.
35885 **
35886 ** Call the value from the second bullet "nRec".  nRec is the number of
35887 ** valid page entries in the journal.  In most cases, you can compute the
35888 ** value of nRec from the size of the journal file.  But if a power
35889 ** failure occurred while the journal was being written, it could be the
35890 ** case that the size of the journal file had already been increased but
35891 ** the extra entries had not yet made it safely to disk.  In such a case,
35892 ** the value of nRec computed from the file size would be too large.  For
35893 ** that reason, we always use the nRec value in the header.
35894 **
35895 ** If the nRec value is 0xffffffff it means that nRec should be computed
35896 ** from the file size.  This value is used when the user selects the
35897 ** no-sync option for the journal.  A power failure could lead to corruption
35898 ** in this case.  But for things like temporary table (which will be
35899 ** deleted when the power is restored) we don't care.  
35900 **
35901 ** If the file opened as the journal file is not a well-formed
35902 ** journal file then all pages up to the first corrupted page are rolled
35903 ** back (or no pages if the journal header is corrupted). The journal file
35904 ** is then deleted and SQLITE_OK returned, just as if no corruption had
35905 ** been encountered.
35906 **
35907 ** If an I/O or malloc() error occurs, the journal-file is not deleted
35908 ** and an error code is returned.
35909 **
35910 ** The isHot parameter indicates that we are trying to rollback a journal
35911 ** that might be a hot journal.  Or, it could be that the journal is 
35912 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
35913 ** If the journal really is hot, reset the pager cache prior rolling
35914 ** back any content.  If the journal is merely persistent, no reset is
35915 ** needed.
35916 */
35917 static int pager_playback(Pager *pPager, int isHot){
35918   sqlite3_vfs *pVfs = pPager->pVfs;
35919   i64 szJ;                 /* Size of the journal file in bytes */
35920   u32 nRec;                /* Number of Records in the journal */
35921   u32 u;                   /* Unsigned loop counter */
35922   Pgno mxPg = 0;           /* Size of the original file in pages */
35923   int rc;                  /* Result code of a subroutine */
35924   int res = 1;             /* Value returned by sqlite3OsAccess() */
35925   char *zMaster = 0;       /* Name of master journal file if any */
35926   int needPagerReset;      /* True to reset page prior to first page rollback */
35927
35928   /* Figure out how many records are in the journal.  Abort early if
35929   ** the journal is empty.
35930   */
35931   assert( isOpen(pPager->jfd) );
35932   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
35933   if( rc!=SQLITE_OK || szJ==0 ){
35934     goto end_playback;
35935   }
35936
35937   /* Read the master journal name from the journal, if it is present.
35938   ** If a master journal file name is specified, but the file is not
35939   ** present on disk, then the journal is not hot and does not need to be
35940   ** played back.
35941   **
35942   ** TODO: Technically the following is an error because it assumes that
35943   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
35944   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
35945   **  mxPathname is 512, which is the same as the minimum allowable value
35946   ** for pageSize.
35947   */
35948   zMaster = pPager->pTmpSpace;
35949   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
35950   if( rc==SQLITE_OK && zMaster[0] ){
35951     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
35952   }
35953   zMaster = 0;
35954   if( rc!=SQLITE_OK || !res ){
35955     goto end_playback;
35956   }
35957   pPager->journalOff = 0;
35958   needPagerReset = isHot;
35959
35960   /* This loop terminates either when a readJournalHdr() or 
35961   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
35962   ** occurs. 
35963   */
35964   while( 1 ){
35965     /* Read the next journal header from the journal file.  If there are
35966     ** not enough bytes left in the journal file for a complete header, or
35967     ** it is corrupted, then a process must of failed while writing it.
35968     ** This indicates nothing more needs to be rolled back.
35969     */
35970     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
35971     if( rc!=SQLITE_OK ){ 
35972       if( rc==SQLITE_DONE ){
35973         rc = SQLITE_OK;
35974       }
35975       goto end_playback;
35976     }
35977
35978     /* If nRec is 0xffffffff, then this journal was created by a process
35979     ** working in no-sync mode. This means that the rest of the journal
35980     ** file consists of pages, there are no more journal headers. Compute
35981     ** the value of nRec based on this assumption.
35982     */
35983     if( nRec==0xffffffff ){
35984       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35985       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
35986     }
35987
35988     /* If nRec is 0 and this rollback is of a transaction created by this
35989     ** process and if this is the final header in the journal, then it means
35990     ** that this part of the journal was being filled but has not yet been
35991     ** synced to disk.  Compute the number of pages based on the remaining
35992     ** size of the file.
35993     **
35994     ** The third term of the test was added to fix ticket #2565.
35995     ** When rolling back a hot journal, nRec==0 always means that the next
35996     ** chunk of the journal contains zero pages to be rolled back.  But
35997     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
35998     ** the journal, it means that the journal might contain additional
35999     ** pages that need to be rolled back and that the number of pages 
36000     ** should be computed based on the journal file size.
36001     */
36002     if( nRec==0 && !isHot &&
36003         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
36004       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
36005     }
36006
36007     /* If this is the first header read from the journal, truncate the
36008     ** database file back to its original size.
36009     */
36010     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
36011       rc = pager_truncate(pPager, mxPg);
36012       if( rc!=SQLITE_OK ){
36013         goto end_playback;
36014       }
36015       pPager->dbSize = mxPg;
36016     }
36017
36018     /* Copy original pages out of the journal and back into the 
36019     ** database file and/or page cache.
36020     */
36021     for(u=0; u<nRec; u++){
36022       if( needPagerReset ){
36023         pager_reset(pPager);
36024         needPagerReset = 0;
36025       }
36026       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
36027       if( rc!=SQLITE_OK ){
36028         if( rc==SQLITE_DONE ){
36029           rc = SQLITE_OK;
36030           pPager->journalOff = szJ;
36031           break;
36032         }else if( rc==SQLITE_IOERR_SHORT_READ ){
36033           /* If the journal has been truncated, simply stop reading and
36034           ** processing the journal. This might happen if the journal was
36035           ** not completely written and synced prior to a crash.  In that
36036           ** case, the database should have never been written in the
36037           ** first place so it is OK to simply abandon the rollback. */
36038           rc = SQLITE_OK;
36039           goto end_playback;
36040         }else{
36041           /* If we are unable to rollback, quit and return the error
36042           ** code.  This will cause the pager to enter the error state
36043           ** so that no further harm will be done.  Perhaps the next
36044           ** process to come along will be able to rollback the database.
36045           */
36046           goto end_playback;
36047         }
36048       }
36049     }
36050   }
36051   /*NOTREACHED*/
36052   assert( 0 );
36053
36054 end_playback:
36055   /* Following a rollback, the database file should be back in its original
36056   ** state prior to the start of the transaction, so invoke the
36057   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
36058   ** assertion that the transaction counter was modified.
36059   */
36060   assert(
36061     pPager->fd->pMethods==0 ||
36062     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
36063   );
36064
36065   /* If this playback is happening automatically as a result of an IO or 
36066   ** malloc error that occurred after the change-counter was updated but 
36067   ** before the transaction was committed, then the change-counter 
36068   ** modification may just have been reverted. If this happens in exclusive 
36069   ** mode, then subsequent transactions performed by the connection will not
36070   ** update the change-counter at all. This may lead to cache inconsistency
36071   ** problems for other processes at some point in the future. So, just
36072   ** in case this has happened, clear the changeCountDone flag now.
36073   */
36074   pPager->changeCountDone = pPager->tempFile;
36075
36076   if( rc==SQLITE_OK ){
36077     zMaster = pPager->pTmpSpace;
36078     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
36079     testcase( rc!=SQLITE_OK );
36080   }
36081   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
36082     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36083   }
36084   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
36085     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36086   }
36087   if( rc==SQLITE_OK ){
36088     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
36089     testcase( rc!=SQLITE_OK );
36090   }
36091   if( rc==SQLITE_OK && zMaster[0] && res ){
36092     /* If there was a master journal and this routine will return success,
36093     ** see if it is possible to delete the master journal.
36094     */
36095     rc = pager_delmaster(pPager, zMaster);
36096     testcase( rc!=SQLITE_OK );
36097   }
36098
36099   /* The Pager.sectorSize variable may have been updated while rolling
36100   ** back a journal created by a process with a different sector size
36101   ** value. Reset it to the correct value for this process.
36102   */
36103   setSectorSize(pPager);
36104   return rc;
36105 }
36106
36107
36108 /*
36109 ** Read the content for page pPg out of the database file and into 
36110 ** pPg->pData. A shared lock or greater must be held on the database
36111 ** file before this function is called.
36112 **
36113 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
36114 ** the value read from the database file.
36115 **
36116 ** If an IO error occurs, then the IO error is returned to the caller.
36117 ** Otherwise, SQLITE_OK is returned.
36118 */
36119 static int readDbPage(PgHdr *pPg){
36120   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
36121   Pgno pgno = pPg->pgno;       /* Page number to read */
36122   int rc = SQLITE_OK;          /* Return code */
36123   int isInWal = 0;             /* True if page is in log file */
36124   int pgsz = pPager->pageSize; /* Number of bytes to read */
36125
36126   assert( pPager->state>=PAGER_SHARED && !MEMDB );
36127   assert( isOpen(pPager->fd) );
36128
36129   if( NEVER(!isOpen(pPager->fd)) ){
36130     assert( pPager->tempFile );
36131     memset(pPg->pData, 0, pPager->pageSize);
36132     return SQLITE_OK;
36133   }
36134
36135   if( pagerUseWal(pPager) ){
36136     /* Try to pull the page from the write-ahead log. */
36137     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
36138   }
36139   if( rc==SQLITE_OK && !isInWal ){
36140     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
36141     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
36142     if( rc==SQLITE_IOERR_SHORT_READ ){
36143       rc = SQLITE_OK;
36144     }
36145   }
36146
36147   if( pgno==1 ){
36148     if( rc ){
36149       /* If the read is unsuccessful, set the dbFileVers[] to something
36150       ** that will never be a valid file version.  dbFileVers[] is a copy
36151       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
36152       ** zero or the size of the database in page. Bytes 32..35 and 35..39
36153       ** should be page numbers which are never 0xffffffff.  So filling
36154       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
36155       **
36156       ** For an encrypted database, the situation is more complex:  bytes
36157       ** 24..39 of the database are white noise.  But the probability of
36158       ** white noising equaling 16 bytes of 0xff is vanishingly small so
36159       ** we should still be ok.
36160       */
36161       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
36162     }else{
36163       u8 *dbFileVers = &((u8*)pPg->pData)[24];
36164       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
36165     }
36166   }
36167   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
36168
36169   PAGER_INCR(sqlite3_pager_readdb_count);
36170   PAGER_INCR(pPager->nRead);
36171   IOTRACE(("PGIN %p %d\n", pPager, pgno));
36172   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
36173                PAGERID(pPager), pgno, pager_pagehash(pPg)));
36174
36175   return rc;
36176 }
36177
36178 #ifndef SQLITE_OMIT_WAL
36179 /*
36180 ** This function is invoked once for each page that has already been 
36181 ** written into the log file when a WAL transaction is rolled back.
36182 ** Parameter iPg is the page number of said page. The pCtx argument 
36183 ** is actually a pointer to the Pager structure.
36184 **
36185 ** If page iPg is present in the cache, and has no outstanding references,
36186 ** it is discarded. Otherwise, if there are one or more outstanding
36187 ** references, the page content is reloaded from the database. If the
36188 ** attempt to reload content from the database is required and fails, 
36189 ** return an SQLite error code. Otherwise, SQLITE_OK.
36190 */
36191 static int pagerUndoCallback(void *pCtx, Pgno iPg){
36192   int rc = SQLITE_OK;
36193   Pager *pPager = (Pager *)pCtx;
36194   PgHdr *pPg;
36195
36196   pPg = sqlite3PagerLookup(pPager, iPg);
36197   if( pPg ){
36198     if( sqlite3PcachePageRefcount(pPg)==1 ){
36199       sqlite3PcacheDrop(pPg);
36200     }else{
36201       rc = readDbPage(pPg);
36202       if( rc==SQLITE_OK ){
36203         pPager->xReiniter(pPg);
36204       }
36205       sqlite3PagerUnref(pPg);
36206     }
36207   }
36208
36209   /* Normally, if a transaction is rolled back, any backup processes are
36210   ** updated as data is copied out of the rollback journal and into the
36211   ** database. This is not generally possible with a WAL database, as
36212   ** rollback involves simply truncating the log file. Therefore, if one
36213   ** or more frames have already been written to the log (and therefore 
36214   ** also copied into the backup databases) as part of this transaction,
36215   ** the backups must be restarted.
36216   */
36217   sqlite3BackupRestart(pPager->pBackup);
36218
36219   return rc;
36220 }
36221
36222 /*
36223 ** This function is called to rollback a transaction on a WAL database.
36224 */
36225 static int pagerRollbackWal(Pager *pPager){
36226   int rc;                         /* Return Code */
36227   PgHdr *pList;                   /* List of dirty pages to revert */
36228
36229   /* For all pages in the cache that are currently dirty or have already
36230   ** been written (but not committed) to the log file, do one of the 
36231   ** following:
36232   **
36233   **   + Discard the cached page (if refcount==0), or
36234   **   + Reload page content from the database (if refcount>0).
36235   */
36236   pPager->dbSize = pPager->dbOrigSize;
36237   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
36238   pList = sqlite3PcacheDirtyList(pPager->pPCache);
36239   while( pList && rc==SQLITE_OK ){
36240     PgHdr *pNext = pList->pDirty;
36241     rc = pagerUndoCallback((void *)pPager, pList->pgno);
36242     pList = pNext;
36243   }
36244
36245   return rc;
36246 }
36247
36248 /*
36249 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
36250 ** the contents of the list of pages headed by pList (connected by pDirty),
36251 ** this function notifies any active backup processes that the pages have
36252 ** changed. 
36253 */ 
36254 static int pagerWalFrames(
36255   Pager *pPager,                  /* Pager object */
36256   PgHdr *pList,                   /* List of frames to log */
36257   Pgno nTruncate,                 /* Database size after this commit */
36258   int isCommit,                   /* True if this is a commit */
36259   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
36260 ){
36261   int rc;                         /* Return code */
36262
36263   assert( pPager->pWal );
36264   rc = sqlite3WalFrames(pPager->pWal, 
36265       pPager->pageSize, pList, nTruncate, isCommit, sync_flags
36266   );
36267   if( rc==SQLITE_OK && pPager->pBackup ){
36268     PgHdr *p;
36269     for(p=pList; p; p=p->pDirty){
36270       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
36271     }
36272   }
36273   return rc;
36274 }
36275
36276 /*
36277 ** Begin a read transaction on the WAL.
36278 **
36279 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
36280 ** makes a snapshot of the database at the current point in time and preserves
36281 ** that snapshot for use by the reader in spite of concurrently changes by
36282 ** other writers or checkpointers.
36283 */
36284 static int pagerBeginReadTransaction(Pager *pPager){
36285   int rc;                         /* Return code */
36286   int changed = 0;                /* True if cache must be reset */
36287
36288   assert( pagerUseWal(pPager) );
36289
36290   /* sqlite3WalEndReadTransaction() was not called for the previous
36291   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
36292   ** are in locking_mode=NORMAL and EndRead() was previously called,
36293   ** the duplicate call is harmless.
36294   */
36295   sqlite3WalEndReadTransaction(pPager->pWal);
36296
36297   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
36298   if( rc==SQLITE_OK ){
36299     int dummy;
36300     if( changed ){
36301       pager_reset(pPager);
36302       assert( pPager->errCode || pPager->dbSizeValid==0 );
36303     }
36304     rc = sqlite3PagerPagecount(pPager, &dummy);
36305   }
36306   pPager->state = PAGER_SHARED;
36307
36308   return rc;
36309 }
36310
36311 /*
36312 ** Check if the *-wal file that corresponds to the database opened by pPager
36313 ** exists if the database is not empy, or verify that the *-wal file does
36314 ** not exist (by deleting it) if the database file is empty.
36315 **
36316 ** If the database is not empty and the *-wal file exists, open the pager
36317 ** in WAL mode.  If the database is empty or if no *-wal file exists and
36318 ** if no error occurs, make sure Pager.journalMode is not set to
36319 ** PAGER_JOURNALMODE_WAL.
36320 **
36321 ** Return SQLITE_OK or an error code.
36322 **
36323 ** If the WAL file is opened, also open a snapshot (read transaction).
36324 **
36325 ** The caller must hold a SHARED lock on the database file to call this
36326 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
36327 ** a WAL on a none-empty database, this ensures there is no race condition 
36328 ** between the xAccess() below and an xDelete() being executed by some 
36329 ** other connection.
36330 */
36331 static int pagerOpenWalIfPresent(Pager *pPager){
36332   int rc = SQLITE_OK;
36333   if( !pPager->tempFile ){
36334     int isWal;                    /* True if WAL file exists */
36335     int nPage;                    /* Size of the database file */
36336     assert( pPager->state>=SHARED_LOCK );
36337     rc = sqlite3PagerPagecount(pPager, &nPage);
36338     if( rc ) return rc;
36339     if( nPage==0 ){
36340       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
36341       isWal = 0;
36342     }else{
36343       rc = sqlite3OsAccess(
36344           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
36345       );
36346     }
36347     if( rc==SQLITE_OK ){
36348       if( isWal ){
36349         pager_reset(pPager);
36350         rc = sqlite3PagerOpenWal(pPager, 0);
36351         if( rc==SQLITE_OK ){
36352           rc = pagerBeginReadTransaction(pPager);
36353         }
36354       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
36355         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
36356       }
36357     }
36358   }
36359   return rc;
36360 }
36361 #endif
36362
36363 /*
36364 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
36365 ** the entire master journal file. The case pSavepoint==NULL occurs when 
36366 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
36367 ** savepoint.
36368 **
36369 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
36370 ** being rolled back), then the rollback consists of up to three stages,
36371 ** performed in the order specified:
36372 **
36373 **   * Pages are played back from the main journal starting at byte
36374 **     offset PagerSavepoint.iOffset and continuing to 
36375 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
36376 **     file if PagerSavepoint.iHdrOffset is zero.
36377 **
36378 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
36379 **     back starting from the journal header immediately following 
36380 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
36381 **
36382 **   * Pages are then played back from the sub-journal file, starting
36383 **     with the PagerSavepoint.iSubRec and continuing to the end of
36384 **     the journal file.
36385 **
36386 ** Throughout the rollback process, each time a page is rolled back, the
36387 ** corresponding bit is set in a bitvec structure (variable pDone in the
36388 ** implementation below). This is used to ensure that a page is only
36389 ** rolled back the first time it is encountered in either journal.
36390 **
36391 ** If pSavepoint is NULL, then pages are only played back from the main
36392 ** journal file. There is no need for a bitvec in this case.
36393 **
36394 ** In either case, before playback commences the Pager.dbSize variable
36395 ** is reset to the value that it held at the start of the savepoint 
36396 ** (or transaction). No page with a page-number greater than this value
36397 ** is played back. If one is encountered it is simply skipped.
36398 */
36399 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
36400   i64 szJ;                 /* Effective size of the main journal */
36401   i64 iHdrOff;             /* End of first segment of main-journal records */
36402   int rc = SQLITE_OK;      /* Return code */
36403   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
36404
36405   assert( pPager->state>=PAGER_SHARED );
36406
36407   /* Allocate a bitvec to use to store the set of pages rolled back */
36408   if( pSavepoint ){
36409     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
36410     if( !pDone ){
36411       return SQLITE_NOMEM;
36412     }
36413   }
36414
36415   /* Set the database size back to the value it was before the savepoint 
36416   ** being reverted was opened.
36417   */
36418   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
36419   pPager->changeCountDone = pPager->tempFile;
36420
36421   if( !pSavepoint && pagerUseWal(pPager) ){
36422     return pagerRollbackWal(pPager);
36423   }
36424
36425   /* Use pPager->journalOff as the effective size of the main rollback
36426   ** journal.  The actual file might be larger than this in
36427   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
36428   ** past pPager->journalOff is off-limits to us.
36429   */
36430   szJ = pPager->journalOff;
36431   assert( pagerUseWal(pPager)==0 || szJ==0 );
36432
36433   /* Begin by rolling back records from the main journal starting at
36434   ** PagerSavepoint.iOffset and continuing to the next journal header.
36435   ** There might be records in the main journal that have a page number
36436   ** greater than the current database size (pPager->dbSize) but those
36437   ** will be skipped automatically.  Pages are added to pDone as they
36438   ** are played back.
36439   */
36440   if( pSavepoint && !pagerUseWal(pPager) ){
36441     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
36442     pPager->journalOff = pSavepoint->iOffset;
36443     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
36444       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36445     }
36446     assert( rc!=SQLITE_DONE );
36447   }else{
36448     pPager->journalOff = 0;
36449   }
36450
36451   /* Continue rolling back records out of the main journal starting at
36452   ** the first journal header seen and continuing until the effective end
36453   ** of the main journal file.  Continue to skip out-of-range pages and
36454   ** continue adding pages rolled back to pDone.
36455   */
36456   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
36457     u32 ii;            /* Loop counter */
36458     u32 nJRec = 0;     /* Number of Journal Records */
36459     u32 dummy;
36460     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
36461     assert( rc!=SQLITE_DONE );
36462
36463     /*
36464     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
36465     ** test is related to ticket #2565.  See the discussion in the
36466     ** pager_playback() function for additional information.
36467     */
36468     if( nJRec==0 
36469      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
36470     ){
36471       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
36472     }
36473     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
36474       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36475     }
36476     assert( rc!=SQLITE_DONE );
36477   }
36478   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
36479
36480   /* Finally,  rollback pages from the sub-journal.  Page that were
36481   ** previously rolled back out of the main journal (and are hence in pDone)
36482   ** will be skipped.  Out-of-range pages are also skipped.
36483   */
36484   if( pSavepoint ){
36485     u32 ii;            /* Loop counter */
36486     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
36487
36488     if( pagerUseWal(pPager) ){
36489       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
36490     }
36491     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
36492       assert( offset==ii*(4+pPager->pageSize) );
36493       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
36494     }
36495     assert( rc!=SQLITE_DONE );
36496   }
36497
36498   sqlite3BitvecDestroy(pDone);
36499   if( rc==SQLITE_OK ){
36500     pPager->journalOff = szJ;
36501   }
36502
36503   return rc;
36504 }
36505
36506 /*
36507 ** Change the maximum number of in-memory pages that are allowed.
36508 */
36509 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
36510   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
36511 }
36512
36513 /*
36514 ** Adjust the robustness of the database to damage due to OS crashes
36515 ** or power failures by changing the number of syncs()s when writing
36516 ** the rollback journal.  There are three levels:
36517 **
36518 **    OFF       sqlite3OsSync() is never called.  This is the default
36519 **              for temporary and transient files.
36520 **
36521 **    NORMAL    The journal is synced once before writes begin on the
36522 **              database.  This is normally adequate protection, but
36523 **              it is theoretically possible, though very unlikely,
36524 **              that an inopertune power failure could leave the journal
36525 **              in a state which would cause damage to the database
36526 **              when it is rolled back.
36527 **
36528 **    FULL      The journal is synced twice before writes begin on the
36529 **              database (with some additional information - the nRec field
36530 **              of the journal header - being written in between the two
36531 **              syncs).  If we assume that writing a
36532 **              single disk sector is atomic, then this mode provides
36533 **              assurance that the journal will not be corrupted to the
36534 **              point of causing damage to the database during rollback.
36535 **
36536 ** Numeric values associated with these states are OFF==1, NORMAL=2,
36537 ** and FULL=3.
36538 */
36539 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
36540 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
36541   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
36542   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
36543   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
36544   if( pPager->noSync ) pPager->needSync = 0;
36545 }
36546 #endif
36547
36548 /*
36549 ** The following global variable is incremented whenever the library
36550 ** attempts to open a temporary file.  This information is used for
36551 ** testing and analysis only.  
36552 */
36553 #ifdef SQLITE_TEST
36554 SQLITE_API int sqlite3_opentemp_count = 0;
36555 #endif
36556
36557 /*
36558 ** Open a temporary file.
36559 **
36560 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
36561 ** or some other error code if we fail. The OS will automatically 
36562 ** delete the temporary file when it is closed.
36563 **
36564 ** The flags passed to the VFS layer xOpen() call are those specified
36565 ** by parameter vfsFlags ORed with the following:
36566 **
36567 **     SQLITE_OPEN_READWRITE
36568 **     SQLITE_OPEN_CREATE
36569 **     SQLITE_OPEN_EXCLUSIVE
36570 **     SQLITE_OPEN_DELETEONCLOSE
36571 */
36572 static int pagerOpentemp(
36573   Pager *pPager,        /* The pager object */
36574   sqlite3_file *pFile,  /* Write the file descriptor here */
36575   int vfsFlags          /* Flags passed through to the VFS */
36576 ){
36577   int rc;               /* Return code */
36578
36579 #ifdef SQLITE_TEST
36580   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
36581 #endif
36582
36583   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
36584             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
36585   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
36586   assert( rc!=SQLITE_OK || isOpen(pFile) );
36587   return rc;
36588 }
36589
36590 /*
36591 ** Set the busy handler function.
36592 **
36593 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
36594 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
36595 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
36596 ** lock. It does *not* invoke the busy handler when upgrading from
36597 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
36598 ** (which occurs during hot-journal rollback). Summary:
36599 **
36600 **   Transition                        | Invokes xBusyHandler
36601 **   --------------------------------------------------------
36602 **   NO_LOCK       -> SHARED_LOCK      | Yes
36603 **   SHARED_LOCK   -> RESERVED_LOCK    | No
36604 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
36605 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
36606 **
36607 ** If the busy-handler callback returns non-zero, the lock is 
36608 ** retried. If it returns zero, then the SQLITE_BUSY error is
36609 ** returned to the caller of the pager API function.
36610 */
36611 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
36612   Pager *pPager,                       /* Pager object */
36613   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
36614   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
36615 ){  
36616   pPager->xBusyHandler = xBusyHandler;
36617   pPager->pBusyHandlerArg = pBusyHandlerArg;
36618 }
36619
36620 /*
36621 ** Change the page size used by the Pager object. The new page size 
36622 ** is passed in *pPageSize.
36623 **
36624 ** If the pager is in the error state when this function is called, it
36625 ** is a no-op. The value returned is the error state error code (i.e. 
36626 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
36627 **
36628 ** Otherwise, if all of the following are true:
36629 **
36630 **   * the new page size (value of *pPageSize) is valid (a power 
36631 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
36632 **
36633 **   * there are no outstanding page references, and
36634 **
36635 **   * the database is either not an in-memory database or it is
36636 **     an in-memory database that currently consists of zero pages.
36637 **
36638 ** then the pager object page size is set to *pPageSize.
36639 **
36640 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
36641 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
36642 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
36643 ** In all other cases, SQLITE_OK is returned.
36644 **
36645 ** If the page size is not changed, either because one of the enumerated
36646 ** conditions above is not true, the pager was in error state when this
36647 ** function was called, or because the memory allocation attempt failed, 
36648 ** then *pPageSize is set to the old, retained page size before returning.
36649 */
36650 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
36651   int rc = pPager->errCode;
36652
36653   if( rc==SQLITE_OK ){
36654     u16 pageSize = *pPageSize;
36655     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
36656     if( (pPager->memDb==0 || pPager->dbSize==0)
36657      && sqlite3PcacheRefCount(pPager->pPCache)==0 
36658      && pageSize && pageSize!=pPager->pageSize 
36659     ){
36660       char *pNew = (char *)sqlite3PageMalloc(pageSize);
36661       if( !pNew ){
36662         rc = SQLITE_NOMEM;
36663       }else{
36664         pager_reset(pPager);
36665         pPager->pageSize = pageSize;
36666         sqlite3PageFree(pPager->pTmpSpace);
36667         pPager->pTmpSpace = pNew;
36668         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
36669       }
36670     }
36671     *pPageSize = (u16)pPager->pageSize;
36672     if( nReserve<0 ) nReserve = pPager->nReserve;
36673     assert( nReserve>=0 && nReserve<1000 );
36674     pPager->nReserve = (i16)nReserve;
36675     pagerReportSize(pPager);
36676   }
36677   return rc;
36678 }
36679
36680 /*
36681 ** Return a pointer to the "temporary page" buffer held internally
36682 ** by the pager.  This is a buffer that is big enough to hold the
36683 ** entire content of a database page.  This buffer is used internally
36684 ** during rollback and will be overwritten whenever a rollback
36685 ** occurs.  But other modules are free to use it too, as long as
36686 ** no rollbacks are happening.
36687 */
36688 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
36689   return pPager->pTmpSpace;
36690 }
36691
36692 /*
36693 ** Attempt to set the maximum database page count if mxPage is positive. 
36694 ** Make no changes if mxPage is zero or negative.  And never reduce the
36695 ** maximum page count below the current size of the database.
36696 **
36697 ** Regardless of mxPage, return the current maximum page count.
36698 */
36699 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
36700   int nPage;
36701   if( mxPage>0 ){
36702     pPager->mxPgno = mxPage;
36703   }
36704   if( pPager->state!=PAGER_UNLOCK ){
36705     sqlite3PagerPagecount(pPager, &nPage);
36706     assert( (int)pPager->mxPgno>=nPage );
36707   }
36708   return pPager->mxPgno;
36709 }
36710
36711 /*
36712 ** The following set of routines are used to disable the simulated
36713 ** I/O error mechanism.  These routines are used to avoid simulated
36714 ** errors in places where we do not care about errors.
36715 **
36716 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
36717 ** and generate no code.
36718 */
36719 #ifdef SQLITE_TEST
36720 SQLITE_API extern int sqlite3_io_error_pending;
36721 SQLITE_API extern int sqlite3_io_error_hit;
36722 static int saved_cnt;
36723 void disable_simulated_io_errors(void){
36724   saved_cnt = sqlite3_io_error_pending;
36725   sqlite3_io_error_pending = -1;
36726 }
36727 void enable_simulated_io_errors(void){
36728   sqlite3_io_error_pending = saved_cnt;
36729 }
36730 #else
36731 # define disable_simulated_io_errors()
36732 # define enable_simulated_io_errors()
36733 #endif
36734
36735 /*
36736 ** Read the first N bytes from the beginning of the file into memory
36737 ** that pDest points to. 
36738 **
36739 ** If the pager was opened on a transient file (zFilename==""), or
36740 ** opened on a file less than N bytes in size, the output buffer is
36741 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
36742 ** function is used to read database headers, and a new transient or
36743 ** zero sized database has a header than consists entirely of zeroes.
36744 **
36745 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
36746 ** the error code is returned to the caller and the contents of the
36747 ** output buffer undefined.
36748 */
36749 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
36750   int rc = SQLITE_OK;
36751   memset(pDest, 0, N);
36752   assert( isOpen(pPager->fd) || pPager->tempFile );
36753
36754   /* This routine is only called by btree immediately after creating
36755   ** the Pager object.  There has not been an opportunity to transition
36756   ** to WAL mode yet.
36757   */
36758   assert( !pagerUseWal(pPager) );
36759
36760   if( isOpen(pPager->fd) ){
36761     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
36762     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
36763     if( rc==SQLITE_IOERR_SHORT_READ ){
36764       rc = SQLITE_OK;
36765     }
36766   }
36767   return rc;
36768 }
36769
36770 /*
36771 ** Return the total number of pages in the database file associated 
36772 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
36773 ** However, if the file is between 1 and <page-size> bytes in size, then 
36774 ** this is considered a 1 page file.
36775 **
36776 ** If the pager is in error state when this function is called, then the
36777 ** error state error code is returned and *pnPage left unchanged. Or,
36778 ** if the file system has to be queried for the size of the file and
36779 ** the query attempt returns an IO error, the IO error code is returned
36780 ** and *pnPage is left unchanged.
36781 **
36782 ** Otherwise, if everything is successful, then SQLITE_OK is returned
36783 ** and *pnPage is set to the number of pages in the database.
36784 */
36785 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
36786   Pgno nPage = 0;           /* Value to return via *pnPage */
36787
36788   /* Determine the number of pages in the file. Store this in nPage. */
36789   if( pPager->dbSizeValid ){
36790     nPage = pPager->dbSize;
36791   }else{
36792     int rc;                 /* Error returned by OsFileSize() */
36793     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
36794
36795     if( pagerUseWal(pPager) && pPager->state!=PAGER_UNLOCK ){
36796       sqlite3WalDbsize(pPager->pWal, &nPage);
36797     }
36798
36799     if( nPage==0 ){
36800       assert( isOpen(pPager->fd) || pPager->tempFile );
36801       if( isOpen(pPager->fd) ){
36802         if( SQLITE_OK!=(rc = sqlite3OsFileSize(pPager->fd, &n)) ){
36803           pager_error(pPager, rc);
36804           return rc;
36805         }
36806       }
36807       if( n>0 && n<pPager->pageSize ){
36808         nPage = 1;
36809       }else{
36810         nPage = (Pgno)(n / pPager->pageSize);
36811       }
36812     }
36813     if( pPager->state!=PAGER_UNLOCK ){
36814       pPager->dbSize = nPage;
36815       pPager->dbFileSize = nPage;
36816       pPager->dbSizeValid = 1;
36817     }
36818   }
36819
36820   /* If the current number of pages in the file is greater than the 
36821   ** configured maximum pager number, increase the allowed limit so
36822   ** that the file can be read.
36823   */
36824   if( nPage>pPager->mxPgno ){
36825     pPager->mxPgno = (Pgno)nPage;
36826   }
36827
36828   /* Set the output variable and return SQLITE_OK */
36829   *pnPage = nPage;
36830   return SQLITE_OK;
36831 }
36832
36833
36834 /*
36835 ** Try to obtain a lock of type locktype on the database file. If
36836 ** a similar or greater lock is already held, this function is a no-op
36837 ** (returning SQLITE_OK immediately).
36838 **
36839 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
36840 ** the busy callback if the lock is currently not available. Repeat 
36841 ** until the busy callback returns false or until the attempt to 
36842 ** obtain the lock succeeds.
36843 **
36844 ** Return SQLITE_OK on success and an error code if we cannot obtain
36845 ** the lock. If the lock is obtained successfully, set the Pager.state 
36846 ** variable to locktype before returning.
36847 */
36848 static int pager_wait_on_lock(Pager *pPager, int locktype){
36849   int rc;                              /* Return code */
36850
36851   /* The OS lock values must be the same as the Pager lock values */
36852   assert( PAGER_SHARED==SHARED_LOCK );
36853   assert( PAGER_RESERVED==RESERVED_LOCK );
36854   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
36855
36856   /* If the file is currently unlocked then the size must be unknown. It
36857   ** must not have been modified at this point.
36858   */
36859   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
36860   assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
36861
36862   /* Check that this is either a no-op (because the requested lock is 
36863   ** already held, or one of the transistions that the busy-handler
36864   ** may be invoked during, according to the comment above
36865   ** sqlite3PagerSetBusyhandler().
36866   */
36867   assert( (pPager->state>=locktype)
36868        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
36869        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
36870   );
36871
36872   if( pPager->state>=locktype ){
36873     rc = SQLITE_OK;
36874   }else{
36875     do {
36876       rc = sqlite3OsLock(pPager->fd, locktype);
36877     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
36878     if( rc==SQLITE_OK ){
36879       pPager->state = (u8)locktype;
36880       IOTRACE(("LOCK %p %d\n", pPager, locktype))
36881     }
36882   }
36883   return rc;
36884 }
36885
36886 /*
36887 ** Function assertTruncateConstraint(pPager) checks that one of the 
36888 ** following is true for all dirty pages currently in the page-cache:
36889 **
36890 **   a) The page number is less than or equal to the size of the 
36891 **      current database image, in pages, OR
36892 **
36893 **   b) if the page content were written at this time, it would not
36894 **      be necessary to write the current content out to the sub-journal
36895 **      (as determined by function subjRequiresPage()).
36896 **
36897 ** If the condition asserted by this function were not true, and the
36898 ** dirty page were to be discarded from the cache via the pagerStress()
36899 ** routine, pagerStress() would not write the current page content to
36900 ** the database file. If a savepoint transaction were rolled back after
36901 ** this happened, the correct behaviour would be to restore the current
36902 ** content of the page. However, since this content is not present in either
36903 ** the database file or the portion of the rollback journal and 
36904 ** sub-journal rolled back the content could not be restored and the
36905 ** database image would become corrupt. It is therefore fortunate that 
36906 ** this circumstance cannot arise.
36907 */
36908 #if defined(SQLITE_DEBUG)
36909 static void assertTruncateConstraintCb(PgHdr *pPg){
36910   assert( pPg->flags&PGHDR_DIRTY );
36911   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
36912 }
36913 static void assertTruncateConstraint(Pager *pPager){
36914   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
36915 }
36916 #else
36917 # define assertTruncateConstraint(pPager)
36918 #endif
36919
36920 /*
36921 ** Truncate the in-memory database file image to nPage pages. This 
36922 ** function does not actually modify the database file on disk. It 
36923 ** just sets the internal state of the pager object so that the 
36924 ** truncation will be done when the current transaction is committed.
36925 */
36926 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
36927   assert( pPager->dbSizeValid );
36928   assert( pPager->dbSize>=nPage );
36929   assert( pPager->state>=PAGER_RESERVED );
36930   pPager->dbSize = nPage;
36931   assertTruncateConstraint(pPager);
36932 }
36933
36934
36935 /*
36936 ** This function is called before attempting a hot-journal rollback. It
36937 ** syncs the journal file to disk, then sets pPager->journalHdr to the
36938 ** size of the journal file so that the pager_playback() routine knows
36939 ** that the entire journal file has been synced.
36940 **
36941 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
36942 ** that if a power-failure occurs during the rollback, the process that
36943 ** attempts rollback following system recovery sees the same journal
36944 ** content as this process.
36945 **
36946 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
36947 ** an SQLite error code.
36948 */
36949 static int pagerSyncHotJournal(Pager *pPager){
36950   int rc = SQLITE_OK;
36951   if( !pPager->noSync ){
36952     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
36953   }
36954   if( rc==SQLITE_OK ){
36955     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
36956   }
36957   return rc;
36958 }
36959
36960 /*
36961 ** Shutdown the page cache.  Free all memory and close all files.
36962 **
36963 ** If a transaction was in progress when this routine is called, that
36964 ** transaction is rolled back.  All outstanding pages are invalidated
36965 ** and their memory is freed.  Any attempt to use a page associated
36966 ** with this page cache after this function returns will likely
36967 ** result in a coredump.
36968 **
36969 ** This function always succeeds. If a transaction is active an attempt
36970 ** is made to roll it back. If an error occurs during the rollback 
36971 ** a hot journal may be left in the filesystem but no error is returned
36972 ** to the caller.
36973 */
36974 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
36975   u8 *pTmp = (u8 *)pPager->pTmpSpace;
36976
36977   disable_simulated_io_errors();
36978   sqlite3BeginBenignMalloc();
36979   pPager->errCode = 0;
36980   pPager->exclusiveMode = 0;
36981 #ifndef SQLITE_OMIT_WAL
36982   sqlite3WalClose(pPager->pWal,
36983     (pPager->noSync ? 0 : pPager->sync_flags), 
36984     pPager->pageSize, pTmp
36985   );
36986   pPager->pWal = 0;
36987 #endif
36988   pager_reset(pPager);
36989   if( MEMDB ){
36990     pager_unlock(pPager);
36991   }else{
36992     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
36993     ** call which may be made from within pagerUnlockAndRollback(). If it
36994     ** is not -1, then the unsynced portion of an open journal file may
36995     ** be played back into the database. If a power failure occurs while
36996     ** this is happening, the database may become corrupt.
36997     */
36998     if( isOpen(pPager->jfd) ){
36999       pPager->errCode = pagerSyncHotJournal(pPager);
37000     }
37001     pagerUnlockAndRollback(pPager);
37002   }
37003   sqlite3EndBenignMalloc();
37004   enable_simulated_io_errors();
37005   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
37006   IOTRACE(("CLOSE %p\n", pPager))
37007   sqlite3OsClose(pPager->jfd);
37008   sqlite3OsClose(pPager->fd);
37009   sqlite3PageFree(pTmp);
37010   sqlite3PcacheClose(pPager->pPCache);
37011
37012 #ifdef SQLITE_HAS_CODEC
37013   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
37014 #endif
37015
37016   assert( !pPager->aSavepoint && !pPager->pInJournal );
37017   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
37018
37019   sqlite3_free(pPager);
37020   return SQLITE_OK;
37021 }
37022
37023 #if !defined(NDEBUG) || defined(SQLITE_TEST)
37024 /*
37025 ** Return the page number for page pPg.
37026 */
37027 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
37028   return pPg->pgno;
37029 }
37030 #endif
37031
37032 /*
37033 ** Increment the reference count for page pPg.
37034 */
37035 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
37036   sqlite3PcacheRef(pPg);
37037 }
37038
37039 /*
37040 ** Sync the journal. In other words, make sure all the pages that have
37041 ** been written to the journal have actually reached the surface of the
37042 ** disk and can be restored in the event of a hot-journal rollback.
37043 **
37044 ** If the Pager.needSync flag is not set, then this function is a
37045 ** no-op. Otherwise, the actions required depend on the journal-mode
37046 ** and the device characteristics of the the file-system, as follows:
37047 **
37048 **   * If the journal file is an in-memory journal file, no action need
37049 **     be taken.
37050 **
37051 **   * Otherwise, if the device does not support the SAFE_APPEND property,
37052 **     then the nRec field of the most recently written journal header
37053 **     is updated to contain the number of journal records that have
37054 **     been written following it. If the pager is operating in full-sync
37055 **     mode, then the journal file is synced before this field is updated.
37056 **
37057 **   * If the device does not support the SEQUENTIAL property, then 
37058 **     journal file is synced.
37059 **
37060 ** Or, in pseudo-code:
37061 **
37062 **   if( NOT <in-memory journal> ){
37063 **     if( NOT SAFE_APPEND ){
37064 **       if( <full-sync mode> ) xSync(<journal file>);
37065 **       <update nRec field>
37066 **     } 
37067 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
37068 **   }
37069 **
37070 ** The Pager.needSync flag is never be set for temporary files, or any
37071 ** file operating in no-sync mode (Pager.noSync set to non-zero).
37072 **
37073 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
37074 ** page currently held in memory before returning SQLITE_OK. If an IO
37075 ** error is encountered, then the IO error code is returned to the caller.
37076 */
37077 static int syncJournal(Pager *pPager){
37078   if( pPager->needSync ){
37079     assert( !pPager->tempFile );
37080     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
37081       int rc;                              /* Return code */
37082       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37083       assert( isOpen(pPager->jfd) );
37084
37085       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
37086         /* This block deals with an obscure problem. If the last connection
37087         ** that wrote to this database was operating in persistent-journal
37088         ** mode, then the journal file may at this point actually be larger
37089         ** than Pager.journalOff bytes. If the next thing in the journal
37090         ** file happens to be a journal-header (written as part of the
37091         ** previous connection's transaction), and a crash or power-failure 
37092         ** occurs after nRec is updated but before this connection writes 
37093         ** anything else to the journal file (or commits/rolls back its 
37094         ** transaction), then SQLite may become confused when doing the 
37095         ** hot-journal rollback following recovery. It may roll back all
37096         ** of this connections data, then proceed to rolling back the old,
37097         ** out-of-date data that follows it. Database corruption.
37098         **
37099         ** To work around this, if the journal file does appear to contain
37100         ** a valid header following Pager.journalOff, then write a 0x00
37101         ** byte to the start of it to prevent it from being recognized.
37102         **
37103         ** Variable iNextHdrOffset is set to the offset at which this
37104         ** problematic header will occur, if it exists. aMagic is used 
37105         ** as a temporary buffer to inspect the first couple of bytes of
37106         ** the potential journal header.
37107         */
37108         i64 iNextHdrOffset;
37109         u8 aMagic[8];
37110         u8 zHeader[sizeof(aJournalMagic)+4];
37111
37112         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37113         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
37114
37115         iNextHdrOffset = journalHdrOffset(pPager);
37116         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
37117         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
37118           static const u8 zerobyte = 0;
37119           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
37120         }
37121         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
37122           return rc;
37123         }
37124
37125         /* Write the nRec value into the journal file header. If in
37126         ** full-synchronous mode, sync the journal first. This ensures that
37127         ** all data has really hit the disk before nRec is updated to mark
37128         ** it as a candidate for rollback.
37129         **
37130         ** This is not required if the persistent media supports the
37131         ** SAFE_APPEND property. Because in this case it is not possible 
37132         ** for garbage data to be appended to the file, the nRec field
37133         ** is populated with 0xFFFFFFFF when the journal header is written
37134         ** and never needs to be updated.
37135         */
37136         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37137           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37138           IOTRACE(("JSYNC %p\n", pPager))
37139           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
37140           if( rc!=SQLITE_OK ) return rc;
37141         }
37142         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
37143         rc = sqlite3OsWrite(
37144             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
37145         );
37146         if( rc!=SQLITE_OK ) return rc;
37147       }
37148       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37149         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37150         IOTRACE(("JSYNC %p\n", pPager))
37151         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
37152           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
37153         );
37154         if( rc!=SQLITE_OK ) return rc;
37155       }
37156     }
37157
37158     /* The journal file was just successfully synced. Set Pager.needSync 
37159     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
37160     */
37161     pPager->needSync = 0;
37162     pPager->journalStarted = 1;
37163     pPager->journalHdr = pPager->journalOff;
37164     sqlite3PcacheClearSyncFlags(pPager->pPCache);
37165   }
37166
37167   return SQLITE_OK;
37168 }
37169
37170 /*
37171 ** The argument is the first in a linked list of dirty pages connected
37172 ** by the PgHdr.pDirty pointer. This function writes each one of the
37173 ** in-memory pages in the list to the database file. The argument may
37174 ** be NULL, representing an empty list. In this case this function is
37175 ** a no-op.
37176 **
37177 ** The pager must hold at least a RESERVED lock when this function
37178 ** is called. Before writing anything to the database file, this lock
37179 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
37180 ** SQLITE_BUSY is returned and no data is written to the database file.
37181 ** 
37182 ** If the pager is a temp-file pager and the actual file-system file
37183 ** is not yet open, it is created and opened before any data is 
37184 ** written out.
37185 **
37186 ** Once the lock has been upgraded and, if necessary, the file opened,
37187 ** the pages are written out to the database file in list order. Writing
37188 ** a page is skipped if it meets either of the following criteria:
37189 **
37190 **   * The page number is greater than Pager.dbSize, or
37191 **   * The PGHDR_DONT_WRITE flag is set on the page.
37192 **
37193 ** If writing out a page causes the database file to grow, Pager.dbFileSize
37194 ** is updated accordingly. If page 1 is written out, then the value cached
37195 ** in Pager.dbFileVers[] is updated to match the new value stored in
37196 ** the database file.
37197 **
37198 ** If everything is successful, SQLITE_OK is returned. If an IO error 
37199 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
37200 ** be obtained, SQLITE_BUSY is returned.
37201 */
37202 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
37203   int rc;                              /* Return code */
37204
37205   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
37206   ** database file. If there is already an EXCLUSIVE lock, the following
37207   ** call is a no-op.
37208   **
37209   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
37210   ** through an intermediate state PENDING.   A PENDING lock prevents new
37211   ** readers from attaching to the database but is unsufficient for us to
37212   ** write.  The idea of a PENDING lock is to prevent new readers from
37213   ** coming in while we wait for existing readers to clear.
37214   **
37215   ** While the pager is in the RESERVED state, the original database file
37216   ** is unchanged and we can rollback without having to playback the
37217   ** journal into the original database file.  Once we transition to
37218   ** EXCLUSIVE, it means the database file has been changed and any rollback
37219   ** will require a journal playback.
37220   */
37221   assert( !pagerUseWal(pPager) );
37222   assert( pPager->state>=PAGER_RESERVED );
37223   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
37224
37225   /* If the file is a temp-file has not yet been opened, open it now. It
37226   ** is not possible for rc to be other than SQLITE_OK if this branch
37227   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
37228   */
37229   if( !isOpen(pPager->fd) ){
37230     assert( pPager->tempFile && rc==SQLITE_OK );
37231     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
37232   }
37233
37234   /* Before the first write, give the VFS a hint of what the final
37235   ** file size will be.
37236   */
37237   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
37238   if( rc==SQLITE_OK && pPager->dbSize>(pPager->dbOrigSize+1) ){
37239     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
37240     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
37241   }
37242
37243   while( rc==SQLITE_OK && pList ){
37244     Pgno pgno = pList->pgno;
37245
37246     /* If there are dirty pages in the page cache with page numbers greater
37247     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
37248     ** make the file smaller (presumably by auto-vacuum code). Do not write
37249     ** any such pages to the file.
37250     **
37251     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
37252     ** set (set by sqlite3PagerDontWrite()).
37253     */
37254     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
37255       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
37256       char *pData;                                   /* Data to write */    
37257
37258       /* Encode the database */
37259       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
37260
37261       /* Write out the page data. */
37262       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
37263
37264       /* If page 1 was just written, update Pager.dbFileVers to match
37265       ** the value now stored in the database file. If writing this 
37266       ** page caused the database file to grow, update dbFileSize. 
37267       */
37268       if( pgno==1 ){
37269         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
37270       }
37271       if( pgno>pPager->dbFileSize ){
37272         pPager->dbFileSize = pgno;
37273       }
37274
37275       /* Update any backup objects copying the contents of this pager. */
37276       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
37277
37278       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
37279                    PAGERID(pPager), pgno, pager_pagehash(pList)));
37280       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
37281       PAGER_INCR(sqlite3_pager_writedb_count);
37282       PAGER_INCR(pPager->nWrite);
37283     }else{
37284       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
37285     }
37286 #ifdef SQLITE_CHECK_PAGES
37287     pList->pageHash = pager_pagehash(pList);
37288 #endif
37289     pList = pList->pDirty;
37290   }
37291
37292   return rc;
37293 }
37294
37295 /*
37296 ** Ensure that the sub-journal file is open. If it is already open, this 
37297 ** function is a no-op.
37298 **
37299 ** SQLITE_OK is returned if everything goes according to plan. An 
37300 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
37301 ** fails.
37302 */
37303 static int openSubJournal(Pager *pPager){
37304   int rc = SQLITE_OK;
37305   if( !isOpen(pPager->sjfd) ){
37306     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
37307       sqlite3MemJournalOpen(pPager->sjfd);
37308     }else{
37309       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
37310     }
37311   }
37312   return rc;
37313 }
37314
37315 /*
37316 ** Append a record of the current state of page pPg to the sub-journal. 
37317 ** It is the callers responsibility to use subjRequiresPage() to check 
37318 ** that it is really required before calling this function.
37319 **
37320 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
37321 ** for all open savepoints before returning.
37322 **
37323 ** This function returns SQLITE_OK if everything is successful, an IO
37324 ** error code if the attempt to write to the sub-journal fails, or 
37325 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
37326 ** bitvec.
37327 */
37328 static int subjournalPage(PgHdr *pPg){
37329   int rc = SQLITE_OK;
37330   Pager *pPager = pPg->pPager;
37331   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
37332
37333     /* Open the sub-journal, if it has not already been opened */
37334     assert( pPager->useJournal );
37335     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
37336     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
37337     assert( pagerUseWal(pPager) 
37338          || pageInJournal(pPg) 
37339          || pPg->pgno>pPager->dbOrigSize 
37340     );
37341     rc = openSubJournal(pPager);
37342
37343     /* If the sub-journal was opened successfully (or was already open),
37344     ** write the journal record into the file.  */
37345     if( rc==SQLITE_OK ){
37346       void *pData = pPg->pData;
37347       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
37348       char *pData2;
37349   
37350       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
37351       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
37352       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
37353       if( rc==SQLITE_OK ){
37354         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
37355       }
37356     }
37357   }
37358   if( rc==SQLITE_OK ){
37359     pPager->nSubRec++;
37360     assert( pPager->nSavepoint>0 );
37361     rc = addToSavepointBitvecs(pPager, pPg->pgno);
37362   }
37363   return rc;
37364 }
37365
37366 /*
37367 ** This function is called by the pcache layer when it has reached some
37368 ** soft memory limit. The first argument is a pointer to a Pager object
37369 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
37370 ** database). The second argument is a reference to a page that is 
37371 ** currently dirty but has no outstanding references. The page
37372 ** is always associated with the Pager object passed as the first 
37373 ** argument.
37374 **
37375 ** The job of this function is to make pPg clean by writing its contents
37376 ** out to the database file, if possible. This may involve syncing the
37377 ** journal file. 
37378 **
37379 ** If successful, sqlite3PcacheMakeClean() is called on the page and
37380 ** SQLITE_OK returned. If an IO error occurs while trying to make the
37381 ** page clean, the IO error code is returned. If the page cannot be
37382 ** made clean for some other reason, but no error occurs, then SQLITE_OK
37383 ** is returned by sqlite3PcacheMakeClean() is not called.
37384 */
37385 static int pagerStress(void *p, PgHdr *pPg){
37386   Pager *pPager = (Pager *)p;
37387   int rc = SQLITE_OK;
37388
37389   assert( pPg->pPager==pPager );
37390   assert( pPg->flags&PGHDR_DIRTY );
37391
37392   /* The doNotSyncSpill flag is set during times when doing a sync of
37393   ** journal (and adding a new header) is not allowed.  This occurs
37394   ** during calls to sqlite3PagerWrite() while trying to journal multiple
37395   ** pages belonging to the same sector.
37396   **
37397   ** The doNotSpill flag inhibits all cache spilling regardless of whether
37398   ** or not a sync is required.  This is set during a rollback.
37399   **
37400   ** Spilling is also inhibited when in an error state.
37401   */
37402   if( pPager->errCode ) return SQLITE_OK;
37403   if( pPager->doNotSpill ) return SQLITE_OK;
37404   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
37405     return SQLITE_OK;
37406   }
37407
37408   pPg->pDirty = 0;
37409   if( pagerUseWal(pPager) ){
37410     /* Write a single frame for this page to the log. */
37411     if( subjRequiresPage(pPg) ){ 
37412       rc = subjournalPage(pPg); 
37413     }
37414     if( rc==SQLITE_OK ){
37415       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
37416     }
37417   }else{
37418   
37419     /* Sync the journal file if required. */
37420     if( pPg->flags&PGHDR_NEED_SYNC ){
37421       assert( !pPager->noSync );
37422       rc = syncJournal(pPager);
37423       if( rc==SQLITE_OK && 
37424         !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
37425         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37426       ){
37427         pPager->nRec = 0;
37428         rc = writeJournalHdr(pPager);
37429       }
37430     }
37431   
37432     /* If the page number of this page is larger than the current size of
37433     ** the database image, it may need to be written to the sub-journal.
37434     ** This is because the call to pager_write_pagelist() below will not
37435     ** actually write data to the file in this case.
37436     **
37437     ** Consider the following sequence of events:
37438     **
37439     **   BEGIN;
37440     **     <journal page X>
37441     **     <modify page X>
37442     **     SAVEPOINT sp;
37443     **       <shrink database file to Y pages>
37444     **       pagerStress(page X)
37445     **     ROLLBACK TO sp;
37446     **
37447     ** If (X>Y), then when pagerStress is called page X will not be written
37448     ** out to the database file, but will be dropped from the cache. Then,
37449     ** following the "ROLLBACK TO sp" statement, reading page X will read
37450     ** data from the database file. This will be the copy of page X as it
37451     ** was when the transaction started, not as it was when "SAVEPOINT sp"
37452     ** was executed.
37453     **
37454     ** The solution is to write the current data for page X into the 
37455     ** sub-journal file now (if it is not already there), so that it will
37456     ** be restored to its current value when the "ROLLBACK TO sp" is 
37457     ** executed.
37458     */
37459     if( NEVER(
37460         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
37461     ) ){
37462       rc = subjournalPage(pPg);
37463     }
37464   
37465     /* Write the contents of the page out to the database file. */
37466     if( rc==SQLITE_OK ){
37467       rc = pager_write_pagelist(pPager, pPg);
37468     }
37469   }
37470
37471   /* Mark the page as clean. */
37472   if( rc==SQLITE_OK ){
37473     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
37474     sqlite3PcacheMakeClean(pPg);
37475   }
37476
37477   return pager_error(pPager, rc);
37478 }
37479
37480
37481 /*
37482 ** Allocate and initialize a new Pager object and put a pointer to it
37483 ** in *ppPager. The pager should eventually be freed by passing it
37484 ** to sqlite3PagerClose().
37485 **
37486 ** The zFilename argument is the path to the database file to open.
37487 ** If zFilename is NULL then a randomly-named temporary file is created
37488 ** and used as the file to be cached. Temporary files are be deleted
37489 ** automatically when they are closed. If zFilename is ":memory:" then 
37490 ** all information is held in cache. It is never written to disk. 
37491 ** This can be used to implement an in-memory database.
37492 **
37493 ** The nExtra parameter specifies the number of bytes of space allocated
37494 ** along with each page reference. This space is available to the user
37495 ** via the sqlite3PagerGetExtra() API.
37496 **
37497 ** The flags argument is used to specify properties that affect the
37498 ** operation of the pager. It should be passed some bitwise combination
37499 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
37500 **
37501 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
37502 ** of the xOpen() method of the supplied VFS when opening files. 
37503 **
37504 ** If the pager object is allocated and the specified file opened 
37505 ** successfully, SQLITE_OK is returned and *ppPager set to point to
37506 ** the new pager object. If an error occurs, *ppPager is set to NULL
37507 ** and error code returned. This function may return SQLITE_NOMEM
37508 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
37509 ** various SQLITE_IO_XXX errors.
37510 */
37511 SQLITE_PRIVATE int sqlite3PagerOpen(
37512   sqlite3_vfs *pVfs,       /* The virtual file system to use */
37513   Pager **ppPager,         /* OUT: Return the Pager structure here */
37514   const char *zFilename,   /* Name of the database file to open */
37515   int nExtra,              /* Extra bytes append to each in-memory page */
37516   int flags,               /* flags controlling this file */
37517   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
37518   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
37519 ){
37520   u8 *pPtr;
37521   Pager *pPager = 0;       /* Pager object to allocate and return */
37522   int rc = SQLITE_OK;      /* Return code */
37523   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
37524   int memDb = 0;           /* True if this is an in-memory file */
37525   int readOnly = 0;        /* True if this is a read-only file */
37526   int journalFileSize;     /* Bytes to allocate for each journal fd */
37527   char *zPathname = 0;     /* Full path to database file */
37528   int nPathname = 0;       /* Number of bytes in zPathname */
37529   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
37530   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
37531   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
37532   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
37533
37534   /* Figure out how much space is required for each journal file-handle
37535   ** (there are two of them, the main journal and the sub-journal). This
37536   ** is the maximum space required for an in-memory journal file handle 
37537   ** and a regular journal file-handle. Note that a "regular journal-handle"
37538   ** may be a wrapper capable of caching the first portion of the journal
37539   ** file in memory to implement the atomic-write optimization (see 
37540   ** source file journal.c).
37541   */
37542   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
37543     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
37544   }else{
37545     journalFileSize = ROUND8(sqlite3MemJournalSize());
37546   }
37547
37548   /* Set the output variable to NULL in case an error occurs. */
37549   *ppPager = 0;
37550
37551   /* Compute and store the full pathname in an allocated buffer pointed
37552   ** to by zPathname, length nPathname. Or, if this is a temporary file,
37553   ** leave both nPathname and zPathname set to 0.
37554   */
37555   if( zFilename && zFilename[0] ){
37556     nPathname = pVfs->mxPathname+1;
37557     zPathname = sqlite3Malloc(nPathname*2);
37558     if( zPathname==0 ){
37559       return SQLITE_NOMEM;
37560     }
37561 #ifndef SQLITE_OMIT_MEMORYDB
37562     if( strcmp(zFilename,":memory:")==0 ){
37563       memDb = 1;
37564       zPathname[0] = 0;
37565     }else
37566 #endif
37567     {
37568       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
37569       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
37570     }
37571
37572     nPathname = sqlite3Strlen30(zPathname);
37573     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
37574       /* This branch is taken when the journal path required by
37575       ** the database being opened will be more than pVfs->mxPathname
37576       ** bytes in length. This means the database cannot be opened,
37577       ** as it will not be possible to open the journal file or even
37578       ** check for a hot-journal before reading.
37579       */
37580       rc = SQLITE_CANTOPEN_BKPT;
37581     }
37582     if( rc!=SQLITE_OK ){
37583       sqlite3_free(zPathname);
37584       return rc;
37585     }
37586   }
37587
37588   /* Allocate memory for the Pager structure, PCache object, the
37589   ** three file descriptors, the database file name and the journal 
37590   ** file name. The layout in memory is as follows:
37591   **
37592   **     Pager object                    (sizeof(Pager) bytes)
37593   **     PCache object                   (sqlite3PcacheSize() bytes)
37594   **     Database file handle            (pVfs->szOsFile bytes)
37595   **     Sub-journal file handle         (journalFileSize bytes)
37596   **     Main journal file handle        (journalFileSize bytes)
37597   **     Database file name              (nPathname+1 bytes)
37598   **     Journal file name               (nPathname+8+1 bytes)
37599   */
37600   pPtr = (u8 *)sqlite3MallocZero(
37601     ROUND8(sizeof(*pPager)) +      /* Pager structure */
37602     ROUND8(pcacheSize) +           /* PCache object */
37603     ROUND8(pVfs->szOsFile) +       /* The main db file */
37604     journalFileSize * 2 +          /* The two journal files */ 
37605     nPathname + 1 +                /* zFilename */
37606     nPathname + 8 + 1              /* zJournal */
37607 #ifndef SQLITE_OMIT_WAL
37608     + nPathname + 4 + 1              /* zWal */
37609 #endif
37610   );
37611   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
37612   if( !pPtr ){
37613     sqlite3_free(zPathname);
37614     return SQLITE_NOMEM;
37615   }
37616   pPager =              (Pager*)(pPtr);
37617   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
37618   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
37619   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
37620   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
37621   pPager->zFilename =    (char*)(pPtr += journalFileSize);
37622   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
37623
37624   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
37625   if( zPathname ){
37626     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
37627     memcpy(pPager->zFilename, zPathname, nPathname);
37628     memcpy(pPager->zJournal, zPathname, nPathname);
37629     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
37630     if( pPager->zFilename[0]==0 ){
37631       pPager->zJournal[0] = 0;
37632     }
37633 #ifndef SQLITE_OMIT_WAL
37634     else{
37635       pPager->zWal = &pPager->zJournal[nPathname+8+1];
37636       memcpy(pPager->zWal, zPathname, nPathname);
37637       memcpy(&pPager->zWal[nPathname], "-wal", 4);
37638     }
37639 #endif
37640     sqlite3_free(zPathname);
37641   }
37642   pPager->pVfs = pVfs;
37643   pPager->vfsFlags = vfsFlags;
37644
37645   /* Open the pager file.
37646   */
37647   if( zFilename && zFilename[0] && !memDb ){
37648     int fout = 0;                    /* VFS flags returned by xOpen() */
37649     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
37650     readOnly = (fout&SQLITE_OPEN_READONLY);
37651
37652     /* If the file was successfully opened for read/write access,
37653     ** choose a default page size in case we have to create the
37654     ** database file. The default page size is the maximum of:
37655     **
37656     **    + SQLITE_DEFAULT_PAGE_SIZE,
37657     **    + The value returned by sqlite3OsSectorSize()
37658     **    + The largest page size that can be written atomically.
37659     */
37660     if( rc==SQLITE_OK && !readOnly ){
37661       setSectorSize(pPager);
37662       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
37663       if( szPageDflt<pPager->sectorSize ){
37664         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
37665           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
37666         }else{
37667           szPageDflt = (u16)pPager->sectorSize;
37668         }
37669       }
37670 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37671       {
37672         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37673         int ii;
37674         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37675         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37676         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
37677         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
37678           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
37679             szPageDflt = ii;
37680           }
37681         }
37682       }
37683 #endif
37684     }
37685   }else{
37686     /* If a temporary file is requested, it is not opened immediately.
37687     ** In this case we accept the default page size and delay actually
37688     ** opening the file until the first call to OsWrite().
37689     **
37690     ** This branch is also run for an in-memory database. An in-memory
37691     ** database is the same as a temp-file that is never written out to
37692     ** disk and uses an in-memory rollback journal.
37693     */ 
37694     tempFile = 1;
37695     pPager->state = PAGER_EXCLUSIVE;
37696     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
37697   }
37698
37699   /* The following call to PagerSetPagesize() serves to set the value of 
37700   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
37701   */
37702   if( rc==SQLITE_OK ){
37703     assert( pPager->memDb==0 );
37704     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
37705     testcase( rc!=SQLITE_OK );
37706   }
37707
37708   /* If an error occurred in either of the blocks above, free the 
37709   ** Pager structure and close the file.
37710   */
37711   if( rc!=SQLITE_OK ){
37712     assert( !pPager->pTmpSpace );
37713     sqlite3OsClose(pPager->fd);
37714     sqlite3_free(pPager);
37715     return rc;
37716   }
37717
37718   /* Initialize the PCache object. */
37719   assert( nExtra<1000 );
37720   nExtra = ROUND8(nExtra);
37721   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
37722                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
37723
37724   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
37725   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
37726
37727   pPager->useJournal = (u8)useJournal;
37728   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
37729   /* pPager->stmtOpen = 0; */
37730   /* pPager->stmtInUse = 0; */
37731   /* pPager->nRef = 0; */
37732   pPager->dbSizeValid = (u8)memDb;
37733   /* pPager->stmtSize = 0; */
37734   /* pPager->stmtJSize = 0; */
37735   /* pPager->nPage = 0; */
37736   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
37737   /* pPager->state = PAGER_UNLOCK; */
37738   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
37739   /* pPager->errMask = 0; */
37740   pPager->tempFile = (u8)tempFile;
37741   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
37742           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
37743   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
37744   pPager->exclusiveMode = (u8)tempFile; 
37745   pPager->changeCountDone = pPager->tempFile;
37746   pPager->memDb = (u8)memDb;
37747   pPager->readOnly = (u8)readOnly;
37748   /* pPager->needSync = 0; */
37749   assert( useJournal || pPager->tempFile );
37750   pPager->noSync = pPager->tempFile;
37751   pPager->fullSync = pPager->noSync ?0:1;
37752   pPager->sync_flags = SQLITE_SYNC_NORMAL;
37753   /* pPager->pFirst = 0; */
37754   /* pPager->pFirstSynced = 0; */
37755   /* pPager->pLast = 0; */
37756   pPager->nExtra = (u16)nExtra;
37757   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
37758   assert( isOpen(pPager->fd) || tempFile );
37759   setSectorSize(pPager);
37760   if( !useJournal ){
37761     pPager->journalMode = PAGER_JOURNALMODE_OFF;
37762   }else if( memDb ){
37763     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
37764   }
37765   /* pPager->xBusyHandler = 0; */
37766   /* pPager->pBusyHandlerArg = 0; */
37767   pPager->xReiniter = xReinit;
37768   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
37769
37770   *ppPager = pPager;
37771   return SQLITE_OK;
37772 }
37773
37774
37775
37776 /*
37777 ** This function is called after transitioning from PAGER_UNLOCK to
37778 ** PAGER_SHARED state. It tests if there is a hot journal present in
37779 ** the file-system for the given pager. A hot journal is one that 
37780 ** needs to be played back. According to this function, a hot-journal
37781 ** file exists if the following criteria are met:
37782 **
37783 **   * The journal file exists in the file system, and
37784 **   * No process holds a RESERVED or greater lock on the database file, and
37785 **   * The database file itself is greater than 0 bytes in size, and
37786 **   * The first byte of the journal file exists and is not 0x00.
37787 **
37788 ** If the current size of the database file is 0 but a journal file
37789 ** exists, that is probably an old journal left over from a prior
37790 ** database with the same name. In this case the journal file is
37791 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
37792 ** is returned.
37793 **
37794 ** This routine does not check if there is a master journal filename
37795 ** at the end of the file. If there is, and that master journal file
37796 ** does not exist, then the journal file is not really hot. In this
37797 ** case this routine will return a false-positive. The pager_playback()
37798 ** routine will discover that the journal file is not really hot and 
37799 ** will not roll it back. 
37800 **
37801 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
37802 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
37803 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
37804 ** to determine whether or not a hot-journal file exists, the IO error
37805 ** code is returned and the value of *pExists is undefined.
37806 */
37807 static int hasHotJournal(Pager *pPager, int *pExists){
37808   sqlite3_vfs * const pVfs = pPager->pVfs;
37809   int rc = SQLITE_OK;           /* Return code */
37810   int exists = 1;               /* True if a journal file is present */
37811   int jrnlOpen = !!isOpen(pPager->jfd);
37812
37813   assert( pPager!=0 );
37814   assert( pPager->useJournal );
37815   assert( isOpen(pPager->fd) );
37816   assert( pPager->state <= PAGER_SHARED );
37817   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
37818     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
37819   ));
37820
37821   *pExists = 0;
37822   if( !jrnlOpen ){
37823     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
37824   }
37825   if( rc==SQLITE_OK && exists ){
37826     int locked;                 /* True if some process holds a RESERVED lock */
37827
37828     /* Race condition here:  Another process might have been holding the
37829     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
37830     ** call above, but then delete the journal and drop the lock before
37831     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
37832     ** is the case, this routine might think there is a hot journal when
37833     ** in fact there is none.  This results in a false-positive which will
37834     ** be dealt with by the playback routine.  Ticket #3883.
37835     */
37836     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
37837     if( rc==SQLITE_OK && !locked ){
37838       int nPage;
37839
37840       /* Check the size of the database file. If it consists of 0 pages,
37841       ** then delete the journal file. See the header comment above for 
37842       ** the reasoning here.  Delete the obsolete journal file under
37843       ** a RESERVED lock to avoid race conditions and to avoid violating
37844       ** [H33020].
37845       */
37846       rc = sqlite3PagerPagecount(pPager, &nPage);
37847       if( rc==SQLITE_OK ){
37848         if( nPage==0 ){
37849           sqlite3BeginBenignMalloc();
37850           if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
37851             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
37852             sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
37853           }
37854           sqlite3EndBenignMalloc();
37855         }else{
37856           /* The journal file exists and no other connection has a reserved
37857           ** or greater lock on the database file. Now check that there is
37858           ** at least one non-zero bytes at the start of the journal file.
37859           ** If there is, then we consider this journal to be hot. If not, 
37860           ** it can be ignored.
37861           */
37862           if( !jrnlOpen ){
37863             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
37864             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
37865           }
37866           if( rc==SQLITE_OK ){
37867             u8 first = 0;
37868             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
37869             if( rc==SQLITE_IOERR_SHORT_READ ){
37870               rc = SQLITE_OK;
37871             }
37872             if( !jrnlOpen ){
37873               sqlite3OsClose(pPager->jfd);
37874             }
37875             *pExists = (first!=0);
37876           }else if( rc==SQLITE_CANTOPEN ){
37877             /* If we cannot open the rollback journal file in order to see if
37878             ** its has a zero header, that might be due to an I/O error, or
37879             ** it might be due to the race condition described above and in
37880             ** ticket #3883.  Either way, assume that the journal is hot.
37881             ** This might be a false positive.  But if it is, then the
37882             ** automatic journal playback and recovery mechanism will deal
37883             ** with it under an EXCLUSIVE lock where we do not need to
37884             ** worry so much with race conditions.
37885             */
37886             *pExists = 1;
37887             rc = SQLITE_OK;
37888           }
37889         }
37890       }
37891     }
37892   }
37893
37894   return rc;
37895 }
37896
37897 /*
37898 ** This function is called to obtain a shared lock on the database file.
37899 ** It is illegal to call sqlite3PagerAcquire() until after this function
37900 ** has been successfully called. If a shared-lock is already held when
37901 ** this function is called, it is a no-op.
37902 **
37903 ** The following operations are also performed by this function.
37904 **
37905 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
37906 **      on the database file), then an attempt is made to obtain a
37907 **      SHARED lock on the database file. Immediately after obtaining
37908 **      the SHARED lock, the file-system is checked for a hot-journal,
37909 **      which is played back if present. Following any hot-journal 
37910 **      rollback, the contents of the cache are validated by checking
37911 **      the 'change-counter' field of the database file header and
37912 **      discarded if they are found to be invalid.
37913 **
37914 **   2) If the pager is running in exclusive-mode, and there are currently
37915 **      no outstanding references to any pages, and is in the error state,
37916 **      then an attempt is made to clear the error state by discarding
37917 **      the contents of the page cache and rolling back any open journal
37918 **      file.
37919 **
37920 ** If the operation described by (2) above is not attempted, and if the
37921 ** pager is in an error state other than SQLITE_FULL when this is called,
37922 ** the error state error code is returned. It is permitted to read the
37923 ** database when in SQLITE_FULL error state.
37924 **
37925 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
37926 ** IO error occurs while locking the database, checking for a hot-journal
37927 ** file or rolling back a journal file, the IO error code is returned.
37928 */
37929 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
37930   int rc = SQLITE_OK;                /* Return code */
37931   int isErrorReset = 0;              /* True if recovering from error state */
37932
37933   /* This routine is only called from b-tree and only when there are no
37934   ** outstanding pages */
37935   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37936   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
37937
37938   /* If this database is in an error-state, now is a chance to clear
37939   ** the error. Discard the contents of the pager-cache and rollback
37940   ** any hot journal in the file-system.
37941   */
37942   if( pPager->errCode ){
37943     if( isOpen(pPager->jfd) || pPager->zJournal ){
37944       isErrorReset = 1;
37945     }
37946     pPager->errCode = SQLITE_OK;
37947     pager_reset(pPager);
37948   }
37949
37950   if( pagerUseWal(pPager) ){
37951     rc = pagerBeginReadTransaction(pPager);
37952   }else if( pPager->state==PAGER_UNLOCK || isErrorReset ){
37953     sqlite3_vfs * const pVfs = pPager->pVfs;
37954     int isHotJournal = 0;
37955     assert( !MEMDB );
37956     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37957     if( pPager->noReadlock ){
37958       assert( pPager->readOnly );
37959       pPager->state = PAGER_SHARED;
37960     }else{
37961       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
37962       if( rc!=SQLITE_OK ){
37963         assert( pPager->state==PAGER_UNLOCK );
37964         return pager_error(pPager, rc);
37965       }
37966     }
37967     assert( pPager->state>=SHARED_LOCK );
37968
37969     /* If a journal file exists, and there is no RESERVED lock on the
37970     ** database file, then it either needs to be played back or deleted.
37971     */
37972     if( !isErrorReset ){
37973       assert( pPager->state <= PAGER_SHARED );
37974       rc = hasHotJournal(pPager, &isHotJournal);
37975       if( rc!=SQLITE_OK ){
37976         goto failed;
37977       }
37978     }
37979     if( isErrorReset || isHotJournal ){
37980       /* Get an EXCLUSIVE lock on the database file. At this point it is
37981       ** important that a RESERVED lock is not obtained on the way to the
37982       ** EXCLUSIVE lock. If it were, another process might open the
37983       ** database file, detect the RESERVED lock, and conclude that the
37984       ** database is safe to read while this process is still rolling the 
37985       ** hot-journal back.
37986       ** 
37987       ** Because the intermediate RESERVED lock is not requested, any
37988       ** other process attempting to access the database file will get to 
37989       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
37990       ** on the database file.
37991       */
37992       if( pPager->state<EXCLUSIVE_LOCK ){
37993         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
37994         if( rc!=SQLITE_OK ){
37995           rc = pager_error(pPager, rc);
37996           goto failed;
37997         }
37998         pPager->state = PAGER_EXCLUSIVE;
37999       }
38000  
38001       /* Open the journal for read/write access. This is because in 
38002       ** exclusive-access mode the file descriptor will be kept open and
38003       ** possibly used for a transaction later on. On some systems, the
38004       ** OsTruncate() call used in exclusive-access mode also requires
38005       ** a read/write file handle.
38006       */
38007       if( !isOpen(pPager->jfd) ){
38008         int res;
38009         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
38010         if( rc==SQLITE_OK ){
38011           if( res ){
38012             int fout = 0;
38013             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
38014             assert( !pPager->tempFile );
38015             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
38016             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38017             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
38018               rc = SQLITE_CANTOPEN_BKPT;
38019               sqlite3OsClose(pPager->jfd);
38020             }
38021           }else{
38022             /* If the journal does not exist, it usually means that some 
38023             ** other connection managed to get in and roll it back before 
38024             ** this connection obtained the exclusive lock above. Or, it 
38025             ** may mean that the pager was in the error-state when this
38026             ** function was called and the journal file does not exist.  */
38027             rc = pager_end_transaction(pPager, 0);
38028           }
38029         }
38030       }
38031       if( rc!=SQLITE_OK ){
38032         goto failed;
38033       }
38034
38035       /* Reset the journal status fields to indicates that we have no
38036       ** rollback journal at this time. */
38037       pPager->journalStarted = 0;
38038       pPager->journalOff = 0;
38039       pPager->setMaster = 0;
38040       pPager->journalHdr = 0;
38041  
38042       /* Make sure the journal file has been synced to disk. */
38043  
38044       /* Playback and delete the journal.  Drop the database write
38045       ** lock and reacquire the read lock. Purge the cache before
38046       ** playing back the hot-journal so that we don't end up with
38047       ** an inconsistent cache.  Sync the hot journal before playing
38048       ** it back since the process that crashed and left the hot journal
38049       ** probably did not sync it and we are required to always sync
38050       ** the journal before playing it back.
38051       */
38052       if( isOpen(pPager->jfd) ){
38053         rc = pagerSyncHotJournal(pPager);
38054         if( rc==SQLITE_OK ){
38055           rc = pager_playback(pPager, 1);
38056         }
38057         if( rc!=SQLITE_OK ){
38058           rc = pager_error(pPager, rc);
38059           goto failed;
38060         }
38061       }
38062       assert( (pPager->state==PAGER_SHARED)
38063            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
38064       );
38065     }
38066
38067     if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
38068       /* The shared-lock has just been acquired on the database file
38069       ** and there are already pages in the cache (from a previous
38070       ** read or write transaction).  Check to see if the database
38071       ** has been modified.  If the database has changed, flush the
38072       ** cache.
38073       **
38074       ** Database changes is detected by looking at 15 bytes beginning
38075       ** at offset 24 into the file.  The first 4 of these 16 bytes are
38076       ** a 32-bit counter that is incremented with each change.  The
38077       ** other bytes change randomly with each file change when
38078       ** a codec is in use.
38079       ** 
38080       ** There is a vanishingly small chance that a change will not be 
38081       ** detected.  The chance of an undetected change is so small that
38082       ** it can be neglected.
38083       */
38084       int nPage = 0;
38085       char dbFileVers[sizeof(pPager->dbFileVers)];
38086       sqlite3PagerPagecount(pPager, &nPage);
38087
38088       if( pPager->errCode ){
38089         rc = pPager->errCode;
38090         goto failed;
38091       }
38092
38093       if( nPage>0 ){
38094         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
38095         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
38096         if( rc!=SQLITE_OK ){
38097           goto failed;
38098         }
38099       }else{
38100         memset(dbFileVers, 0, sizeof(dbFileVers));
38101       }
38102
38103       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
38104         pager_reset(pPager);
38105       }
38106     }
38107     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
38108
38109     /* If there is a WAL file in the file-system, open this database in WAL
38110     ** mode. Otherwise, the following function call is a no-op.
38111     */
38112     rc = pagerOpenWalIfPresent(pPager);
38113   }
38114
38115  failed:
38116   if( rc!=SQLITE_OK ){
38117     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
38118     pager_unlock(pPager);
38119   }
38120   return rc;
38121 }
38122
38123 /*
38124 ** If the reference count has reached zero, rollback any active
38125 ** transaction and unlock the pager.
38126 **
38127 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
38128 ** the rollback journal, the unlock is not performed and there is
38129 ** nothing to rollback, so this routine is a no-op.
38130 */ 
38131 static void pagerUnlockIfUnused(Pager *pPager){
38132   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
38133    && (!pPager->exclusiveMode || pPager->journalOff>0) 
38134   ){
38135     pagerUnlockAndRollback(pPager);
38136   }
38137 }
38138
38139 /*
38140 ** Acquire a reference to page number pgno in pager pPager (a page
38141 ** reference has type DbPage*). If the requested reference is 
38142 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
38143 **
38144 ** If the requested page is already in the cache, it is returned. 
38145 ** Otherwise, a new page object is allocated and populated with data
38146 ** read from the database file. In some cases, the pcache module may
38147 ** choose not to allocate a new page object and may reuse an existing
38148 ** object with no outstanding references.
38149 **
38150 ** The extra data appended to a page is always initialized to zeros the 
38151 ** first time a page is loaded into memory. If the page requested is 
38152 ** already in the cache when this function is called, then the extra
38153 ** data is left as it was when the page object was last used.
38154 **
38155 ** If the database image is smaller than the requested page or if a 
38156 ** non-zero value is passed as the noContent parameter and the 
38157 ** requested page is not already stored in the cache, then no 
38158 ** actual disk read occurs. In this case the memory image of the 
38159 ** page is initialized to all zeros. 
38160 **
38161 ** If noContent is true, it means that we do not care about the contents
38162 ** of the page. This occurs in two seperate scenarios:
38163 **
38164 **   a) When reading a free-list leaf page from the database, and
38165 **
38166 **   b) When a savepoint is being rolled back and we need to load
38167 **      a new page into the cache to be filled with the data read
38168 **      from the savepoint journal.
38169 **
38170 ** If noContent is true, then the data returned is zeroed instead of
38171 ** being read from the database. Additionally, the bits corresponding
38172 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
38173 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
38174 ** savepoints are set. This means if the page is made writable at any
38175 ** point in the future, using a call to sqlite3PagerWrite(), its contents
38176 ** will not be journaled. This saves IO.
38177 **
38178 ** The acquisition might fail for several reasons.  In all cases,
38179 ** an appropriate error code is returned and *ppPage is set to NULL.
38180 **
38181 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
38182 ** to find a page in the in-memory cache first.  If the page is not already
38183 ** in memory, this routine goes to disk to read it in whereas Lookup()
38184 ** just returns 0.  This routine acquires a read-lock the first time it
38185 ** has to go to disk, and could also playback an old journal if necessary.
38186 ** Since Lookup() never goes to disk, it never has to deal with locks
38187 ** or journal files.
38188 */
38189 SQLITE_PRIVATE int sqlite3PagerAcquire(
38190   Pager *pPager,      /* The pager open on the database file */
38191   Pgno pgno,          /* Page number to fetch */
38192   DbPage **ppPage,    /* Write a pointer to the page here */
38193   int noContent       /* Do not bother reading content from disk if true */
38194 ){
38195   int rc;
38196   PgHdr *pPg;
38197
38198   assert( assert_pager_state(pPager) );
38199   assert( pPager->state>PAGER_UNLOCK );
38200
38201   if( pgno==0 ){
38202     return SQLITE_CORRUPT_BKPT;
38203   }
38204
38205   /* If the pager is in the error state, return an error immediately. 
38206   ** Otherwise, request the page from the PCache layer. */
38207   if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
38208     rc = pPager->errCode;
38209   }else{
38210     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
38211   }
38212
38213   if( rc!=SQLITE_OK ){
38214     /* Either the call to sqlite3PcacheFetch() returned an error or the
38215     ** pager was already in the error-state when this function was called.
38216     ** Set pPg to 0 and jump to the exception handler.  */
38217     pPg = 0;
38218     goto pager_acquire_err;
38219   }
38220   assert( (*ppPage)->pgno==pgno );
38221   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
38222
38223   if( (*ppPage)->pPager && !noContent ){
38224     /* In this case the pcache already contains an initialized copy of
38225     ** the page. Return without further ado.  */
38226     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
38227     PAGER_INCR(pPager->nHit);
38228     return SQLITE_OK;
38229
38230   }else{
38231     /* The pager cache has created a new page. Its content needs to 
38232     ** be initialized.  */
38233     int nMax;
38234
38235     PAGER_INCR(pPager->nMiss);
38236     pPg = *ppPage;
38237     pPg->pPager = pPager;
38238
38239     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
38240     ** number greater than this, or the unused locking-page, is requested. */
38241     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
38242       rc = SQLITE_CORRUPT_BKPT;
38243       goto pager_acquire_err;
38244     }
38245
38246     rc = sqlite3PagerPagecount(pPager, &nMax);
38247     if( rc!=SQLITE_OK ){
38248       goto pager_acquire_err;
38249     }
38250
38251     if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
38252       if( pgno>pPager->mxPgno ){
38253         rc = SQLITE_FULL;
38254         goto pager_acquire_err;
38255       }
38256       if( noContent ){
38257         /* Failure to set the bits in the InJournal bit-vectors is benign.
38258         ** It merely means that we might do some extra work to journal a 
38259         ** page that does not need to be journaled.  Nevertheless, be sure 
38260         ** to test the case where a malloc error occurs while trying to set 
38261         ** a bit in a bit vector.
38262         */
38263         sqlite3BeginBenignMalloc();
38264         if( pgno<=pPager->dbOrigSize ){
38265           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
38266           testcase( rc==SQLITE_NOMEM );
38267         }
38268         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
38269         testcase( rc==SQLITE_NOMEM );
38270         sqlite3EndBenignMalloc();
38271       }
38272       memset(pPg->pData, 0, pPager->pageSize);
38273       IOTRACE(("ZERO %p %d\n", pPager, pgno));
38274     }else{
38275       assert( pPg->pPager==pPager );
38276       rc = readDbPage(pPg);
38277       if( rc!=SQLITE_OK ){
38278         goto pager_acquire_err;
38279       }
38280     }
38281 #ifdef SQLITE_CHECK_PAGES
38282     pPg->pageHash = pager_pagehash(pPg);
38283 #endif
38284   }
38285
38286   return SQLITE_OK;
38287
38288 pager_acquire_err:
38289   assert( rc!=SQLITE_OK );
38290   if( pPg ){
38291     sqlite3PcacheDrop(pPg);
38292   }
38293   pagerUnlockIfUnused(pPager);
38294
38295   *ppPage = 0;
38296   return rc;
38297 }
38298
38299 /*
38300 ** Acquire a page if it is already in the in-memory cache.  Do
38301 ** not read the page from disk.  Return a pointer to the page,
38302 ** or 0 if the page is not in cache. Also, return 0 if the 
38303 ** pager is in PAGER_UNLOCK state when this function is called,
38304 ** or if the pager is in an error state other than SQLITE_FULL.
38305 **
38306 ** See also sqlite3PagerGet().  The difference between this routine
38307 ** and sqlite3PagerGet() is that _get() will go to the disk and read
38308 ** in the page if the page is not already in cache.  This routine
38309 ** returns NULL if the page is not in cache or if a disk I/O error 
38310 ** has ever happened.
38311 */
38312 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
38313   PgHdr *pPg = 0;
38314   assert( pPager!=0 );
38315   assert( pgno!=0 );
38316   assert( pPager->pPCache!=0 );
38317   assert( pPager->state > PAGER_UNLOCK );
38318   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
38319   return pPg;
38320 }
38321
38322 /*
38323 ** Release a page reference.
38324 **
38325 ** If the number of references to the page drop to zero, then the
38326 ** page is added to the LRU list.  When all references to all pages
38327 ** are released, a rollback occurs and the lock on the database is
38328 ** removed.
38329 */
38330 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
38331   if( pPg ){
38332     Pager *pPager = pPg->pPager;
38333     sqlite3PcacheRelease(pPg);
38334     pagerUnlockIfUnused(pPager);
38335   }
38336 }
38337
38338 /*
38339 ** This function is called at the start of every write transaction.
38340 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
38341 ** file when this routine is called.
38342 **
38343 ** Open the journal file for pager pPager and write a journal header
38344 ** to the start of it. If there are active savepoints, open the sub-journal
38345 ** as well. This function is only used when the journal file is being 
38346 ** opened to write a rollback log for a transaction. It is not used 
38347 ** when opening a hot journal file to roll it back.
38348 **
38349 ** If the journal file is already open (as it may be in exclusive mode),
38350 ** then this function just writes a journal header to the start of the
38351 ** already open file. 
38352 **
38353 ** Whether or not the journal file is opened by this function, the
38354 ** Pager.pInJournal bitvec structure is allocated.
38355 **
38356 ** Return SQLITE_OK if everything is successful. Otherwise, return 
38357 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
38358 ** an IO error code if opening or writing the journal file fails.
38359 */
38360 static int pager_open_journal(Pager *pPager){
38361   int rc = SQLITE_OK;                        /* Return code */
38362   int nPage;                                 /* Size of database file */
38363   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
38364
38365   assert( pPager->state>=PAGER_RESERVED );
38366   assert( pPager->useJournal );
38367   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
38368   assert( pPager->pInJournal==0 );
38369   
38370   /* If already in the error state, this function is a no-op.  But on
38371   ** the other hand, this routine is never called if we are already in
38372   ** an error state. */
38373   if( NEVER(pPager->errCode) ) return pPager->errCode;
38374
38375   testcase( pPager->dbSizeValid==0 );
38376   rc = sqlite3PagerPagecount(pPager, &nPage);
38377   if( rc ) return rc;
38378   pPager->pInJournal = sqlite3BitvecCreate(nPage);
38379   if( pPager->pInJournal==0 ){
38380     return SQLITE_NOMEM;
38381   }
38382
38383   /* Open the journal file if it is not already open. */
38384   if( !isOpen(pPager->jfd) ){
38385     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
38386       sqlite3MemJournalOpen(pPager->jfd);
38387     }else{
38388       const int flags =                   /* VFS flags to open journal file */
38389         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
38390         (pPager->tempFile ? 
38391           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
38392           (SQLITE_OPEN_MAIN_JOURNAL)
38393         );
38394 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38395       rc = sqlite3JournalOpen(
38396           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
38397       );
38398 #else
38399       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
38400 #endif
38401     }
38402     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38403   }
38404
38405
38406   /* Write the first journal header to the journal file and open 
38407   ** the sub-journal if necessary.
38408   */
38409   if( rc==SQLITE_OK ){
38410     /* TODO: Check if all of these are really required. */
38411     pPager->dbOrigSize = pPager->dbSize;
38412     pPager->journalStarted = 0;
38413     pPager->needSync = 0;
38414     pPager->nRec = 0;
38415     pPager->journalOff = 0;
38416     pPager->setMaster = 0;
38417     pPager->journalHdr = 0;
38418     rc = writeJournalHdr(pPager);
38419   }
38420
38421   if( rc!=SQLITE_OK ){
38422     sqlite3BitvecDestroy(pPager->pInJournal);
38423     pPager->pInJournal = 0;
38424   }
38425   return rc;
38426 }
38427
38428 /*
38429 ** Begin a write-transaction on the specified pager object. If a 
38430 ** write-transaction has already been opened, this function is a no-op.
38431 **
38432 ** If the exFlag argument is false, then acquire at least a RESERVED
38433 ** lock on the database file. If exFlag is true, then acquire at least
38434 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
38435 ** functions need be called.
38436 **
38437 ** If this is not a temporary or in-memory file and, the journal file is 
38438 ** opened if it has not been already. For a temporary file, the opening 
38439 ** of the journal file is deferred until there is an actual need to 
38440 ** write to the journal. TODO: Why handle temporary files differently?
38441 **
38442 ** If the journal file is opened (or if it is already open), then a
38443 ** journal-header is written to the start of it.
38444 **
38445 ** If the subjInMemory argument is non-zero, then any sub-journal opened
38446 ** within this transaction will be opened as an in-memory file. This
38447 ** has no effect if the sub-journal is already opened (as it may be when
38448 ** running in exclusive mode) or if the transaction does not require a
38449 ** sub-journal. If the subjInMemory argument is zero, then any required
38450 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
38451 ** or using a temporary file otherwise.
38452 */
38453 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
38454   int rc = SQLITE_OK;
38455   assert( pPager->state!=PAGER_UNLOCK );
38456   pPager->subjInMemory = (u8)subjInMemory;
38457
38458   if( pPager->state==PAGER_SHARED ){
38459     assert( pPager->pInJournal==0 );
38460     assert( !MEMDB && !pPager->tempFile );
38461
38462     if( pagerUseWal(pPager) ){
38463       /* If the pager is configured to use locking_mode=exclusive, and an
38464       ** exclusive lock on the database is not already held, obtain it now.
38465       */
38466       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
38467         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
38468         pPager->state = PAGER_SHARED;
38469         if( rc!=SQLITE_OK ){
38470           return rc;
38471         }
38472         sqlite3WalExclusiveMode(pPager->pWal, 1);
38473       }
38474
38475       /* Grab the write lock on the log file. If successful, upgrade to
38476       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
38477       ** The busy-handler is not invoked if another connection already
38478       ** holds the write-lock. If possible, the upper layer will call it.
38479       **
38480       ** WAL mode sets Pager.state to PAGER_RESERVED when it has an open
38481       ** transaction, but never to PAGER_EXCLUSIVE. This is because in 
38482       ** PAGER_EXCLUSIVE state the code to roll back savepoint transactions
38483       ** may copy data from the sub-journal into the database file as well
38484       ** as into the page cache. Which would be incorrect in WAL mode.
38485       */
38486       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
38487       if( rc==SQLITE_OK ){
38488         pPager->dbOrigSize = pPager->dbSize;
38489         pPager->state = PAGER_RESERVED;
38490         pPager->journalOff = 0;
38491       }
38492
38493       assert( rc!=SQLITE_OK || pPager->state==PAGER_RESERVED );
38494       assert( rc==SQLITE_OK || pPager->state==PAGER_SHARED );
38495     }else{
38496       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
38497       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
38498       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
38499       ** lock, but not when obtaining the RESERVED lock.
38500       */
38501       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
38502       if( rc==SQLITE_OK ){
38503         pPager->state = PAGER_RESERVED;
38504         if( exFlag ){
38505           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
38506         }
38507       }
38508     }
38509
38510     /* No need to open the journal file at this time.  It will be
38511     ** opened before it is written to.  If we defer opening the journal,
38512     ** we might save the work of creating a file if the transaction
38513     ** ends up being a no-op.
38514     */
38515
38516     if( rc!=SQLITE_OK ){
38517       assert( !pPager->dbModified );
38518       /* Ignore any IO error that occurs within pager_end_transaction(). The
38519       ** purpose of this call is to reset the internal state of the pager
38520       ** sub-system. It doesn't matter if the journal-file is not properly
38521       ** finalized at this point (since it is not a valid journal file anyway).
38522       */
38523       pager_end_transaction(pPager, 0);
38524     }
38525   }
38526
38527   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
38528   return rc;
38529 }
38530
38531 /*
38532 ** Mark a single data page as writeable. The page is written into the 
38533 ** main journal or sub-journal as required. If the page is written into
38534 ** one of the journals, the corresponding bit is set in the 
38535 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
38536 ** of any open savepoints as appropriate.
38537 */
38538 static int pager_write(PgHdr *pPg){
38539   void *pData = pPg->pData;
38540   Pager *pPager = pPg->pPager;
38541   int rc = SQLITE_OK;
38542
38543   /* This routine is not called unless a transaction has already been
38544   ** started.
38545   */
38546   assert( pPager->state>=PAGER_RESERVED );
38547
38548   /* If an error has been previously detected, report the same error
38549   ** again.
38550   */
38551   if( NEVER(pPager->errCode) )  return pPager->errCode;
38552
38553   /* Higher-level routines never call this function if database is not
38554   ** writable.  But check anyway, just for robustness. */
38555   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
38556
38557   assert( !pPager->setMaster );
38558
38559   CHECK_PAGE(pPg);
38560
38561   /* Mark the page as dirty.  If the page has already been written
38562   ** to the journal then we can return right away.
38563   */
38564   sqlite3PcacheMakeDirty(pPg);
38565   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
38566     assert( !pagerUseWal(pPager) );
38567     pPager->dbModified = 1;
38568   }else{
38569
38570     /* If we get this far, it means that the page needs to be
38571     ** written to the transaction journal or the ckeckpoint journal
38572     ** or both.
38573     **
38574     ** Higher level routines should have already started a transaction,
38575     ** which means they have acquired the necessary locks but the rollback
38576     ** journal might not yet be open.
38577     */
38578     assert( pPager->state>=RESERVED_LOCK );
38579     if( pPager->pInJournal==0
38580      && pPager->journalMode!=PAGER_JOURNALMODE_OFF 
38581      && !pagerUseWal(pPager)
38582     ){
38583       assert( pPager->useJournal );
38584       rc = pager_open_journal(pPager);
38585       if( rc!=SQLITE_OK ) return rc;
38586     }
38587     pPager->dbModified = 1;
38588   
38589     /* The transaction journal now exists and we have a RESERVED or an
38590     ** EXCLUSIVE lock on the main database file.  Write the current page to
38591     ** the transaction journal if it is not there already.
38592     */
38593     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
38594       assert( !pagerUseWal(pPager) );
38595       if( pPg->pgno<=pPager->dbOrigSize ){
38596         u32 cksum;
38597         char *pData2;
38598
38599         /* We should never write to the journal file the page that
38600         ** contains the database locks.  The following assert verifies
38601         ** that we do not. */
38602         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
38603
38604         assert( pPager->journalHdr <= pPager->journalOff );
38605         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38606         cksum = pager_cksum(pPager, (u8*)pData2);
38607         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
38608         if( rc==SQLITE_OK ){
38609           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
38610                               pPager->journalOff + 4);
38611           pPager->journalOff += pPager->pageSize+4;
38612         }
38613         if( rc==SQLITE_OK ){
38614           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
38615           pPager->journalOff += 4;
38616         }
38617         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
38618                  pPager->journalOff, pPager->pageSize));
38619         PAGER_INCR(sqlite3_pager_writej_count);
38620         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
38621              PAGERID(pPager), pPg->pgno, 
38622              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
38623
38624         /* Even if an IO or diskfull error occurred while journalling the
38625         ** page in the block above, set the need-sync flag for the page.
38626         ** Otherwise, when the transaction is rolled back, the logic in
38627         ** playback_one_page() will think that the page needs to be restored
38628         ** in the database file. And if an IO error occurs while doing so,
38629         ** then corruption may follow.
38630         */
38631         if( !pPager->noSync ){
38632           pPg->flags |= PGHDR_NEED_SYNC;
38633           pPager->needSync = 1;
38634         }
38635
38636         /* An error has occurred writing to the journal file. The 
38637         ** transaction will be rolled back by the layer above.
38638         */
38639         if( rc!=SQLITE_OK ){
38640           return rc;
38641         }
38642
38643         pPager->nRec++;
38644         assert( pPager->pInJournal!=0 );
38645         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
38646         testcase( rc==SQLITE_NOMEM );
38647         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38648         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
38649         if( rc!=SQLITE_OK ){
38650           assert( rc==SQLITE_NOMEM );
38651           return rc;
38652         }
38653       }else{
38654         if( !pPager->journalStarted && !pPager->noSync ){
38655           pPg->flags |= PGHDR_NEED_SYNC;
38656           pPager->needSync = 1;
38657         }
38658         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
38659                 PAGERID(pPager), pPg->pgno,
38660                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
38661       }
38662     }
38663   
38664     /* If the statement journal is open and the page is not in it,
38665     ** then write the current page to the statement journal.  Note that
38666     ** the statement journal format differs from the standard journal format
38667     ** in that it omits the checksums and the header.
38668     */
38669     if( subjRequiresPage(pPg) ){
38670       rc = subjournalPage(pPg);
38671     }
38672   }
38673
38674   /* Update the database size and return.
38675   */
38676   assert( pPager->state>=PAGER_SHARED );
38677   if( pPager->dbSize<pPg->pgno ){
38678     pPager->dbSize = pPg->pgno;
38679   }
38680   return rc;
38681 }
38682
38683 /*
38684 ** Mark a data page as writeable. This routine must be called before 
38685 ** making changes to a page. The caller must check the return value 
38686 ** of this function and be careful not to change any page data unless 
38687 ** this routine returns SQLITE_OK.
38688 **
38689 ** The difference between this function and pager_write() is that this
38690 ** function also deals with the special case where 2 or more pages
38691 ** fit on a single disk sector. In this case all co-resident pages
38692 ** must have been written to the journal file before returning.
38693 **
38694 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
38695 ** as appropriate. Otherwise, SQLITE_OK.
38696 */
38697 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
38698   int rc = SQLITE_OK;
38699
38700   PgHdr *pPg = pDbPage;
38701   Pager *pPager = pPg->pPager;
38702   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
38703
38704   if( nPagePerSector>1 ){
38705     Pgno nPageCount;          /* Total number of pages in database file */
38706     Pgno pg1;                 /* First page of the sector pPg is located on. */
38707     int nPage = 0;            /* Number of pages starting at pg1 to journal */
38708     int ii;                   /* Loop counter */
38709     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
38710
38711     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
38712     ** a journal header to be written between the pages journaled by
38713     ** this function.
38714     */
38715     assert( !MEMDB );
38716     assert( pPager->doNotSyncSpill==0 );
38717     pPager->doNotSyncSpill++;
38718
38719     /* This trick assumes that both the page-size and sector-size are
38720     ** an integer power of 2. It sets variable pg1 to the identifier
38721     ** of the first page of the sector pPg is located on.
38722     */
38723     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
38724
38725     rc = sqlite3PagerPagecount(pPager, (int *)&nPageCount);
38726     if( rc==SQLITE_OK ){
38727       if( pPg->pgno>nPageCount ){
38728         nPage = (pPg->pgno - pg1)+1;
38729       }else if( (pg1+nPagePerSector-1)>nPageCount ){
38730         nPage = nPageCount+1-pg1;
38731       }else{
38732         nPage = nPagePerSector;
38733       }
38734       assert(nPage>0);
38735       assert(pg1<=pPg->pgno);
38736       assert((pg1+nPage)>pPg->pgno);
38737     }
38738
38739     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
38740       Pgno pg = pg1+ii;
38741       PgHdr *pPage;
38742       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
38743         if( pg!=PAGER_MJ_PGNO(pPager) ){
38744           rc = sqlite3PagerGet(pPager, pg, &pPage);
38745           if( rc==SQLITE_OK ){
38746             rc = pager_write(pPage);
38747             if( pPage->flags&PGHDR_NEED_SYNC ){
38748               needSync = 1;
38749               assert(pPager->needSync);
38750             }
38751             sqlite3PagerUnref(pPage);
38752           }
38753         }
38754       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
38755         if( pPage->flags&PGHDR_NEED_SYNC ){
38756           needSync = 1;
38757         }
38758         sqlite3PagerUnref(pPage);
38759       }
38760     }
38761
38762     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
38763     ** starting at pg1, then it needs to be set for all of them. Because
38764     ** writing to any of these nPage pages may damage the others, the
38765     ** journal file must contain sync()ed copies of all of them
38766     ** before any of them can be written out to the database file.
38767     */
38768     if( rc==SQLITE_OK && needSync ){
38769       assert( !MEMDB && pPager->noSync==0 );
38770       for(ii=0; ii<nPage; ii++){
38771         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
38772         if( pPage ){
38773           pPage->flags |= PGHDR_NEED_SYNC;
38774           sqlite3PagerUnref(pPage);
38775         }
38776       }
38777       assert(pPager->needSync);
38778     }
38779
38780     assert( pPager->doNotSyncSpill==1 );
38781     pPager->doNotSyncSpill--;
38782   }else{
38783     rc = pager_write(pDbPage);
38784   }
38785   return rc;
38786 }
38787
38788 /*
38789 ** Return TRUE if the page given in the argument was previously passed
38790 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
38791 ** to change the content of the page.
38792 */
38793 #ifndef NDEBUG
38794 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
38795   return pPg->flags&PGHDR_DIRTY;
38796 }
38797 #endif
38798
38799 /*
38800 ** A call to this routine tells the pager that it is not necessary to
38801 ** write the information on page pPg back to the disk, even though
38802 ** that page might be marked as dirty.  This happens, for example, when
38803 ** the page has been added as a leaf of the freelist and so its
38804 ** content no longer matters.
38805 **
38806 ** The overlying software layer calls this routine when all of the data
38807 ** on the given page is unused. The pager marks the page as clean so
38808 ** that it does not get written to disk.
38809 **
38810 ** Tests show that this optimization can quadruple the speed of large 
38811 ** DELETE operations.
38812 */
38813 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
38814   Pager *pPager = pPg->pPager;
38815   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
38816     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
38817     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
38818     pPg->flags |= PGHDR_DONT_WRITE;
38819 #ifdef SQLITE_CHECK_PAGES
38820     pPg->pageHash = pager_pagehash(pPg);
38821 #endif
38822   }
38823 }
38824
38825 /*
38826 ** This routine is called to increment the value of the database file 
38827 ** change-counter, stored as a 4-byte big-endian integer starting at 
38828 ** byte offset 24 of the pager file.
38829 **
38830 ** If the isDirectMode flag is zero, then this is done by calling 
38831 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
38832 ** page data. In this case the file will be updated when the current
38833 ** transaction is committed.
38834 **
38835 ** The isDirectMode flag may only be non-zero if the library was compiled
38836 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
38837 ** if isDirect is non-zero, then the database file is updated directly
38838 ** by writing an updated version of page 1 using a call to the 
38839 ** sqlite3OsWrite() function.
38840 */
38841 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
38842   int rc = SQLITE_OK;
38843
38844   /* Declare and initialize constant integer 'isDirect'. If the
38845   ** atomic-write optimization is enabled in this build, then isDirect
38846   ** is initialized to the value passed as the isDirectMode parameter
38847   ** to this function. Otherwise, it is always set to zero.
38848   **
38849   ** The idea is that if the atomic-write optimization is not
38850   ** enabled at compile time, the compiler can omit the tests of
38851   ** 'isDirect' below, as well as the block enclosed in the
38852   ** "if( isDirect )" condition.
38853   */
38854 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
38855 # define DIRECT_MODE 0
38856   assert( isDirectMode==0 );
38857   UNUSED_PARAMETER(isDirectMode);
38858 #else
38859 # define DIRECT_MODE isDirectMode
38860 #endif
38861
38862   assert( pPager->state>=PAGER_RESERVED );
38863   if( !pPager->changeCountDone && pPager->dbSize>0 ){
38864     PgHdr *pPgHdr;                /* Reference to page 1 */
38865     u32 change_counter;           /* Initial value of change-counter field */
38866
38867     assert( !pPager->tempFile && isOpen(pPager->fd) );
38868
38869     /* Open page 1 of the file for writing. */
38870     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
38871     assert( pPgHdr==0 || rc==SQLITE_OK );
38872
38873     /* If page one was fetched successfully, and this function is not
38874     ** operating in direct-mode, make page 1 writable.  When not in 
38875     ** direct mode, page 1 is always held in cache and hence the PagerGet()
38876     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
38877     */
38878     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
38879       rc = sqlite3PagerWrite(pPgHdr);
38880     }
38881
38882     if( rc==SQLITE_OK ){
38883       /* Increment the value just read and write it back to byte 24. */
38884       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
38885       change_counter++;
38886       put32bits(((char*)pPgHdr->pData)+24, change_counter);
38887
38888       /* Also store the SQLite version number in bytes 96..99 and in
38889       ** bytes 92..95 store the change counter for which the version number
38890       ** is valid. */
38891       put32bits(((char*)pPgHdr->pData)+92, change_counter);
38892       put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
38893
38894       /* If running in direct mode, write the contents of page 1 to the file. */
38895       if( DIRECT_MODE ){
38896         const void *zBuf;
38897         assert( pPager->dbFileSize>0 );
38898         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
38899         if( rc==SQLITE_OK ){
38900           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
38901         }
38902         if( rc==SQLITE_OK ){
38903           pPager->changeCountDone = 1;
38904         }
38905       }else{
38906         pPager->changeCountDone = 1;
38907       }
38908     }
38909
38910     /* Release the page reference. */
38911     sqlite3PagerUnref(pPgHdr);
38912   }
38913   return rc;
38914 }
38915
38916 /*
38917 ** Sync the pager file to disk. This is a no-op for in-memory files
38918 ** or pages with the Pager.noSync flag set.
38919 **
38920 ** If successful, or called on a pager for which it is a no-op, this
38921 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
38922 */
38923 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
38924   int rc;                              /* Return code */
38925   assert( !MEMDB );
38926   if( pPager->noSync ){
38927     rc = SQLITE_OK;
38928   }else{
38929     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
38930   }
38931   return rc;
38932 }
38933
38934 /*
38935 ** Sync the database file for the pager pPager. zMaster points to the name
38936 ** of a master journal file that should be written into the individual
38937 ** journal file. zMaster may be NULL, which is interpreted as no master
38938 ** journal (a single database transaction).
38939 **
38940 ** This routine ensures that:
38941 **
38942 **   * The database file change-counter is updated,
38943 **   * the journal is synced (unless the atomic-write optimization is used),
38944 **   * all dirty pages are written to the database file, 
38945 **   * the database file is truncated (if required), and
38946 **   * the database file synced. 
38947 **
38948 ** The only thing that remains to commit the transaction is to finalize 
38949 ** (delete, truncate or zero the first part of) the journal file (or 
38950 ** delete the master journal file if specified).
38951 **
38952 ** Note that if zMaster==NULL, this does not overwrite a previous value
38953 ** passed to an sqlite3PagerCommitPhaseOne() call.
38954 **
38955 ** If the final parameter - noSync - is true, then the database file itself
38956 ** is not synced. The caller must call sqlite3PagerSync() directly to
38957 ** sync the database file before calling CommitPhaseTwo() to delete the
38958 ** journal file in this case.
38959 */
38960 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
38961   Pager *pPager,                  /* Pager object */
38962   const char *zMaster,            /* If not NULL, the master journal name */
38963   int noSync                      /* True to omit the xSync on the db file */
38964 ){
38965   int rc = SQLITE_OK;             /* Return code */
38966
38967   /* The dbOrigSize is never set if journal_mode=OFF */
38968   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
38969
38970   /* If a prior error occurred, report that error again. */
38971   if( pPager->errCode ) return pPager->errCode;
38972
38973   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
38974       pPager->zFilename, zMaster, pPager->dbSize));
38975
38976   if( MEMDB && pPager->dbModified ){
38977     /* If this is an in-memory db, or no pages have been written to, or this
38978     ** function has already been called, it is mostly a no-op.  However, any
38979     ** backup in progress needs to be restarted.
38980     */
38981     sqlite3BackupRestart(pPager->pBackup);
38982   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
38983     if( pagerUseWal(pPager) ){
38984       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
38985       if( pList ){
38986         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
38987             (pPager->fullSync ? pPager->sync_flags : 0)
38988         );
38989       }
38990       if( rc==SQLITE_OK ){
38991         sqlite3PcacheCleanAll(pPager->pPCache);
38992       }
38993     }else{
38994       /* The following block updates the change-counter. Exactly how it
38995       ** does this depends on whether or not the atomic-update optimization
38996       ** was enabled at compile time, and if this transaction meets the 
38997       ** runtime criteria to use the operation: 
38998       **
38999       **    * The file-system supports the atomic-write property for
39000       **      blocks of size page-size, and 
39001       **    * This commit is not part of a multi-file transaction, and
39002       **    * Exactly one page has been modified and store in the journal file.
39003       **
39004       ** If the optimization was not enabled at compile time, then the
39005       ** pager_incr_changecounter() function is called to update the change
39006       ** counter in 'indirect-mode'. If the optimization is compiled in but
39007       ** is not applicable to this transaction, call sqlite3JournalCreate()
39008       ** to make sure the journal file has actually been created, then call
39009       ** pager_incr_changecounter() to update the change-counter in indirect
39010       ** mode. 
39011       **
39012       ** Otherwise, if the optimization is both enabled and applicable,
39013       ** then call pager_incr_changecounter() to update the change-counter
39014       ** in 'direct' mode. In this case the journal file will never be
39015       ** created for this transaction.
39016       */
39017   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39018       PgHdr *pPg;
39019       assert( isOpen(pPager->jfd) 
39020            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
39021            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
39022       );
39023       if( !zMaster && isOpen(pPager->jfd) 
39024        && pPager->journalOff==jrnlBufferSize(pPager) 
39025        && pPager->dbSize>=pPager->dbFileSize
39026        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
39027       ){
39028         /* Update the db file change counter via the direct-write method. The 
39029         ** following call will modify the in-memory representation of page 1 
39030         ** to include the updated change counter and then write page 1 
39031         ** directly to the database file. Because of the atomic-write 
39032         ** property of the host file-system, this is safe.
39033         */
39034         rc = pager_incr_changecounter(pPager, 1);
39035       }else{
39036         rc = sqlite3JournalCreate(pPager->jfd);
39037         if( rc==SQLITE_OK ){
39038           rc = pager_incr_changecounter(pPager, 0);
39039         }
39040       }
39041   #else
39042       rc = pager_incr_changecounter(pPager, 0);
39043   #endif
39044       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39045   
39046       /* If this transaction has made the database smaller, then all pages
39047       ** being discarded by the truncation must be written to the journal
39048       ** file. This can only happen in auto-vacuum mode.
39049       **
39050       ** Before reading the pages with page numbers larger than the 
39051       ** current value of Pager.dbSize, set dbSize back to the value
39052       ** that it took at the start of the transaction. Otherwise, the
39053       ** calls to sqlite3PagerGet() return zeroed pages instead of 
39054       ** reading data from the database file.
39055       **
39056       ** When journal_mode==OFF the dbOrigSize is always zero, so this
39057       ** block never runs if journal_mode=OFF.
39058       */
39059   #ifndef SQLITE_OMIT_AUTOVACUUM
39060       if( pPager->dbSize<pPager->dbOrigSize 
39061        && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
39062       ){
39063         Pgno i;                                   /* Iterator variable */
39064         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
39065         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
39066         pPager->dbSize = pPager->dbOrigSize;
39067         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
39068           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
39069             PgHdr *pPage;             /* Page to journal */
39070             rc = sqlite3PagerGet(pPager, i, &pPage);
39071             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39072             rc = sqlite3PagerWrite(pPage);
39073             sqlite3PagerUnref(pPage);
39074             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39075           }
39076         }
39077         pPager->dbSize = dbSize;
39078       } 
39079   #endif
39080   
39081       /* Write the master journal name into the journal file. If a master 
39082       ** journal file name has already been written to the journal file, 
39083       ** or if zMaster is NULL (no master journal), then this call is a no-op.
39084       */
39085       rc = writeMasterJournal(pPager, zMaster);
39086       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39087   
39088       /* Sync the journal file. If the atomic-update optimization is being
39089       ** used, this call will not create the journal file or perform any
39090       ** real IO.
39091       */
39092       rc = syncJournal(pPager);
39093       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39094   
39095       /* Write all dirty pages to the database file. */
39096       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
39097       if( rc!=SQLITE_OK ){
39098         assert( rc!=SQLITE_IOERR_BLOCKED );
39099         goto commit_phase_one_exit;
39100       }
39101       sqlite3PcacheCleanAll(pPager->pPCache);
39102   
39103       /* If the file on disk is not the same size as the database image,
39104       ** then use pager_truncate to grow or shrink the file here.
39105       */
39106       if( pPager->dbSize!=pPager->dbFileSize ){
39107         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
39108         assert( pPager->state>=PAGER_EXCLUSIVE );
39109         rc = pager_truncate(pPager, nNew);
39110         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39111       }
39112   
39113       /* Finally, sync the database file. */
39114       if( !pPager->noSync && !noSync ){
39115         rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39116       }
39117       IOTRACE(("DBSYNC %p\n", pPager))
39118     }
39119
39120     pPager->state = PAGER_SYNCED;
39121   }
39122
39123 commit_phase_one_exit:
39124   return rc;
39125 }
39126
39127
39128 /*
39129 ** When this function is called, the database file has been completely
39130 ** updated to reflect the changes made by the current transaction and
39131 ** synced to disk. The journal file still exists in the file-system 
39132 ** though, and if a failure occurs at this point it will eventually
39133 ** be used as a hot-journal and the current transaction rolled back.
39134 **
39135 ** This function finalizes the journal file, either by deleting, 
39136 ** truncating or partially zeroing it, so that it cannot be used 
39137 ** for hot-journal rollback. Once this is done the transaction is
39138 ** irrevocably committed.
39139 **
39140 ** If an error occurs, an IO error code is returned and the pager
39141 ** moves into the error state. Otherwise, SQLITE_OK is returned.
39142 */
39143 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
39144   int rc = SQLITE_OK;                  /* Return code */
39145
39146   /* This routine should not be called if a prior error has occurred.
39147   ** But if (due to a coding error elsewhere in the system) it does get
39148   ** called, just return the same error code without doing anything. */
39149   if( NEVER(pPager->errCode) ) return pPager->errCode;
39150
39151   /* This function should not be called if the pager is not in at least
39152   ** PAGER_RESERVED state. **FIXME**: Make it so that this test always
39153   ** fails - make it so that we never reach this point if we do not hold
39154   ** all necessary locks.
39155   */
39156   if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
39157
39158   /* An optimization. If the database was not actually modified during
39159   ** this transaction, the pager is running in exclusive-mode and is
39160   ** using persistent journals, then this function is a no-op.
39161   **
39162   ** The start of the journal file currently contains a single journal 
39163   ** header with the nRec field set to 0. If such a journal is used as
39164   ** a hot-journal during hot-journal rollback, 0 changes will be made
39165   ** to the database file. So there is no need to zero the journal 
39166   ** header. Since the pager is in exclusive mode, there is no need
39167   ** to drop any locks either.
39168   */
39169   if( pPager->dbModified==0 && pPager->exclusiveMode 
39170    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39171   ){
39172     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
39173     return SQLITE_OK;
39174   }
39175
39176   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
39177   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
39178   rc = pager_end_transaction(pPager, pPager->setMaster);
39179   return pager_error(pPager, rc);
39180 }
39181
39182 /*
39183 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
39184 **
39185 ** This function performs two tasks:
39186 **
39187 **   1) It rolls back the journal file, restoring all database file and 
39188 **      in-memory cache pages to the state they were in when the transaction
39189 **      was opened, and
39190 **   2) It finalizes the journal file, so that it is not used for hot
39191 **      rollback at any point in the future.
39192 **
39193 ** subject to the following qualifications:
39194 **
39195 ** * If the journal file is not yet open when this function is called,
39196 **   then only (2) is performed. In this case there is no journal file
39197 **   to roll back.
39198 **
39199 ** * If in an error state other than SQLITE_FULL, then task (1) is 
39200 **   performed. If successful, task (2). Regardless of the outcome
39201 **   of either, the error state error code is returned to the caller
39202 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
39203 **
39204 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
39205 **   or not (1) is successful, also attempt (2). If successful, return
39206 **   SQLITE_OK. Otherwise, enter the error state and return the first 
39207 **   error code encountered. 
39208 **
39209 **   In this case there is no chance that the database was written to. 
39210 **   So is safe to finalize the journal file even if the playback 
39211 **   (operation 1) failed. However the pager must enter the error state
39212 **   as the contents of the in-memory cache are now suspect.
39213 **
39214 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
39215 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
39216 **   otherwise enter the error state and return the error code from the 
39217 **   failing operation.
39218 **
39219 **   In this case the database file may have been written to. So if the
39220 **   playback operation did not succeed it would not be safe to finalize
39221 **   the journal file. It needs to be left in the file-system so that
39222 **   some other process can use it to restore the database state (by
39223 **   hot-journal rollback).
39224 */
39225 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
39226   int rc = SQLITE_OK;                  /* Return code */
39227   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
39228   if( pagerUseWal(pPager) ){
39229     int rc2;
39230
39231     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
39232     rc2 = pager_end_transaction(pPager, pPager->setMaster);
39233     if( rc==SQLITE_OK ) rc = rc2;
39234     rc = pager_error(pPager, rc);
39235   }else if( !pPager->dbModified || !isOpen(pPager->jfd) ){
39236     rc = pager_end_transaction(pPager, pPager->setMaster);
39237   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
39238     if( pPager->state>=PAGER_EXCLUSIVE ){
39239       pager_playback(pPager, 0);
39240     }
39241     rc = pPager->errCode;
39242   }else{
39243     if( pPager->state==PAGER_RESERVED ){
39244       int rc2;
39245       rc = pager_playback(pPager, 0);
39246       rc2 = pager_end_transaction(pPager, pPager->setMaster);
39247       if( rc==SQLITE_OK ){
39248         rc = rc2;
39249       }
39250     }else{
39251       rc = pager_playback(pPager, 0);
39252     }
39253
39254     if( !MEMDB ){
39255       pPager->dbSizeValid = 0;
39256     }
39257
39258     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
39259     ** cache. So call pager_error() on the way out to make any error 
39260     ** persistent.
39261     */
39262     rc = pager_error(pPager, rc);
39263   }
39264   return rc;
39265 }
39266
39267 /*
39268 ** Return TRUE if the database file is opened read-only.  Return FALSE
39269 ** if the database is (in theory) writable.
39270 */
39271 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
39272   return pPager->readOnly;
39273 }
39274
39275 /*
39276 ** Return the number of references to the pager.
39277 */
39278 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
39279   return sqlite3PcacheRefCount(pPager->pPCache);
39280 }
39281
39282 /*
39283 ** Return the approximate number of bytes of memory currently
39284 ** used by the pager and its associated cache.
39285 */
39286 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
39287   int perPageSize = pPager->pageSize + pPager->nExtra + 20;
39288   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
39289            + sqlite3MallocSize(pPager);
39290 }
39291
39292 /*
39293 ** Return the number of references to the specified page.
39294 */
39295 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
39296   return sqlite3PcachePageRefcount(pPage);
39297 }
39298
39299 #ifdef SQLITE_TEST
39300 /*
39301 ** This routine is used for testing and analysis only.
39302 */
39303 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
39304   static int a[11];
39305   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
39306   a[1] = sqlite3PcachePagecount(pPager->pPCache);
39307   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
39308   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
39309   a[4] = pPager->state;
39310   a[5] = pPager->errCode;
39311   a[6] = pPager->nHit;
39312   a[7] = pPager->nMiss;
39313   a[8] = 0;  /* Used to be pPager->nOvfl */
39314   a[9] = pPager->nRead;
39315   a[10] = pPager->nWrite;
39316   return a;
39317 }
39318 #endif
39319
39320 /*
39321 ** Return true if this is an in-memory pager.
39322 */
39323 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
39324   return MEMDB;
39325 }
39326
39327 /*
39328 ** Check that there are at least nSavepoint savepoints open. If there are
39329 ** currently less than nSavepoints open, then open one or more savepoints
39330 ** to make up the difference. If the number of savepoints is already
39331 ** equal to nSavepoint, then this function is a no-op.
39332 **
39333 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
39334 ** occurs while opening the sub-journal file, then an IO error code is
39335 ** returned. Otherwise, SQLITE_OK.
39336 */
39337 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
39338   int rc = SQLITE_OK;                       /* Return code */
39339   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
39340
39341   if( nSavepoint>nCurrent && pPager->useJournal ){
39342     int ii;                                 /* Iterator variable */
39343     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
39344     int nPage;                              /* Size of database file */
39345
39346     rc = sqlite3PagerPagecount(pPager, &nPage);
39347     if( rc ) return rc;
39348
39349     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
39350     ** if the allocation fails. Otherwise, zero the new portion in case a 
39351     ** malloc failure occurs while populating it in the for(...) loop below.
39352     */
39353     aNew = (PagerSavepoint *)sqlite3Realloc(
39354         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
39355     );
39356     if( !aNew ){
39357       return SQLITE_NOMEM;
39358     }
39359     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
39360     pPager->aSavepoint = aNew;
39361
39362     /* Populate the PagerSavepoint structures just allocated. */
39363     for(ii=nCurrent; ii<nSavepoint; ii++){
39364       aNew[ii].nOrig = nPage;
39365       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
39366         aNew[ii].iOffset = pPager->journalOff;
39367       }else{
39368         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
39369       }
39370       aNew[ii].iSubRec = pPager->nSubRec;
39371       aNew[ii].pInSavepoint = sqlite3BitvecCreate(nPage);
39372       if( !aNew[ii].pInSavepoint ){
39373         return SQLITE_NOMEM;
39374       }
39375       if( pagerUseWal(pPager) ){
39376         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
39377       }
39378       pPager->nSavepoint = ii+1;
39379     }
39380     assert( pPager->nSavepoint==nSavepoint );
39381     assertTruncateConstraint(pPager);
39382   }
39383
39384   return rc;
39385 }
39386
39387 /*
39388 ** This function is called to rollback or release (commit) a savepoint.
39389 ** The savepoint to release or rollback need not be the most recently 
39390 ** created savepoint.
39391 **
39392 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
39393 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
39394 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
39395 ** that have occurred since the specified savepoint was created.
39396 **
39397 ** The savepoint to rollback or release is identified by parameter 
39398 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
39399 ** (the first created). A value of (Pager.nSavepoint-1) means operate
39400 ** on the most recently created savepoint. If iSavepoint is greater than
39401 ** (Pager.nSavepoint-1), then this function is a no-op.
39402 **
39403 ** If a negative value is passed to this function, then the current
39404 ** transaction is rolled back. This is different to calling 
39405 ** sqlite3PagerRollback() because this function does not terminate
39406 ** the transaction or unlock the database, it just restores the 
39407 ** contents of the database to its original state. 
39408 **
39409 ** In any case, all savepoints with an index greater than iSavepoint 
39410 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
39411 ** then savepoint iSavepoint is also destroyed.
39412 **
39413 ** This function may return SQLITE_NOMEM if a memory allocation fails,
39414 ** or an IO error code if an IO error occurs while rolling back a 
39415 ** savepoint. If no errors occur, SQLITE_OK is returned.
39416 */ 
39417 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
39418   int rc = SQLITE_OK;
39419
39420   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
39421   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
39422
39423   if( iSavepoint<pPager->nSavepoint ){
39424     int ii;            /* Iterator variable */
39425     int nNew;          /* Number of remaining savepoints after this op. */
39426
39427     /* Figure out how many savepoints will still be active after this
39428     ** operation. Store this value in nNew. Then free resources associated 
39429     ** with any savepoints that are destroyed by this operation.
39430     */
39431     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
39432     for(ii=nNew; ii<pPager->nSavepoint; ii++){
39433       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39434     }
39435     pPager->nSavepoint = nNew;
39436
39437     /* If this is a release of the outermost savepoint, truncate 
39438     ** the sub-journal to zero bytes in size. */
39439     if( op==SAVEPOINT_RELEASE ){
39440       if( nNew==0 && isOpen(pPager->sjfd) ){
39441         /* Only truncate if it is an in-memory sub-journal. */
39442         if( sqlite3IsMemJournal(pPager->sjfd) ){
39443           rc = sqlite3OsTruncate(pPager->sjfd, 0);
39444           assert( rc==SQLITE_OK );
39445         }
39446         pPager->nSubRec = 0;
39447       }
39448     }
39449     /* Else this is a rollback operation, playback the specified savepoint.
39450     ** If this is a temp-file, it is possible that the journal file has
39451     ** not yet been opened. In this case there have been no changes to
39452     ** the database file, so the playback operation can be skipped.
39453     */
39454     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
39455       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
39456       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
39457       assert(rc!=SQLITE_DONE);
39458     }
39459   
39460   }
39461   return rc;
39462 }
39463
39464 /*
39465 ** Return the full pathname of the database file.
39466 */
39467 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
39468   return pPager->zFilename;
39469 }
39470
39471 /*
39472 ** Return the VFS structure for the pager.
39473 */
39474 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
39475   return pPager->pVfs;
39476 }
39477
39478 /*
39479 ** Return the file handle for the database file associated
39480 ** with the pager.  This might return NULL if the file has
39481 ** not yet been opened.
39482 */
39483 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
39484   return pPager->fd;
39485 }
39486
39487 /*
39488 ** Return the full pathname of the journal file.
39489 */
39490 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
39491   return pPager->zJournal;
39492 }
39493
39494 /*
39495 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
39496 ** if fsync()s are executed normally.
39497 */
39498 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
39499   return pPager->noSync;
39500 }
39501
39502 #ifdef SQLITE_HAS_CODEC
39503 /*
39504 ** Set or retrieve the codec for this pager
39505 */
39506 SQLITE_PRIVATE void sqlite3PagerSetCodec(
39507   Pager *pPager,
39508   void *(*xCodec)(void*,void*,Pgno,int),
39509   void (*xCodecSizeChng)(void*,int,int),
39510   void (*xCodecFree)(void*),
39511   void *pCodec
39512 ){
39513   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
39514   pPager->xCodec = pPager->memDb ? 0 : xCodec;
39515   pPager->xCodecSizeChng = xCodecSizeChng;
39516   pPager->xCodecFree = xCodecFree;
39517   pPager->pCodec = pCodec;
39518   pagerReportSize(pPager);
39519 }
39520 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
39521   return pPager->pCodec;
39522 }
39523 #endif
39524
39525 #ifndef SQLITE_OMIT_AUTOVACUUM
39526 /*
39527 ** Move the page pPg to location pgno in the file.
39528 **
39529 ** There must be no references to the page previously located at
39530 ** pgno (which we call pPgOld) though that page is allowed to be
39531 ** in cache.  If the page previously located at pgno is not already
39532 ** in the rollback journal, it is not put there by by this routine.
39533 **
39534 ** References to the page pPg remain valid. Updating any
39535 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
39536 ** allocated along with the page) is the responsibility of the caller.
39537 **
39538 ** A transaction must be active when this routine is called. It used to be
39539 ** required that a statement transaction was not active, but this restriction
39540 ** has been removed (CREATE INDEX needs to move a page when a statement
39541 ** transaction is active).
39542 **
39543 ** If the fourth argument, isCommit, is non-zero, then this page is being
39544 ** moved as part of a database reorganization just before the transaction 
39545 ** is being committed. In this case, it is guaranteed that the database page 
39546 ** pPg refers to will not be written to again within this transaction.
39547 **
39548 ** This function may return SQLITE_NOMEM or an IO error code if an error
39549 ** occurs. Otherwise, it returns SQLITE_OK.
39550 */
39551 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
39552   PgHdr *pPgOld;               /* The page being overwritten. */
39553   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
39554   int rc;                      /* Return code */
39555   Pgno origPgno;               /* The original page number */
39556
39557   assert( pPg->nRef>0 );
39558
39559   /* In order to be able to rollback, an in-memory database must journal
39560   ** the page we are moving from.
39561   */
39562   if( MEMDB ){
39563     rc = sqlite3PagerWrite(pPg);
39564     if( rc ) return rc;
39565   }
39566
39567   /* If the page being moved is dirty and has not been saved by the latest
39568   ** savepoint, then save the current contents of the page into the 
39569   ** sub-journal now. This is required to handle the following scenario:
39570   **
39571   **   BEGIN;
39572   **     <journal page X, then modify it in memory>
39573   **     SAVEPOINT one;
39574   **       <Move page X to location Y>
39575   **     ROLLBACK TO one;
39576   **
39577   ** If page X were not written to the sub-journal here, it would not
39578   ** be possible to restore its contents when the "ROLLBACK TO one"
39579   ** statement were is processed.
39580   **
39581   ** subjournalPage() may need to allocate space to store pPg->pgno into
39582   ** one or more savepoint bitvecs. This is the reason this function
39583   ** may return SQLITE_NOMEM.
39584   */
39585   if( pPg->flags&PGHDR_DIRTY
39586    && subjRequiresPage(pPg)
39587    && SQLITE_OK!=(rc = subjournalPage(pPg))
39588   ){
39589     return rc;
39590   }
39591
39592   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
39593       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
39594   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
39595
39596   /* If the journal needs to be sync()ed before page pPg->pgno can
39597   ** be written to, store pPg->pgno in local variable needSyncPgno.
39598   **
39599   ** If the isCommit flag is set, there is no need to remember that
39600   ** the journal needs to be sync()ed before database page pPg->pgno 
39601   ** can be written to. The caller has already promised not to write to it.
39602   */
39603   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
39604     needSyncPgno = pPg->pgno;
39605     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
39606     assert( pPg->flags&PGHDR_DIRTY );
39607     assert( pPager->needSync );
39608   }
39609
39610   /* If the cache contains a page with page-number pgno, remove it
39611   ** from its hash chain. Also, if the PgHdr.needSync was set for 
39612   ** page pgno before the 'move' operation, it needs to be retained 
39613   ** for the page moved there.
39614   */
39615   pPg->flags &= ~PGHDR_NEED_SYNC;
39616   pPgOld = pager_lookup(pPager, pgno);
39617   assert( !pPgOld || pPgOld->nRef==1 );
39618   if( pPgOld ){
39619     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
39620     if( MEMDB ){
39621       /* Do not discard pages from an in-memory database since we might
39622       ** need to rollback later.  Just move the page out of the way. */
39623       assert( pPager->dbSizeValid );
39624       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
39625     }else{
39626       sqlite3PcacheDrop(pPgOld);
39627     }
39628   }
39629
39630   origPgno = pPg->pgno;
39631   sqlite3PcacheMove(pPg, pgno);
39632   sqlite3PcacheMakeDirty(pPg);
39633   pPager->dbModified = 1;
39634
39635   if( needSyncPgno ){
39636     /* If needSyncPgno is non-zero, then the journal file needs to be 
39637     ** sync()ed before any data is written to database file page needSyncPgno.
39638     ** Currently, no such page exists in the page-cache and the 
39639     ** "is journaled" bitvec flag has been set. This needs to be remedied by
39640     ** loading the page into the pager-cache and setting the PgHdr.needSync 
39641     ** flag.
39642     **
39643     ** If the attempt to load the page into the page-cache fails, (due
39644     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
39645     ** array. Otherwise, if the page is loaded and written again in
39646     ** this transaction, it may be written to the database file before
39647     ** it is synced into the journal file. This way, it may end up in
39648     ** the journal file twice, but that is not a problem.
39649     **
39650     ** The sqlite3PagerGet() call may cause the journal to sync. So make
39651     ** sure the Pager.needSync flag is set too.
39652     */
39653     PgHdr *pPgHdr;
39654     assert( pPager->needSync );
39655     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
39656     if( rc!=SQLITE_OK ){
39657       if( needSyncPgno<=pPager->dbOrigSize ){
39658         assert( pPager->pTmpSpace!=0 );
39659         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
39660       }
39661       return rc;
39662     }
39663     pPager->needSync = 1;
39664     assert( pPager->noSync==0 && !MEMDB );
39665     pPgHdr->flags |= PGHDR_NEED_SYNC;
39666     sqlite3PcacheMakeDirty(pPgHdr);
39667     sqlite3PagerUnref(pPgHdr);
39668   }
39669
39670   /*
39671   ** For an in-memory database, make sure the original page continues
39672   ** to exist, in case the transaction needs to roll back.  Use pPgOld
39673   ** as the original page since it has already been allocated.
39674   */
39675   if( MEMDB ){
39676     sqlite3PcacheMove(pPgOld, origPgno);
39677     sqlite3PagerUnref(pPgOld);
39678   }
39679
39680   return SQLITE_OK;
39681 }
39682 #endif
39683
39684 /*
39685 ** Return a pointer to the data for the specified page.
39686 */
39687 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
39688   assert( pPg->nRef>0 || pPg->pPager->memDb );
39689   return pPg->pData;
39690 }
39691
39692 /*
39693 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
39694 ** allocated along with the specified page.
39695 */
39696 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
39697   return pPg->pExtra;
39698 }
39699
39700 /*
39701 ** Get/set the locking-mode for this pager. Parameter eMode must be one
39702 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
39703 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
39704 ** the locking-mode is set to the value specified.
39705 **
39706 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
39707 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
39708 ** locking-mode.
39709 */
39710 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
39711   assert( eMode==PAGER_LOCKINGMODE_QUERY
39712             || eMode==PAGER_LOCKINGMODE_NORMAL
39713             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
39714   assert( PAGER_LOCKINGMODE_QUERY<0 );
39715   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
39716   if( eMode>=0 && !pPager->tempFile ){
39717     pPager->exclusiveMode = (u8)eMode;
39718   }
39719   return (int)pPager->exclusiveMode;
39720 }
39721
39722 /*
39723 ** Set the journal-mode for this pager. Parameter eMode must be one of:
39724 **
39725 **    PAGER_JOURNALMODE_DELETE
39726 **    PAGER_JOURNALMODE_TRUNCATE
39727 **    PAGER_JOURNALMODE_PERSIST
39728 **    PAGER_JOURNALMODE_OFF
39729 **    PAGER_JOURNALMODE_MEMORY
39730 **    PAGER_JOURNALMODE_WAL
39731 **
39732 ** The journalmode is set to the value specified if the change is allowed.
39733 ** The change may be disallowed for the following reasons:
39734 **
39735 **   *  An in-memory database can only have its journal_mode set to _OFF
39736 **      or _MEMORY.
39737 **
39738 **   *  Temporary databases cannot have _WAL journalmode.
39739 **
39740 ** The returned indicate the current (possibly updated) journal-mode.
39741 */
39742 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
39743   u8 eOld = pPager->journalMode;    /* Prior journalmode */
39744
39745   /* The eMode parameter is always valid */
39746   assert(      eMode==PAGER_JOURNALMODE_DELETE
39747             || eMode==PAGER_JOURNALMODE_TRUNCATE
39748             || eMode==PAGER_JOURNALMODE_PERSIST
39749             || eMode==PAGER_JOURNALMODE_OFF 
39750             || eMode==PAGER_JOURNALMODE_WAL 
39751             || eMode==PAGER_JOURNALMODE_MEMORY );
39752
39753   /* This routine is only called from the OP_JournalMode opcode, and
39754   ** the logic there will never allow a temporary file to be changed
39755   ** to WAL mode.
39756   */
39757   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
39758
39759   /* Do allow the journalmode of an in-memory database to be set to
39760   ** anything other than MEMORY or OFF
39761   */
39762   if( MEMDB ){
39763     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
39764     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
39765       eMode = eOld;
39766     }
39767   }
39768
39769   if( eMode!=eOld ){
39770     /* When changing between rollback modes, close the journal file prior
39771     ** to the change.  But when changing from a rollback mode to WAL, keep
39772     ** the journal open since there is a rollback-style transaction in play
39773     ** used to convert the version numbers in the btree header.
39774     */
39775     if( isOpen(pPager->jfd) && eMode!=PAGER_JOURNALMODE_WAL ){
39776       sqlite3OsClose(pPager->jfd);
39777     }
39778
39779     /* Change the journal mode. */
39780     pPager->journalMode = (u8)eMode;
39781
39782     /* When transistioning from TRUNCATE or PERSIST to any other journal
39783     ** mode except WAL (and we are not in locking_mode=EXCLUSIVE) then 
39784     ** delete the journal file.
39785     */
39786     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39787     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
39788     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
39789     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
39790     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
39791     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
39792
39793     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
39794     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
39795
39796       /* In this case we would like to delete the journal file. If it is
39797       ** not possible, then that is not a problem. Deleting the journal file
39798       ** here is an optimization only.
39799       **
39800       ** Before deleting the journal file, obtain a RESERVED lock on the
39801       ** database file. This ensures that the journal file is not deleted
39802       ** while it is in use by some other client.
39803       */
39804       int rc = SQLITE_OK;
39805       int state = pPager->state;
39806       if( state<PAGER_SHARED ){
39807         rc = sqlite3PagerSharedLock(pPager);
39808       }
39809       if( pPager->state==PAGER_SHARED ){
39810         assert( rc==SQLITE_OK );
39811         rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
39812       }
39813       if( rc==SQLITE_OK ){
39814         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39815       }
39816       if( rc==SQLITE_OK && state==PAGER_SHARED ){
39817         sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
39818       }else if( state==PAGER_UNLOCK ){
39819         pager_unlock(pPager);
39820       }
39821       assert( state==pPager->state );
39822     }
39823   }
39824
39825   /* Return the new journal mode */
39826   return (int)pPager->journalMode;
39827 }
39828
39829 /*
39830 ** Return the current journal mode.
39831 */
39832 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
39833   return (int)pPager->journalMode;
39834 }
39835
39836 /*
39837 ** Return TRUE if the pager is in a state where it is OK to change the
39838 ** journalmode.  Journalmode changes can only happen when the database
39839 ** is unmodified.
39840 */
39841 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
39842   if( pPager->dbModified ) return 0;
39843   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
39844   return 1;
39845 }
39846
39847 /*
39848 ** Get/set the size-limit used for persistent journal files.
39849 **
39850 ** Setting the size limit to -1 means no limit is enforced.
39851 ** An attempt to set a limit smaller than -1 is a no-op.
39852 */
39853 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
39854   if( iLimit>=-1 ){
39855     pPager->journalSizeLimit = iLimit;
39856   }
39857   return pPager->journalSizeLimit;
39858 }
39859
39860 /*
39861 ** Return a pointer to the pPager->pBackup variable. The backup module
39862 ** in backup.c maintains the content of this variable. This module
39863 ** uses it opaquely as an argument to sqlite3BackupRestart() and
39864 ** sqlite3BackupUpdate() only.
39865 */
39866 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
39867   return &pPager->pBackup;
39868 }
39869
39870 #ifndef SQLITE_OMIT_WAL
39871 /*
39872 ** This function is called when the user invokes "PRAGMA checkpoint".
39873 */
39874 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
39875   int rc = SQLITE_OK;
39876   if( pPager->pWal ){
39877     u8 *zBuf = (u8 *)pPager->pTmpSpace;
39878     rc = sqlite3WalCheckpoint(pPager->pWal,
39879         (pPager->noSync ? 0 : pPager->sync_flags),
39880         pPager->pageSize, zBuf
39881     );
39882   }
39883   return rc;
39884 }
39885
39886 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
39887   return sqlite3WalCallback(pPager->pWal);
39888 }
39889
39890 /*
39891 ** Return true if the underlying VFS for the given pager supports the
39892 ** primitives necessary for write-ahead logging.
39893 */
39894 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
39895   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
39896   return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
39897 }
39898
39899 /*
39900 ** The caller must be holding a SHARED lock on the database file to call
39901 ** this function.
39902 **
39903 ** If the pager passed as the first argument is open on a real database
39904 ** file (not a temp file or an in-memory database), and the WAL file
39905 ** is not already open, make an attempt to open it now. If successful,
39906 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
39907 ** not support the xShmXXX() methods, return an error code. *pisOpen is
39908 ** not modified in either case.
39909 **
39910 ** If the pager is open on a temp-file (or in-memory database), or if
39911 ** the WAL file is already open, set *pisOpen to 1 and return SQLITE_OK
39912 ** without doing anything.
39913 */
39914 SQLITE_PRIVATE int sqlite3PagerOpenWal(
39915   Pager *pPager,                  /* Pager object */
39916   int *pisOpen                    /* OUT: Set to true if call is a no-op */
39917 ){
39918   int rc = SQLITE_OK;             /* Return code */
39919
39920   assert( pPager->state>=PAGER_SHARED );
39921   assert( (pisOpen==0 && !pPager->tempFile && !pPager->pWal) || *pisOpen==0 );
39922
39923   if( !pPager->tempFile && !pPager->pWal ){
39924     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
39925
39926     /* Open the connection to the log file. If this operation fails, 
39927     ** (e.g. due to malloc() failure), unlock the database file and 
39928     ** return an error code.
39929     */
39930     rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
39931     if( rc==SQLITE_OK ){
39932       pPager->journalMode = PAGER_JOURNALMODE_WAL;
39933     }
39934   }else{
39935     *pisOpen = 1;
39936   }
39937
39938   return rc;
39939 }
39940
39941 /*
39942 ** This function is called to close the connection to the log file prior
39943 ** to switching from WAL to rollback mode.
39944 **
39945 ** Before closing the log file, this function attempts to take an 
39946 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
39947 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
39948 ** If successful, the EXCLUSIVE lock is not released before returning.
39949 */
39950 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
39951   int rc = SQLITE_OK;
39952
39953   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
39954
39955   /* If the log file is not already open, but does exist in the file-system,
39956   ** it may need to be checkpointed before the connection can switch to
39957   ** rollback mode. Open it now so this can happen.
39958   */
39959   if( !pPager->pWal ){
39960     int logexists = 0;
39961     rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_SHARED);
39962     if( rc==SQLITE_OK ){
39963       rc = sqlite3OsAccess(
39964           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
39965       );
39966     }
39967     if( rc==SQLITE_OK && logexists ){
39968       rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
39969                           pPager->zWal, &pPager->pWal);
39970     }
39971   }
39972     
39973   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
39974   ** the database file, the log and log-summary files will be deleted.
39975   */
39976   if( rc==SQLITE_OK && pPager->pWal ){
39977     rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_EXCLUSIVE);
39978     if( rc==SQLITE_OK ){
39979       rc = sqlite3WalClose(pPager->pWal,
39980                            (pPager->noSync ? 0 : pPager->sync_flags), 
39981         pPager->pageSize, (u8*)pPager->pTmpSpace
39982       );
39983       pPager->pWal = 0;
39984     }else{
39985       /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
39986       ** that we did get back to SHARED. */
39987       sqlite3OsUnlock(pPager->fd, SQLITE_LOCK_SHARED);
39988     }
39989   }
39990   return rc;
39991 }
39992
39993 #ifdef SQLITE_HAS_CODEC
39994 /*
39995 ** This function is called by the wal module when writing page content
39996 ** into the log file.
39997 **
39998 ** This function returns a pointer to a buffer containing the encrypted
39999 ** page content. If a malloc fails, this function may return NULL.
40000 */
40001 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
40002   void *aData = 0;
40003   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
40004   return aData;
40005 }
40006 #endif /* SQLITE_HAS_CODEC */
40007
40008 #endif /* !SQLITE_OMIT_WAL */
40009
40010 #endif /* SQLITE_OMIT_DISKIO */
40011
40012 /************** End of pager.c ***********************************************/
40013 /************** Begin file wal.c *********************************************/
40014 /*
40015 ** 2010 February 1
40016 **
40017 ** The author disclaims copyright to this source code.  In place of
40018 ** a legal notice, here is a blessing:
40019 **
40020 **    May you do good and not evil.
40021 **    May you find forgiveness for yourself and forgive others.
40022 **    May you share freely, never taking more than you give.
40023 **
40024 *************************************************************************
40025 **
40026 ** This file contains the implementation of a write-ahead log (WAL) used in 
40027 ** "journal_mode=WAL" mode.
40028 **
40029 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
40030 **
40031 ** A WAL file consists of a header followed by zero or more "frames".
40032 ** Each frame records the revised content of a single page from the
40033 ** database file.  All changes to the database are recorded by writing
40034 ** frames into the WAL.  Transactions commit when a frame is written that
40035 ** contains a commit marker.  A single WAL can and usually does record 
40036 ** multiple transactions.  Periodically, the content of the WAL is
40037 ** transferred back into the database file in an operation called a
40038 ** "checkpoint".
40039 **
40040 ** A single WAL file can be used multiple times.  In other words, the
40041 ** WAL can fill up with frames and then be checkpointed and then new
40042 ** frames can overwrite the old ones.  A WAL always grows from beginning
40043 ** toward the end.  Checksums and counters attached to each frame are
40044 ** used to determine which frames within the WAL are valid and which
40045 ** are leftovers from prior checkpoints.
40046 **
40047 ** The WAL header is 32 bytes in size and consists of the following eight
40048 ** big-endian 32-bit unsigned integer values:
40049 **
40050 **     0: Magic number.  0x377f0682 or 0x377f0683
40051 **     4: File format version.  Currently 3007000
40052 **     8: Database page size.  Example: 1024
40053 **    12: Checkpoint sequence number
40054 **    16: Salt-1, random integer incremented with each checkpoint
40055 **    20: Salt-2, a different random integer changing with each ckpt
40056 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
40057 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
40058 **
40059 ** Immediately following the wal-header are zero or more frames. Each
40060 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
40061 ** of page data. The frame-header is six big-endian 32-bit unsigned 
40062 ** integer values, as follows:
40063 **
40064 **     0: Page number.
40065 **     4: For commit records, the size of the database image in pages 
40066 **        after the commit. For all other records, zero.
40067 **     8: Salt-1 (copied from the header)
40068 **    12: Salt-2 (copied from the header)
40069 **    16: Checksum-1.
40070 **    20: Checksum-2.
40071 **
40072 ** A frame is considered valid if and only if the following conditions are
40073 ** true:
40074 **
40075 **    (1) The salt-1 and salt-2 values in the frame-header match
40076 **        salt values in the wal-header
40077 **
40078 **    (2) The checksum values in the final 8 bytes of the frame-header
40079 **        exactly match the checksum computed consecutively on the
40080 **        WAL header and the first 8 bytes and the content of all frames
40081 **        up to and including the current frame.
40082 **
40083 ** The checksum is computed using 32-bit big-endian integers if the
40084 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
40085 ** is computed using little-endian if the magic number is 0x377f0682.
40086 ** The checksum values are always stored in the frame header in a
40087 ** big-endian format regardless of which byte order is used to compute
40088 ** the checksum.  The checksum is computed by interpreting the input as
40089 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
40090 ** algorithm used for the checksum is as follows:
40091 ** 
40092 **   for i from 0 to n-1 step 2:
40093 **     s0 += x[i] + s1;
40094 **     s1 += x[i+1] + s0;
40095 **   endfor
40096 **
40097 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
40098 ** in reverse order (the largest fibonacci weight occurs on the first element
40099 ** of the sequence being summed.)  The s1 value spans all 32-bit 
40100 ** terms of the sequence whereas s0 omits the final term.
40101 **
40102 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
40103 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
40104 ** The VFS.xSync operations serve as write barriers - all writes launched
40105 ** before the xSync must complete before any write that launches after the
40106 ** xSync begins.
40107 **
40108 ** After each checkpoint, the salt-1 value is incremented and the salt-2
40109 ** value is randomized.  This prevents old and new frames in the WAL from
40110 ** being considered valid at the same time and being checkpointing together
40111 ** following a crash.
40112 **
40113 ** READER ALGORITHM
40114 **
40115 ** To read a page from the database (call it page number P), a reader
40116 ** first checks the WAL to see if it contains page P.  If so, then the
40117 ** last valid instance of page P that is a followed by a commit frame
40118 ** or is a commit frame itself becomes the value read.  If the WAL
40119 ** contains no copies of page P that are valid and which are a commit
40120 ** frame or are followed by a commit frame, then page P is read from
40121 ** the database file.
40122 **
40123 ** To start a read transaction, the reader records the index of the last
40124 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
40125 ** for all subsequent read operations.  New transactions can be appended
40126 ** to the WAL, but as long as the reader uses its original mxFrame value
40127 ** and ignores the newly appended content, it will see a consistent snapshot
40128 ** of the database from a single point in time.  This technique allows
40129 ** multiple concurrent readers to view different versions of the database
40130 ** content simultaneously.
40131 **
40132 ** The reader algorithm in the previous paragraphs works correctly, but 
40133 ** because frames for page P can appear anywhere within the WAL, the
40134 ** reader has to scan the entire WAL looking for page P frames.  If the
40135 ** WAL is large (multiple megabytes is typical) that scan can be slow,
40136 ** and read performance suffers.  To overcome this problem, a separate
40137 ** data structure called the wal-index is maintained to expedite the
40138 ** search for frames of a particular page.
40139 ** 
40140 ** WAL-INDEX FORMAT
40141 **
40142 ** Conceptually, the wal-index is shared memory, though VFS implementations
40143 ** might choose to implement the wal-index using a mmapped file.  Because
40144 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
40145 ** on a network filesystem.  All users of the database must be able to
40146 ** share memory.
40147 **
40148 ** The wal-index is transient.  After a crash, the wal-index can (and should
40149 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
40150 ** to either truncate or zero the header of the wal-index when the last
40151 ** connection to it closes.  Because the wal-index is transient, it can
40152 ** use an architecture-specific format; it does not have to be cross-platform.
40153 ** Hence, unlike the database and WAL file formats which store all values
40154 ** as big endian, the wal-index can store multi-byte values in the native
40155 ** byte order of the host computer.
40156 **
40157 ** The purpose of the wal-index is to answer this question quickly:  Given
40158 ** a page number P, return the index of the last frame for page P in the WAL,
40159 ** or return NULL if there are no frames for page P in the WAL.
40160 **
40161 ** The wal-index consists of a header region, followed by an one or
40162 ** more index blocks.  
40163 **
40164 ** The wal-index header contains the total number of frames within the WAL
40165 ** in the the mxFrame field.  
40166 **
40167 ** Each index block except for the first contains information on 
40168 ** HASHTABLE_NPAGE frames. The first index block contains information on
40169 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
40170 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
40171 ** first index block are the same size as all other index blocks in the
40172 ** wal-index.
40173 **
40174 ** Each index block contains two sections, a page-mapping that contains the
40175 ** database page number associated with each wal frame, and a hash-table 
40176 ** that allows readers to query an index block for a specific page number.
40177 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
40178 ** for the first index block) 32-bit page numbers. The first entry in the 
40179 ** first index-block contains the database page number corresponding to the
40180 ** first frame in the WAL file. The first entry in the second index block
40181 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
40182 ** the log, and so on.
40183 **
40184 ** The last index block in a wal-index usually contains less than the full
40185 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
40186 ** depending on the contents of the WAL file. This does not change the
40187 ** allocated size of the page-mapping array - the page-mapping array merely
40188 ** contains unused entries.
40189 **
40190 ** Even without using the hash table, the last frame for page P
40191 ** can be found by scanning the page-mapping sections of each index block
40192 ** starting with the last index block and moving toward the first, and
40193 ** within each index block, starting at the end and moving toward the
40194 ** beginning.  The first entry that equals P corresponds to the frame
40195 ** holding the content for that page.
40196 **
40197 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
40198 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
40199 ** hash table for each page number in the mapping section, so the hash 
40200 ** table is never more than half full.  The expected number of collisions 
40201 ** prior to finding a match is 1.  Each entry of the hash table is an
40202 ** 1-based index of an entry in the mapping section of the same
40203 ** index block.   Let K be the 1-based index of the largest entry in
40204 ** the mapping section.  (For index blocks other than the last, K will
40205 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
40206 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
40207 ** contain a value of 0.
40208 **
40209 ** To look for page P in the hash table, first compute a hash iKey on
40210 ** P as follows:
40211 **
40212 **      iKey = (P * 383) % HASHTABLE_NSLOT
40213 **
40214 ** Then start scanning entries of the hash table, starting with iKey
40215 ** (wrapping around to the beginning when the end of the hash table is
40216 ** reached) until an unused hash slot is found. Let the first unused slot
40217 ** be at index iUnused.  (iUnused might be less than iKey if there was
40218 ** wrap-around.) Because the hash table is never more than half full,
40219 ** the search is guaranteed to eventually hit an unused entry.  Let 
40220 ** iMax be the value between iKey and iUnused, closest to iUnused,
40221 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
40222 ** no hash slot such that aHash[i]==p) then page P is not in the
40223 ** current index block.  Otherwise the iMax-th mapping entry of the
40224 ** current index block corresponds to the last entry that references 
40225 ** page P.
40226 **
40227 ** A hash search begins with the last index block and moves toward the
40228 ** first index block, looking for entries corresponding to page P.  On
40229 ** average, only two or three slots in each index block need to be
40230 ** examined in order to either find the last entry for page P, or to
40231 ** establish that no such entry exists in the block.  Each index block
40232 ** holds over 4000 entries.  So two or three index blocks are sufficient
40233 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
40234 ** comparisons (on average) suffice to either locate a frame in the
40235 ** WAL or to establish that the frame does not exist in the WAL.  This
40236 ** is much faster than scanning the entire 10MB WAL.
40237 **
40238 ** Note that entries are added in order of increasing K.  Hence, one
40239 ** reader might be using some value K0 and a second reader that started
40240 ** at a later time (after additional transactions were added to the WAL
40241 ** and to the wal-index) might be using a different value K1, where K1>K0.
40242 ** Both readers can use the same hash table and mapping section to get
40243 ** the correct result.  There may be entries in the hash table with
40244 ** K>K0 but to the first reader, those entries will appear to be unused
40245 ** slots in the hash table and so the first reader will get an answer as
40246 ** if no values greater than K0 had ever been inserted into the hash table
40247 ** in the first place - which is what reader one wants.  Meanwhile, the
40248 ** second reader using K1 will see additional values that were inserted
40249 ** later, which is exactly what reader two wants.  
40250 **
40251 ** When a rollback occurs, the value of K is decreased. Hash table entries
40252 ** that correspond to frames greater than the new K value are removed
40253 ** from the hash table at this point.
40254 */
40255 #ifndef SQLITE_OMIT_WAL
40256
40257
40258 /*
40259 ** Trace output macros
40260 */
40261 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
40262 SQLITE_PRIVATE int sqlite3WalTrace = 0;
40263 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
40264 #else
40265 # define WALTRACE(X)
40266 #endif
40267
40268 /*
40269 ** The maximum (and only) versions of the wal and wal-index formats
40270 ** that may be interpreted by this version of SQLite.
40271 **
40272 ** If a client begins recovering a WAL file and finds that (a) the checksum
40273 ** values in the wal-header are correct and (b) the version field is not
40274 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
40275 **
40276 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
40277 ** checksum test is successful) and finds that the version field is not
40278 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
40279 ** returns SQLITE_CANTOPEN.
40280 */
40281 #define WAL_MAX_VERSION      3007000
40282 #define WALINDEX_MAX_VERSION 3007000
40283
40284 /*
40285 ** Indices of various locking bytes.   WAL_NREADER is the number
40286 ** of available reader locks and should be at least 3.
40287 */
40288 #define WAL_WRITE_LOCK         0
40289 #define WAL_ALL_BUT_WRITE      1
40290 #define WAL_CKPT_LOCK          1
40291 #define WAL_RECOVER_LOCK       2
40292 #define WAL_READ_LOCK(I)       (3+(I))
40293 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
40294
40295
40296 /* Object declarations */
40297 typedef struct WalIndexHdr WalIndexHdr;
40298 typedef struct WalIterator WalIterator;
40299 typedef struct WalCkptInfo WalCkptInfo;
40300
40301
40302 /*
40303 ** The following object holds a copy of the wal-index header content.
40304 **
40305 ** The actual header in the wal-index consists of two copies of this
40306 ** object.
40307 */
40308 struct WalIndexHdr {
40309   u32 iVersion;                   /* Wal-index version */
40310   u32 unused;                     /* Unused (padding) field */
40311   u32 iChange;                    /* Counter incremented each transaction */
40312   u8 isInit;                      /* 1 when initialized */
40313   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
40314   u16 szPage;                     /* Database page size in bytes */
40315   u32 mxFrame;                    /* Index of last valid frame in the WAL */
40316   u32 nPage;                      /* Size of database in pages */
40317   u32 aFrameCksum[2];             /* Checksum of last frame in log */
40318   u32 aSalt[2];                   /* Two salt values copied from WAL header */
40319   u32 aCksum[2];                  /* Checksum over all prior fields */
40320 };
40321
40322 /*
40323 ** A copy of the following object occurs in the wal-index immediately
40324 ** following the second copy of the WalIndexHdr.  This object stores
40325 ** information used by checkpoint.
40326 **
40327 ** nBackfill is the number of frames in the WAL that have been written
40328 ** back into the database. (We call the act of moving content from WAL to
40329 ** database "backfilling".)  The nBackfill number is never greater than
40330 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
40331 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
40332 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
40333 ** mxFrame back to zero when the WAL is reset.
40334 **
40335 ** There is one entry in aReadMark[] for each reader lock.  If a reader
40336 ** holds read-lock K, then the value in aReadMark[K] is no greater than
40337 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
40338 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
40339 ** a special case; its value is never used and it exists as a place-holder
40340 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
40341 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
40342 ** directly from the database.
40343 **
40344 ** The value of aReadMark[K] may only be changed by a thread that
40345 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
40346 ** aReadMark[K] cannot changed while there is a reader is using that mark
40347 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
40348 **
40349 ** The checkpointer may only transfer frames from WAL to database where
40350 ** the frame numbers are less than or equal to every aReadMark[] that is
40351 ** in use (that is, every aReadMark[j] for which there is a corresponding
40352 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
40353 ** largest value and will increase an unused aReadMark[] to mxFrame if there
40354 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
40355 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
40356 ** in the WAL has been backfilled into the database) then new readers
40357 ** will choose aReadMark[0] which has value 0 and hence such reader will
40358 ** get all their all content directly from the database file and ignore 
40359 ** the WAL.
40360 **
40361 ** Writers normally append new frames to the end of the WAL.  However,
40362 ** if nBackfill equals mxFrame (meaning that all WAL content has been
40363 ** written back into the database) and if no readers are using the WAL
40364 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
40365 ** the writer will first "reset" the WAL back to the beginning and start
40366 ** writing new content beginning at frame 1.
40367 **
40368 ** We assume that 32-bit loads are atomic and so no locks are needed in
40369 ** order to read from any aReadMark[] entries.
40370 */
40371 struct WalCkptInfo {
40372   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
40373   u32 aReadMark[WAL_NREADER];     /* Reader marks */
40374 };
40375 #define READMARK_NOT_USED  0xffffffff
40376
40377
40378 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
40379 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
40380 ** only support mandatory file-locks, we do not read or write data
40381 ** from the region of the file on which locks are applied.
40382 */
40383 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
40384 #define WALINDEX_LOCK_RESERVED 16
40385 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
40386
40387 /* Size of header before each frame in wal */
40388 #define WAL_FRAME_HDRSIZE 24
40389
40390 /* Size of write ahead log header, including checksum. */
40391 /* #define WAL_HDRSIZE 24 */
40392 #define WAL_HDRSIZE 32
40393
40394 /* WAL magic value. Either this value, or the same value with the least
40395 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
40396 ** big-endian format in the first 4 bytes of a WAL file.
40397 **
40398 ** If the LSB is set, then the checksums for each frame within the WAL
40399 ** file are calculated by treating all data as an array of 32-bit 
40400 ** big-endian words. Otherwise, they are calculated by interpreting 
40401 ** all data as 32-bit little-endian words.
40402 */
40403 #define WAL_MAGIC 0x377f0682
40404
40405 /*
40406 ** Return the offset of frame iFrame in the write-ahead log file, 
40407 ** assuming a database page size of szPage bytes. The offset returned
40408 ** is to the start of the write-ahead log frame-header.
40409 */
40410 #define walFrameOffset(iFrame, szPage) (                               \
40411   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
40412 )
40413
40414 /*
40415 ** An open write-ahead log file is represented by an instance of the
40416 ** following object.
40417 */
40418 struct Wal {
40419   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
40420   sqlite3_file *pDbFd;       /* File handle for the database file */
40421   sqlite3_file *pWalFd;      /* File handle for WAL file */
40422   u32 iCallback;             /* Value to pass to log callback (or 0) */
40423   int nWiData;               /* Size of array apWiData */
40424   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
40425   u16 szPage;                /* Database page size */
40426   i16 readLock;              /* Which read lock is being held.  -1 for none */
40427   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
40428   u8 writeLock;              /* True if in a write transaction */
40429   u8 ckptLock;               /* True if holding a checkpoint lock */
40430   u8 readOnly;               /* True if the WAL file is open read-only */
40431   WalIndexHdr hdr;           /* Wal-index header for current transaction */
40432   const char *zWalName;      /* Name of WAL file */
40433   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
40434 #ifdef SQLITE_DEBUG
40435   u8 lockError;              /* True if a locking error has occurred */
40436 #endif
40437 };
40438
40439 /*
40440 ** Each page of the wal-index mapping contains a hash-table made up of
40441 ** an array of HASHTABLE_NSLOT elements of the following type.
40442 */
40443 typedef u16 ht_slot;
40444
40445 /*
40446 ** This structure is used to implement an iterator that loops through
40447 ** all frames in the WAL in database page order. Where two or more frames
40448 ** correspond to the same database page, the iterator visits only the 
40449 ** frame most recently written to the WAL (in other words, the frame with
40450 ** the largest index).
40451 **
40452 ** The internals of this structure are only accessed by:
40453 **
40454 **   walIteratorInit() - Create a new iterator,
40455 **   walIteratorNext() - Step an iterator,
40456 **   walIteratorFree() - Free an iterator.
40457 **
40458 ** This functionality is used by the checkpoint code (see walCheckpoint()).
40459 */
40460 struct WalIterator {
40461   int iPrior;                     /* Last result returned from the iterator */
40462   int nSegment;                   /* Size of the aSegment[] array */
40463   struct WalSegment {
40464     int iNext;                    /* Next slot in aIndex[] not yet returned */
40465     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
40466     u32 *aPgno;                   /* Array of page numbers. */
40467     int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
40468     int iZero;                    /* Frame number associated with aPgno[0] */
40469   } aSegment[1];                  /* One for every 32KB page in the WAL */
40470 };
40471
40472 /*
40473 ** Define the parameters of the hash tables in the wal-index file. There
40474 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
40475 ** wal-index.
40476 **
40477 ** Changing any of these constants will alter the wal-index format and
40478 ** create incompatibilities.
40479 */
40480 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
40481 #define HASHTABLE_HASH_1     383                  /* Should be prime */
40482 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
40483
40484 /* 
40485 ** The block of page numbers associated with the first hash-table in a
40486 ** wal-index is smaller than usual. This is so that there is a complete
40487 ** hash-table on each aligned 32KB page of the wal-index.
40488 */
40489 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
40490
40491 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
40492 #define WALINDEX_PGSZ   (                                         \
40493     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
40494 )
40495
40496 /*
40497 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
40498 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
40499 ** numbered from zero.
40500 **
40501 ** If this call is successful, *ppPage is set to point to the wal-index
40502 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
40503 ** then an SQLite error code is returned and *ppPage is set to 0.
40504 */
40505 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
40506   int rc = SQLITE_OK;
40507
40508   /* Enlarge the pWal->apWiData[] array if required */
40509   if( pWal->nWiData<=iPage ){
40510     int nByte = sizeof(u32*)*(iPage+1);
40511     volatile u32 **apNew;
40512     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
40513     if( !apNew ){
40514       *ppPage = 0;
40515       return SQLITE_NOMEM;
40516     }
40517     memset((void*)&apNew[pWal->nWiData], 0,
40518            sizeof(u32*)*(iPage+1-pWal->nWiData));
40519     pWal->apWiData = apNew;
40520     pWal->nWiData = iPage+1;
40521   }
40522
40523   /* Request a pointer to the required page from the VFS */
40524   if( pWal->apWiData[iPage]==0 ){
40525     rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
40526         pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
40527     );
40528   }
40529
40530   *ppPage = pWal->apWiData[iPage];
40531   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
40532   return rc;
40533 }
40534
40535 /*
40536 ** Return a pointer to the WalCkptInfo structure in the wal-index.
40537 */
40538 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
40539   assert( pWal->nWiData>0 && pWal->apWiData[0] );
40540   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
40541 }
40542
40543 /*
40544 ** Return a pointer to the WalIndexHdr structure in the wal-index.
40545 */
40546 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
40547   assert( pWal->nWiData>0 && pWal->apWiData[0] );
40548   return (volatile WalIndexHdr*)pWal->apWiData[0];
40549 }
40550
40551 /*
40552 ** The argument to this macro must be of type u32. On a little-endian
40553 ** architecture, it returns the u32 value that results from interpreting
40554 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
40555 ** returns the value that would be produced by intepreting the 4 bytes
40556 ** of the input value as a little-endian integer.
40557 */
40558 #define BYTESWAP32(x) ( \
40559     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
40560   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
40561 )
40562
40563 /*
40564 ** Generate or extend an 8 byte checksum based on the data in 
40565 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
40566 ** initial values of 0 and 0 if aIn==NULL).
40567 **
40568 ** The checksum is written back into aOut[] before returning.
40569 **
40570 ** nByte must be a positive multiple of 8.
40571 */
40572 static void walChecksumBytes(
40573   int nativeCksum, /* True for native byte-order, false for non-native */
40574   u8 *a,           /* Content to be checksummed */
40575   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
40576   const u32 *aIn,  /* Initial checksum value input */
40577   u32 *aOut        /* OUT: Final checksum value output */
40578 ){
40579   u32 s1, s2;
40580   u32 *aData = (u32 *)a;
40581   u32 *aEnd = (u32 *)&a[nByte];
40582
40583   if( aIn ){
40584     s1 = aIn[0];
40585     s2 = aIn[1];
40586   }else{
40587     s1 = s2 = 0;
40588   }
40589
40590   assert( nByte>=8 );
40591   assert( (nByte&0x00000007)==0 );
40592
40593   if( nativeCksum ){
40594     do {
40595       s1 += *aData++ + s2;
40596       s2 += *aData++ + s1;
40597     }while( aData<aEnd );
40598   }else{
40599     do {
40600       s1 += BYTESWAP32(aData[0]) + s2;
40601       s2 += BYTESWAP32(aData[1]) + s1;
40602       aData += 2;
40603     }while( aData<aEnd );
40604   }
40605
40606   aOut[0] = s1;
40607   aOut[1] = s2;
40608 }
40609
40610 /*
40611 ** Write the header information in pWal->hdr into the wal-index.
40612 **
40613 ** The checksum on pWal->hdr is updated before it is written.
40614 */
40615 static void walIndexWriteHdr(Wal *pWal){
40616   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
40617   const int nCksum = offsetof(WalIndexHdr, aCksum);
40618
40619   assert( pWal->writeLock );
40620   pWal->hdr.isInit = 1;
40621   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
40622   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
40623   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40624   sqlite3OsShmBarrier(pWal->pDbFd);
40625   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40626 }
40627
40628 /*
40629 ** This function encodes a single frame header and writes it to a buffer
40630 ** supplied by the caller. A frame-header is made up of a series of 
40631 ** 4-byte big-endian integers, as follows:
40632 **
40633 **     0: Page number.
40634 **     4: For commit records, the size of the database image in pages 
40635 **        after the commit. For all other records, zero.
40636 **     8: Salt-1 (copied from the wal-header)
40637 **    12: Salt-2 (copied from the wal-header)
40638 **    16: Checksum-1.
40639 **    20: Checksum-2.
40640 */
40641 static void walEncodeFrame(
40642   Wal *pWal,                      /* The write-ahead log */
40643   u32 iPage,                      /* Database page number for frame */
40644   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
40645   u8 *aData,                      /* Pointer to page data */
40646   u8 *aFrame                      /* OUT: Write encoded frame here */
40647 ){
40648   int nativeCksum;                /* True for native byte-order checksums */
40649   u32 *aCksum = pWal->hdr.aFrameCksum;
40650   assert( WAL_FRAME_HDRSIZE==24 );
40651   sqlite3Put4byte(&aFrame[0], iPage);
40652   sqlite3Put4byte(&aFrame[4], nTruncate);
40653   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
40654
40655   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40656   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40657   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40658
40659   sqlite3Put4byte(&aFrame[16], aCksum[0]);
40660   sqlite3Put4byte(&aFrame[20], aCksum[1]);
40661 }
40662
40663 /*
40664 ** Check to see if the frame with header in aFrame[] and content
40665 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
40666 ** *pnTruncate and return true.  Return if the frame is not valid.
40667 */
40668 static int walDecodeFrame(
40669   Wal *pWal,                      /* The write-ahead log */
40670   u32 *piPage,                    /* OUT: Database page number for frame */
40671   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
40672   u8 *aData,                      /* Pointer to page data (for checksum) */
40673   u8 *aFrame                      /* Frame data */
40674 ){
40675   int nativeCksum;                /* True for native byte-order checksums */
40676   u32 *aCksum = pWal->hdr.aFrameCksum;
40677   u32 pgno;                       /* Page number of the frame */
40678   assert( WAL_FRAME_HDRSIZE==24 );
40679
40680   /* A frame is only valid if the salt values in the frame-header
40681   ** match the salt values in the wal-header. 
40682   */
40683   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
40684     return 0;
40685   }
40686
40687   /* A frame is only valid if the page number is creater than zero.
40688   */
40689   pgno = sqlite3Get4byte(&aFrame[0]);
40690   if( pgno==0 ){
40691     return 0;
40692   }
40693
40694   /* A frame is only valid if a checksum of the WAL header,
40695   ** all prior frams, the first 16 bytes of this frame-header, 
40696   ** and the frame-data matches the checksum in the last 8 
40697   ** bytes of this frame-header.
40698   */
40699   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40700   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40701   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40702   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
40703    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
40704   ){
40705     /* Checksum failed. */
40706     return 0;
40707   }
40708
40709   /* If we reach this point, the frame is valid.  Return the page number
40710   ** and the new database size.
40711   */
40712   *piPage = pgno;
40713   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
40714   return 1;
40715 }
40716
40717
40718 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
40719 /*
40720 ** Names of locks.  This routine is used to provide debugging output and is not
40721 ** a part of an ordinary build.
40722 */
40723 static const char *walLockName(int lockIdx){
40724   if( lockIdx==WAL_WRITE_LOCK ){
40725     return "WRITE-LOCK";
40726   }else if( lockIdx==WAL_CKPT_LOCK ){
40727     return "CKPT-LOCK";
40728   }else if( lockIdx==WAL_RECOVER_LOCK ){
40729     return "RECOVER-LOCK";
40730   }else{
40731     static char zName[15];
40732     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
40733                      lockIdx-WAL_READ_LOCK(0));
40734     return zName;
40735   }
40736 }
40737 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
40738     
40739
40740 /*
40741 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
40742 ** A lock cannot be moved directly between shared and exclusive - it must go
40743 ** through the unlocked state first.
40744 **
40745 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
40746 */
40747 static int walLockShared(Wal *pWal, int lockIdx){
40748   int rc;
40749   if( pWal->exclusiveMode ) return SQLITE_OK;
40750   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40751                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
40752   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
40753             walLockName(lockIdx), rc ? "failed" : "ok"));
40754   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40755   return rc;
40756 }
40757 static void walUnlockShared(Wal *pWal, int lockIdx){
40758   if( pWal->exclusiveMode ) return;
40759   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40760                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
40761   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
40762 }
40763 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
40764   int rc;
40765   if( pWal->exclusiveMode ) return SQLITE_OK;
40766   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40767                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
40768   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
40769             walLockName(lockIdx), n, rc ? "failed" : "ok"));
40770   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40771   return rc;
40772 }
40773 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
40774   if( pWal->exclusiveMode ) return;
40775   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40776                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
40777   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
40778              walLockName(lockIdx), n));
40779 }
40780
40781 /*
40782 ** Compute a hash on a page number.  The resulting hash value must land
40783 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
40784 ** the hash to the next value in the event of a collision.
40785 */
40786 static int walHash(u32 iPage){
40787   assert( iPage>0 );
40788   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
40789   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
40790 }
40791 static int walNextHash(int iPriorHash){
40792   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
40793 }
40794
40795 /* 
40796 ** Return pointers to the hash table and page number array stored on
40797 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
40798 ** numbered starting from 0.
40799 **
40800 ** Set output variable *paHash to point to the start of the hash table
40801 ** in the wal-index file. Set *piZero to one less than the frame 
40802 ** number of the first frame indexed by this hash table. If a
40803 ** slot in the hash table is set to N, it refers to frame number 
40804 ** (*piZero+N) in the log.
40805 **
40806 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
40807 ** first frame indexed by the hash table, frame (*piZero+1).
40808 */
40809 static int walHashGet(
40810   Wal *pWal,                      /* WAL handle */
40811   int iHash,                      /* Find the iHash'th table */
40812   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
40813   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
40814   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
40815 ){
40816   int rc;                         /* Return code */
40817   volatile u32 *aPgno;
40818
40819   rc = walIndexPage(pWal, iHash, &aPgno);
40820   assert( rc==SQLITE_OK || iHash>0 );
40821
40822   if( rc==SQLITE_OK ){
40823     u32 iZero;
40824     volatile ht_slot *aHash;
40825
40826     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
40827     if( iHash==0 ){
40828       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
40829       iZero = 0;
40830     }else{
40831       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
40832     }
40833   
40834     *paPgno = &aPgno[-1];
40835     *paHash = aHash;
40836     *piZero = iZero;
40837   }
40838   return rc;
40839 }
40840
40841 /*
40842 ** Return the number of the wal-index page that contains the hash-table
40843 ** and page-number array that contain entries corresponding to WAL frame
40844 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
40845 ** are numbered starting from 0.
40846 */
40847 static int walFramePage(u32 iFrame){
40848   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
40849   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
40850        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
40851        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
40852        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
40853        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
40854   );
40855   return iHash;
40856 }
40857
40858 /*
40859 ** Return the page number associated with frame iFrame in this WAL.
40860 */
40861 static u32 walFramePgno(Wal *pWal, u32 iFrame){
40862   int iHash = walFramePage(iFrame);
40863   if( iHash==0 ){
40864     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
40865   }
40866   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
40867 }
40868
40869 /*
40870 ** Remove entries from the hash table that point to WAL slots greater
40871 ** than pWal->hdr.mxFrame.
40872 **
40873 ** This function is called whenever pWal->hdr.mxFrame is decreased due
40874 ** to a rollback or savepoint.
40875 **
40876 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
40877 ** updated.  Any later hash tables will be automatically cleared when
40878 ** pWal->hdr.mxFrame advances to the point where those hash tables are
40879 ** actually needed.
40880 */
40881 static void walCleanupHash(Wal *pWal){
40882   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
40883   volatile u32 *aPgno = 0;        /* Page number array for hash table */
40884   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
40885   int iLimit = 0;                 /* Zero values greater than this */
40886   int nByte;                      /* Number of bytes to zero in aPgno[] */
40887   int i;                          /* Used to iterate through aHash[] */
40888
40889   assert( pWal->writeLock );
40890   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
40891   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
40892   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
40893
40894   if( pWal->hdr.mxFrame==0 ) return;
40895
40896   /* Obtain pointers to the hash-table and page-number array containing 
40897   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
40898   ** that the page said hash-table and array reside on is already mapped.
40899   */
40900   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
40901   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
40902   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
40903
40904   /* Zero all hash-table entries that correspond to frame numbers greater
40905   ** than pWal->hdr.mxFrame.
40906   */
40907   iLimit = pWal->hdr.mxFrame - iZero;
40908   assert( iLimit>0 );
40909   for(i=0; i<HASHTABLE_NSLOT; i++){
40910     if( aHash[i]>iLimit ){
40911       aHash[i] = 0;
40912     }
40913   }
40914   
40915   /* Zero the entries in the aPgno array that correspond to frames with
40916   ** frame numbers greater than pWal->hdr.mxFrame. 
40917   */
40918   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
40919   memset((void *)&aPgno[iLimit+1], 0, nByte);
40920
40921 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40922   /* Verify that the every entry in the mapping region is still reachable
40923   ** via the hash table even after the cleanup.
40924   */
40925   if( iLimit ){
40926     int i;           /* Loop counter */
40927     int iKey;        /* Hash key */
40928     for(i=1; i<=iLimit; i++){
40929       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
40930         if( aHash[iKey]==i ) break;
40931       }
40932       assert( aHash[iKey]==i );
40933     }
40934   }
40935 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
40936 }
40937
40938
40939 /*
40940 ** Set an entry in the wal-index that will map database page number
40941 ** pPage into WAL frame iFrame.
40942 */
40943 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
40944   int rc;                         /* Return code */
40945   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
40946   volatile u32 *aPgno = 0;        /* Page number array */
40947   volatile ht_slot *aHash = 0;    /* Hash table */
40948
40949   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
40950
40951   /* Assuming the wal-index file was successfully mapped, populate the
40952   ** page number array and hash table entry.
40953   */
40954   if( rc==SQLITE_OK ){
40955     int iKey;                     /* Hash table key */
40956     int idx;                      /* Value to write to hash-table slot */
40957     int nCollide;                 /* Number of hash collisions */
40958
40959     idx = iFrame - iZero;
40960     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
40961     
40962     /* If this is the first entry to be added to this hash-table, zero the
40963     ** entire hash table and aPgno[] array before proceding. 
40964     */
40965     if( idx==1 ){
40966       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
40967       memset((void*)&aPgno[1], 0, nByte);
40968     }
40969
40970     /* If the entry in aPgno[] is already set, then the previous writer
40971     ** must have exited unexpectedly in the middle of a transaction (after
40972     ** writing one or more dirty pages to the WAL to free up memory). 
40973     ** Remove the remnants of that writers uncommitted transaction from 
40974     ** the hash-table before writing any new entries.
40975     */
40976     if( aPgno[idx] ){
40977       walCleanupHash(pWal);
40978       assert( !aPgno[idx] );
40979     }
40980
40981     /* Write the aPgno[] array entry and the hash-table slot. */
40982     nCollide = idx;
40983     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
40984       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
40985     }
40986     aPgno[idx] = iPage;
40987     aHash[iKey] = (ht_slot)idx;
40988
40989 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40990     /* Verify that the number of entries in the hash table exactly equals
40991     ** the number of entries in the mapping region.
40992     */
40993     {
40994       int i;           /* Loop counter */
40995       int nEntry = 0;  /* Number of entries in the hash table */
40996       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
40997       assert( nEntry==idx );
40998     }
40999
41000     /* Verify that the every entry in the mapping region is reachable
41001     ** via the hash table.  This turns out to be a really, really expensive
41002     ** thing to check, so only do this occasionally - not on every
41003     ** iteration.
41004     */
41005     if( (idx&0x3ff)==0 ){
41006       int i;           /* Loop counter */
41007       for(i=1; i<=idx; i++){
41008         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41009           if( aHash[iKey]==i ) break;
41010         }
41011         assert( aHash[iKey]==i );
41012       }
41013     }
41014 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41015   }
41016
41017
41018   return rc;
41019 }
41020
41021
41022 /*
41023 ** Recover the wal-index by reading the write-ahead log file. 
41024 **
41025 ** This routine first tries to establish an exclusive lock on the
41026 ** wal-index to prevent other threads/processes from doing anything
41027 ** with the WAL or wal-index while recovery is running.  The
41028 ** WAL_RECOVER_LOCK is also held so that other threads will know
41029 ** that this thread is running recovery.  If unable to establish
41030 ** the necessary locks, this routine returns SQLITE_BUSY.
41031 */
41032 static int walIndexRecover(Wal *pWal){
41033   int rc;                         /* Return Code */
41034   i64 nSize;                      /* Size of log file */
41035   u32 aFrameCksum[2] = {0, 0};
41036   int iLock;                      /* Lock offset to lock for checkpoint */
41037   int nLock;                      /* Number of locks to hold */
41038
41039   /* Obtain an exclusive lock on all byte in the locking range not already
41040   ** locked by the caller. The caller is guaranteed to have locked the
41041   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
41042   ** If successful, the same bytes that are locked here are unlocked before
41043   ** this function returns.
41044   */
41045   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
41046   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
41047   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
41048   assert( pWal->writeLock );
41049   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
41050   nLock = SQLITE_SHM_NLOCK - iLock;
41051   rc = walLockExclusive(pWal, iLock, nLock);
41052   if( rc ){
41053     return rc;
41054   }
41055   WALTRACE(("WAL%p: recovery begin...\n", pWal));
41056
41057   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
41058
41059   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
41060   if( rc!=SQLITE_OK ){
41061     goto recovery_error;
41062   }
41063
41064   if( nSize>WAL_HDRSIZE ){
41065     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
41066     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
41067     int szFrame;                  /* Number of bytes in buffer aFrame[] */
41068     u8 *aData;                    /* Pointer to data part of aFrame buffer */
41069     int iFrame;                   /* Index of last frame read */
41070     i64 iOffset;                  /* Next offset to read from log file */
41071     int szPage;                   /* Page size according to the log */
41072     u32 magic;                    /* Magic value read from WAL header */
41073     u32 version;                  /* Magic value read from WAL header */
41074
41075     /* Read in the WAL header. */
41076     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
41077     if( rc!=SQLITE_OK ){
41078       goto recovery_error;
41079     }
41080
41081     /* If the database page size is not a power of two, or is greater than
41082     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
41083     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
41084     ** WAL file.
41085     */
41086     magic = sqlite3Get4byte(&aBuf[0]);
41087     szPage = sqlite3Get4byte(&aBuf[8]);
41088     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
41089      || szPage&(szPage-1) 
41090      || szPage>SQLITE_MAX_PAGE_SIZE 
41091      || szPage<512 
41092     ){
41093       goto finished;
41094     }
41095     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
41096     pWal->szPage = (u16)szPage;
41097     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
41098     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
41099
41100     /* Verify that the WAL header checksum is correct */
41101     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
41102         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
41103     );
41104     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
41105      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
41106     ){
41107       goto finished;
41108     }
41109
41110     /* Verify that the version number on the WAL format is one that
41111     ** are able to understand */
41112     version = sqlite3Get4byte(&aBuf[4]);
41113     if( version!=WAL_MAX_VERSION ){
41114       rc = SQLITE_CANTOPEN_BKPT;
41115       goto finished;
41116     }
41117
41118     /* Malloc a buffer to read frames into. */
41119     szFrame = szPage + WAL_FRAME_HDRSIZE;
41120     aFrame = (u8 *)sqlite3_malloc(szFrame);
41121     if( !aFrame ){
41122       rc = SQLITE_NOMEM;
41123       goto recovery_error;
41124     }
41125     aData = &aFrame[WAL_FRAME_HDRSIZE];
41126
41127     /* Read all frames from the log file. */
41128     iFrame = 0;
41129     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
41130       u32 pgno;                   /* Database page number for frame */
41131       u32 nTruncate;              /* dbsize field from frame header */
41132       int isValid;                /* True if this frame is valid */
41133
41134       /* Read and decode the next log frame. */
41135       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
41136       if( rc!=SQLITE_OK ) break;
41137       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
41138       if( !isValid ) break;
41139       rc = walIndexAppend(pWal, ++iFrame, pgno);
41140       if( rc!=SQLITE_OK ) break;
41141
41142       /* If nTruncate is non-zero, this is a commit record. */
41143       if( nTruncate ){
41144         pWal->hdr.mxFrame = iFrame;
41145         pWal->hdr.nPage = nTruncate;
41146         pWal->hdr.szPage = (u16)szPage;
41147         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
41148         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
41149       }
41150     }
41151
41152     sqlite3_free(aFrame);
41153   }
41154
41155 finished:
41156   if( rc==SQLITE_OK ){
41157     volatile WalCkptInfo *pInfo;
41158     int i;
41159     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
41160     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
41161     walIndexWriteHdr(pWal);
41162
41163     /* Reset the checkpoint-header. This is safe because this thread is 
41164     ** currently holding locks that exclude all other readers, writers and
41165     ** checkpointers.
41166     */
41167     pInfo = walCkptInfo(pWal);
41168     pInfo->nBackfill = 0;
41169     pInfo->aReadMark[0] = 0;
41170     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
41171   }
41172
41173 recovery_error:
41174   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
41175   walUnlockExclusive(pWal, iLock, nLock);
41176   return rc;
41177 }
41178
41179 /*
41180 ** Close an open wal-index.
41181 */
41182 static void walIndexClose(Wal *pWal, int isDelete){
41183   sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
41184 }
41185
41186 /* 
41187 ** Open a connection to the WAL file zWalName. The database file must 
41188 ** already be opened on connection pDbFd. The buffer that zWalName points
41189 ** to must remain valid for the lifetime of the returned Wal* handle.
41190 **
41191 ** A SHARED lock should be held on the database file when this function
41192 ** is called. The purpose of this SHARED lock is to prevent any other
41193 ** client from unlinking the WAL or wal-index file. If another process
41194 ** were to do this just after this client opened one of these files, the
41195 ** system would be badly broken.
41196 **
41197 ** If the log file is successfully opened, SQLITE_OK is returned and 
41198 ** *ppWal is set to point to a new WAL handle. If an error occurs,
41199 ** an SQLite error code is returned and *ppWal is left unmodified.
41200 */
41201 SQLITE_PRIVATE int sqlite3WalOpen(
41202   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
41203   sqlite3_file *pDbFd,            /* The open database file */
41204   const char *zWalName,           /* Name of the WAL file */
41205   Wal **ppWal                     /* OUT: Allocated Wal handle */
41206 ){
41207   int rc;                         /* Return Code */
41208   Wal *pRet;                      /* Object to allocate and return */
41209   int flags;                      /* Flags passed to OsOpen() */
41210
41211   assert( zWalName && zWalName[0] );
41212   assert( pDbFd );
41213
41214   /* In the amalgamation, the os_unix.c and os_win.c source files come before
41215   ** this source file.  Verify that the #defines of the locking byte offsets
41216   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
41217   */
41218 #ifdef WIN_SHM_BASE
41219   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
41220 #endif
41221 #ifdef UNIX_SHM_BASE
41222   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
41223 #endif
41224
41225
41226   /* Allocate an instance of struct Wal to return. */
41227   *ppWal = 0;
41228   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
41229   if( !pRet ){
41230     return SQLITE_NOMEM;
41231   }
41232
41233   pRet->pVfs = pVfs;
41234   pRet->pWalFd = (sqlite3_file *)&pRet[1];
41235   pRet->pDbFd = pDbFd;
41236   pRet->readLock = -1;
41237   pRet->zWalName = zWalName;
41238
41239   /* Open file handle on the write-ahead log file. */
41240   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
41241   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
41242   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
41243     pRet->readOnly = 1;
41244   }
41245
41246   if( rc!=SQLITE_OK ){
41247     walIndexClose(pRet, 0);
41248     sqlite3OsClose(pRet->pWalFd);
41249     sqlite3_free(pRet);
41250   }else{
41251     *ppWal = pRet;
41252     WALTRACE(("WAL%d: opened\n", pRet));
41253   }
41254   return rc;
41255 }
41256
41257 /*
41258 ** Find the smallest page number out of all pages held in the WAL that
41259 ** has not been returned by any prior invocation of this method on the
41260 ** same WalIterator object.   Write into *piFrame the frame index where
41261 ** that page was last written into the WAL.  Write into *piPage the page
41262 ** number.
41263 **
41264 ** Return 0 on success.  If there are no pages in the WAL with a page
41265 ** number larger than *piPage, then return 1.
41266 */
41267 static int walIteratorNext(
41268   WalIterator *p,               /* Iterator */
41269   u32 *piPage,                  /* OUT: The page number of the next page */
41270   u32 *piFrame                  /* OUT: Wal frame index of next page */
41271 ){
41272   u32 iMin;                     /* Result pgno must be greater than iMin */
41273   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
41274   int i;                        /* For looping through segments */
41275
41276   iMin = p->iPrior;
41277   assert( iMin<0xffffffff );
41278   for(i=p->nSegment-1; i>=0; i--){
41279     struct WalSegment *pSegment = &p->aSegment[i];
41280     while( pSegment->iNext<pSegment->nEntry ){
41281       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
41282       if( iPg>iMin ){
41283         if( iPg<iRet ){
41284           iRet = iPg;
41285           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
41286         }
41287         break;
41288       }
41289       pSegment->iNext++;
41290     }
41291   }
41292
41293   *piPage = p->iPrior = iRet;
41294   return (iRet==0xFFFFFFFF);
41295 }
41296
41297 /*
41298 ** This function merges two sorted lists into a single sorted list.
41299 */
41300 static void walMerge(
41301   u32 *aContent,                  /* Pages in wal */
41302   ht_slot *aLeft,                 /* IN: Left hand input list */
41303   int nLeft,                      /* IN: Elements in array *paLeft */
41304   ht_slot **paRight,              /* IN/OUT: Right hand input list */
41305   int *pnRight,                   /* IN/OUT: Elements in *paRight */
41306   ht_slot *aTmp                   /* Temporary buffer */
41307 ){
41308   int iLeft = 0;                  /* Current index in aLeft */
41309   int iRight = 0;                 /* Current index in aRight */
41310   int iOut = 0;                   /* Current index in output buffer */
41311   int nRight = *pnRight;
41312   ht_slot *aRight = *paRight;
41313
41314   assert( nLeft>0 && nRight>0 );
41315   while( iRight<nRight || iLeft<nLeft ){
41316     ht_slot logpage;
41317     Pgno dbpage;
41318
41319     if( (iLeft<nLeft) 
41320      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
41321     ){
41322       logpage = aLeft[iLeft++];
41323     }else{
41324       logpage = aRight[iRight++];
41325     }
41326     dbpage = aContent[logpage];
41327
41328     aTmp[iOut++] = logpage;
41329     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
41330
41331     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
41332     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
41333   }
41334
41335   *paRight = aLeft;
41336   *pnRight = iOut;
41337   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
41338 }
41339
41340 /*
41341 ** Sort the elements in list aList, removing any duplicates.
41342 */
41343 static void walMergesort(
41344   u32 *aContent,                  /* Pages in wal */
41345   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
41346   ht_slot *aList,                 /* IN/OUT: List to sort */
41347   int *pnList                     /* IN/OUT: Number of elements in aList[] */
41348 ){
41349   struct Sublist {
41350     int nList;                    /* Number of elements in aList */
41351     ht_slot *aList;               /* Pointer to sub-list content */
41352   };
41353
41354   const int nList = *pnList;      /* Size of input list */
41355   int nMerge = 0;                 /* Number of elements in list aMerge */
41356   ht_slot *aMerge = 0;            /* List to be merged */
41357   int iList;                      /* Index into input list */
41358   int iSub = 0;                   /* Index into aSub array */
41359   struct Sublist aSub[13];        /* Array of sub-lists */
41360
41361   memset(aSub, 0, sizeof(aSub));
41362   assert( nList<=HASHTABLE_NPAGE && nList>0 );
41363   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
41364
41365   for(iList=0; iList<nList; iList++){
41366     nMerge = 1;
41367     aMerge = &aList[iList];
41368     for(iSub=0; iList & (1<<iSub); iSub++){
41369       struct Sublist *p = &aSub[iSub];
41370       assert( p->aList && p->nList<=(1<<iSub) );
41371       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
41372       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41373     }
41374     aSub[iSub].aList = aMerge;
41375     aSub[iSub].nList = nMerge;
41376   }
41377
41378   for(iSub++; iSub<ArraySize(aSub); iSub++){
41379     if( nList & (1<<iSub) ){
41380       struct Sublist *p = &aSub[iSub];
41381       assert( p->nList<=(1<<iSub) );
41382       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
41383       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41384     }
41385   }
41386   assert( aMerge==aList );
41387   *pnList = nMerge;
41388
41389 #ifdef SQLITE_DEBUG
41390   {
41391     int i;
41392     for(i=1; i<*pnList; i++){
41393       assert( aContent[aList[i]] > aContent[aList[i-1]] );
41394     }
41395   }
41396 #endif
41397 }
41398
41399 /* 
41400 ** Free an iterator allocated by walIteratorInit().
41401 */
41402 static void walIteratorFree(WalIterator *p){
41403   sqlite3ScratchFree(p);
41404 }
41405
41406 /*
41407 ** Construct a WalInterator object that can be used to loop over all 
41408 ** pages in the WAL in ascending order. The caller must hold the checkpoint
41409 **
41410 ** On success, make *pp point to the newly allocated WalInterator object
41411 ** return SQLITE_OK. Otherwise, return an error code. If this routine
41412 ** returns an error, the value of *pp is undefined.
41413 **
41414 ** The calling routine should invoke walIteratorFree() to destroy the
41415 ** WalIterator object when it has finished with it.
41416 */
41417 static int walIteratorInit(Wal *pWal, WalIterator **pp){
41418   WalIterator *p;                 /* Return value */
41419   int nSegment;                   /* Number of segments to merge */
41420   u32 iLast;                      /* Last frame in log */
41421   int nByte;                      /* Number of bytes to allocate */
41422   int i;                          /* Iterator variable */
41423   ht_slot *aTmp;                  /* Temp space used by merge-sort */
41424   int rc = SQLITE_OK;             /* Return Code */
41425
41426   /* This routine only runs while holding the checkpoint lock. And
41427   ** it only runs if there is actually content in the log (mxFrame>0).
41428   */
41429   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
41430   iLast = pWal->hdr.mxFrame;
41431
41432   /* Allocate space for the WalIterator object. */
41433   nSegment = walFramePage(iLast) + 1;
41434   nByte = sizeof(WalIterator) 
41435         + (nSegment-1)*sizeof(struct WalSegment)
41436         + iLast*sizeof(ht_slot);
41437   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
41438   if( !p ){
41439     return SQLITE_NOMEM;
41440   }
41441   memset(p, 0, nByte);
41442   p->nSegment = nSegment;
41443
41444   /* Allocate temporary space used by the merge-sort routine. This block
41445   ** of memory will be freed before this function returns.
41446   */
41447   aTmp = (ht_slot *)sqlite3ScratchMalloc(
41448       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
41449   );
41450   if( !aTmp ){
41451     rc = SQLITE_NOMEM;
41452   }
41453
41454   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
41455     volatile ht_slot *aHash;
41456     u32 iZero;
41457     volatile u32 *aPgno;
41458
41459     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
41460     if( rc==SQLITE_OK ){
41461       int j;                      /* Counter variable */
41462       int nEntry;                 /* Number of entries in this segment */
41463       ht_slot *aIndex;            /* Sorted index for this segment */
41464
41465       aPgno++;
41466       if( (i+1)==nSegment ){
41467         nEntry = (int)(iLast - iZero);
41468       }else{
41469         nEntry = (int)((u32*)aHash - (u32*)aPgno);
41470       }
41471       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
41472       iZero++;
41473   
41474       for(j=0; j<nEntry; j++){
41475         aIndex[j] = (ht_slot)j;
41476       }
41477       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
41478       p->aSegment[i].iZero = iZero;
41479       p->aSegment[i].nEntry = nEntry;
41480       p->aSegment[i].aIndex = aIndex;
41481       p->aSegment[i].aPgno = (u32 *)aPgno;
41482     }
41483   }
41484   sqlite3ScratchFree(aTmp);
41485
41486   if( rc!=SQLITE_OK ){
41487     walIteratorFree(p);
41488   }
41489   *pp = p;
41490   return rc;
41491 }
41492
41493 /*
41494 ** Copy as much content as we can from the WAL back into the database file
41495 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
41496 **
41497 ** The amount of information copies from WAL to database might be limited
41498 ** by active readers.  This routine will never overwrite a database page
41499 ** that a concurrent reader might be using.
41500 **
41501 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
41502 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
41503 ** checkpoints are always run by a background thread or background 
41504 ** process, foreground threads will never block on a lengthy fsync call.
41505 **
41506 ** Fsync is called on the WAL before writing content out of the WAL and
41507 ** into the database.  This ensures that if the new content is persistent
41508 ** in the WAL and can be recovered following a power-loss or hard reset.
41509 **
41510 ** Fsync is also called on the database file if (and only if) the entire
41511 ** WAL content is copied into the database file.  This second fsync makes
41512 ** it safe to delete the WAL since the new content will persist in the
41513 ** database file.
41514 **
41515 ** This routine uses and updates the nBackfill field of the wal-index header.
41516 ** This is the only routine tha will increase the value of nBackfill.  
41517 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
41518 ** its value.)
41519 **
41520 ** The caller must be holding sufficient locks to ensure that no other
41521 ** checkpoint is running (in any other thread or process) at the same
41522 ** time.
41523 */
41524 static int walCheckpoint(
41525   Wal *pWal,                      /* Wal connection */
41526   int sync_flags,                 /* Flags for OsSync() (or 0) */
41527   int nBuf,                       /* Size of zBuf in bytes */
41528   u8 *zBuf                        /* Temporary buffer to use */
41529 ){
41530   int rc;                         /* Return code */
41531   int szPage = pWal->hdr.szPage;  /* Database page-size */
41532   WalIterator *pIter = 0;         /* Wal iterator context */
41533   u32 iDbpage = 0;                /* Next database page to write */
41534   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
41535   u32 mxSafeFrame;                /* Max frame that can be backfilled */
41536   int i;                          /* Loop counter */
41537   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
41538
41539   if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
41540
41541   /* Allocate the iterator */
41542   rc = walIteratorInit(pWal, &pIter);
41543   if( rc!=SQLITE_OK ){
41544     return rc;
41545   }
41546   assert( pIter );
41547
41548   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
41549   if( pWal->hdr.szPage!=nBuf ){
41550     rc = SQLITE_CORRUPT_BKPT;
41551     goto walcheckpoint_out;
41552   }
41553
41554   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
41555   ** safe to write into the database.  Frames beyond mxSafeFrame might
41556   ** overwrite database pages that are in use by active readers and thus
41557   ** cannot be backfilled from the WAL.
41558   */
41559   mxSafeFrame = pWal->hdr.mxFrame;
41560   pInfo = walCkptInfo(pWal);
41561   for(i=1; i<WAL_NREADER; i++){
41562     u32 y = pInfo->aReadMark[i];
41563     if( mxSafeFrame>=y ){
41564       assert( y<=pWal->hdr.mxFrame );
41565       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41566       if( rc==SQLITE_OK ){
41567         pInfo->aReadMark[i] = READMARK_NOT_USED;
41568         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41569       }else if( rc==SQLITE_BUSY ){
41570         mxSafeFrame = y;
41571       }else{
41572         goto walcheckpoint_out;
41573       }
41574     }
41575   }
41576
41577   if( pInfo->nBackfill<mxSafeFrame
41578    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
41579   ){
41580     u32 nBackfill = pInfo->nBackfill;
41581
41582     /* Sync the WAL to disk */
41583     if( sync_flags ){
41584       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
41585     }
41586
41587     /* Iterate through the contents of the WAL, copying data to the db file. */
41588     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
41589       i64 iOffset;
41590       assert( walFramePgno(pWal, iFrame)==iDbpage );
41591       if( iFrame<=nBackfill || iFrame>mxSafeFrame ) continue;
41592       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
41593       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
41594       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
41595       if( rc!=SQLITE_OK ) break;
41596       iOffset = (iDbpage-1)*(i64)szPage;
41597       testcase( IS_BIG_INT(iOffset) );
41598       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
41599       if( rc!=SQLITE_OK ) break;
41600     }
41601
41602     /* If work was actually accomplished... */
41603     if( rc==SQLITE_OK ){
41604       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
41605         i64 szDb = pWal->hdr.nPage*(i64)szPage;
41606         testcase( IS_BIG_INT(szDb) );
41607         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
41608         if( rc==SQLITE_OK && sync_flags ){
41609           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
41610         }
41611       }
41612       if( rc==SQLITE_OK ){
41613         pInfo->nBackfill = mxSafeFrame;
41614       }
41615     }
41616
41617     /* Release the reader lock held while backfilling */
41618     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
41619   }else if( rc==SQLITE_BUSY ){
41620     /* Reset the return code so as not to report a checkpoint failure
41621     ** just because active readers prevent any backfill.
41622     */
41623     rc = SQLITE_OK;
41624   }
41625
41626  walcheckpoint_out:
41627   walIteratorFree(pIter);
41628   return rc;
41629 }
41630
41631 /*
41632 ** Close a connection to a log file.
41633 */
41634 SQLITE_PRIVATE int sqlite3WalClose(
41635   Wal *pWal,                      /* Wal to close */
41636   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
41637   int nBuf,
41638   u8 *zBuf                        /* Buffer of at least nBuf bytes */
41639 ){
41640   int rc = SQLITE_OK;
41641   if( pWal ){
41642     int isDelete = 0;             /* True to unlink wal and wal-index files */
41643
41644     /* If an EXCLUSIVE lock can be obtained on the database file (using the
41645     ** ordinary, rollback-mode locking methods, this guarantees that the
41646     ** connection associated with this log file is the only connection to
41647     ** the database. In this case checkpoint the database and unlink both
41648     ** the wal and wal-index files.
41649     **
41650     ** The EXCLUSIVE lock is not released before returning.
41651     */
41652     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
41653     if( rc==SQLITE_OK ){
41654       pWal->exclusiveMode = 1;
41655       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
41656       if( rc==SQLITE_OK ){
41657         isDelete = 1;
41658       }
41659     }
41660
41661     walIndexClose(pWal, isDelete);
41662     sqlite3OsClose(pWal->pWalFd);
41663     if( isDelete ){
41664       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
41665     }
41666     WALTRACE(("WAL%p: closed\n", pWal));
41667     sqlite3_free((void *)pWal->apWiData);
41668     sqlite3_free(pWal);
41669   }
41670   return rc;
41671 }
41672
41673 /*
41674 ** Try to read the wal-index header.  Return 0 on success and 1 if
41675 ** there is a problem.
41676 **
41677 ** The wal-index is in shared memory.  Another thread or process might
41678 ** be writing the header at the same time this procedure is trying to
41679 ** read it, which might result in inconsistency.  A dirty read is detected
41680 ** by verifying that both copies of the header are the same and also by
41681 ** a checksum on the header.
41682 **
41683 ** If and only if the read is consistent and the header is different from
41684 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
41685 ** and *pChanged is set to 1.
41686 **
41687 ** If the checksum cannot be verified return non-zero. If the header
41688 ** is read successfully and the checksum verified, return zero.
41689 */
41690 static int walIndexTryHdr(Wal *pWal, int *pChanged){
41691   u32 aCksum[2];                  /* Checksum on the header content */
41692   WalIndexHdr h1, h2;             /* Two copies of the header content */
41693   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
41694
41695   /* The first page of the wal-index must be mapped at this point. */
41696   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41697
41698   /* Read the header. This might happen currently with a write to the
41699   ** same area of shared memory on a different CPU in a SMP,
41700   ** meaning it is possible that an inconsistent snapshot is read
41701   ** from the file. If this happens, return non-zero.
41702   **
41703   ** There are two copies of the header at the beginning of the wal-index.
41704   ** When reading, read [0] first then [1].  Writes are in the reverse order.
41705   ** Memory barriers are used to prevent the compiler or the hardware from
41706   ** reordering the reads and writes.
41707   */
41708   aHdr = walIndexHdr(pWal);
41709   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
41710   sqlite3OsShmBarrier(pWal->pDbFd);
41711   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
41712
41713   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
41714     return 1;   /* Dirty read */
41715   }  
41716   if( h1.isInit==0 ){
41717     return 1;   /* Malformed header - probably all zeros */
41718   }
41719   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
41720   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
41721     return 1;   /* Checksum does not match */
41722   }
41723
41724   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
41725     *pChanged = 1;
41726     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
41727     pWal->szPage = pWal->hdr.szPage;
41728   }
41729
41730   /* The header was successfully read. Return zero. */
41731   return 0;
41732 }
41733
41734 /*
41735 ** Read the wal-index header from the wal-index and into pWal->hdr.
41736 ** If the wal-header appears to be corrupt, try to reconstruct the
41737 ** wal-index from the WAL before returning.
41738 **
41739 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
41740 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
41741 ** to 0.
41742 **
41743 ** If the wal-index header is successfully read, return SQLITE_OK. 
41744 ** Otherwise an SQLite error code.
41745 */
41746 static int walIndexReadHdr(Wal *pWal, int *pChanged){
41747   int rc;                         /* Return code */
41748   int badHdr;                     /* True if a header read failed */
41749   volatile u32 *page0;            /* Chunk of wal-index containing header */
41750
41751   /* Ensure that page 0 of the wal-index (the page that contains the 
41752   ** wal-index header) is mapped. Return early if an error occurs here.
41753   */
41754   assert( pChanged );
41755   rc = walIndexPage(pWal, 0, &page0);
41756   if( rc!=SQLITE_OK ){
41757     return rc;
41758   };
41759   assert( page0 || pWal->writeLock==0 );
41760
41761   /* If the first page of the wal-index has been mapped, try to read the
41762   ** wal-index header immediately, without holding any lock. This usually
41763   ** works, but may fail if the wal-index header is corrupt or currently 
41764   ** being modified by another thread or process.
41765   */
41766   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
41767
41768   /* If the first attempt failed, it might have been due to a race
41769   ** with a writer.  So get a WRITE lock and try again.
41770   */
41771   assert( badHdr==0 || pWal->writeLock==0 );
41772   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
41773     pWal->writeLock = 1;
41774     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
41775       badHdr = walIndexTryHdr(pWal, pChanged);
41776       if( badHdr ){
41777         /* If the wal-index header is still malformed even while holding
41778         ** a WRITE lock, it can only mean that the header is corrupted and
41779         ** needs to be reconstructed.  So run recovery to do exactly that.
41780         */
41781         rc = walIndexRecover(pWal);
41782         *pChanged = 1;
41783       }
41784     }
41785     pWal->writeLock = 0;
41786     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
41787   }
41788
41789   /* If the header is read successfully, check the version number to make
41790   ** sure the wal-index was not constructed with some future format that
41791   ** this version of SQLite cannot understand.
41792   */
41793   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
41794     rc = SQLITE_CANTOPEN_BKPT;
41795   }
41796
41797   return rc;
41798 }
41799
41800 /*
41801 ** This is the value that walTryBeginRead returns when it needs to
41802 ** be retried.
41803 */
41804 #define WAL_RETRY  (-1)
41805
41806 /*
41807 ** Attempt to start a read transaction.  This might fail due to a race or
41808 ** other transient condition.  When that happens, it returns WAL_RETRY to
41809 ** indicate to the caller that it is safe to retry immediately.
41810 **
41811 ** On success return SQLITE_OK.  On a permanent failure (such an
41812 ** I/O error or an SQLITE_BUSY because another process is running
41813 ** recovery) return a positive error code.
41814 **
41815 ** The useWal parameter is true to force the use of the WAL and disable
41816 ** the case where the WAL is bypassed because it has been completely
41817 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
41818 ** to make a copy of the wal-index header into pWal->hdr.  If the 
41819 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
41820 ** to the caller that the local paget cache is obsolete and needs to be 
41821 ** flushed.)  When useWal==1, the wal-index header is assumed to already
41822 ** be loaded and the pChanged parameter is unused.
41823 **
41824 ** The caller must set the cnt parameter to the number of prior calls to
41825 ** this routine during the current read attempt that returned WAL_RETRY.
41826 ** This routine will start taking more aggressive measures to clear the
41827 ** race conditions after multiple WAL_RETRY returns, and after an excessive
41828 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
41829 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
41830 ** and is not honoring the locking protocol.  There is a vanishingly small
41831 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
41832 ** bad luck when there is lots of contention for the wal-index, but that
41833 ** possibility is so small that it can be safely neglected, we believe.
41834 **
41835 ** On success, this routine obtains a read lock on 
41836 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
41837 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
41838 ** that means the Wal does not hold any read lock.  The reader must not
41839 ** access any database page that is modified by a WAL frame up to and
41840 ** including frame number aReadMark[pWal->readLock].  The reader will
41841 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
41842 ** Or if pWal->readLock==0, then the reader will ignore the WAL
41843 ** completely and get all content directly from the database file.
41844 ** If the useWal parameter is 1 then the WAL will never be ignored and
41845 ** this routine will always set pWal->readLock>0 on success.
41846 ** When the read transaction is completed, the caller must release the
41847 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
41848 **
41849 ** This routine uses the nBackfill and aReadMark[] fields of the header
41850 ** to select a particular WAL_READ_LOCK() that strives to let the
41851 ** checkpoint process do as much work as possible.  This routine might
41852 ** update values of the aReadMark[] array in the header, but if it does
41853 ** so it takes care to hold an exclusive lock on the corresponding
41854 ** WAL_READ_LOCK() while changing values.
41855 */
41856 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
41857   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
41858   u32 mxReadMark;                 /* Largest aReadMark[] value */
41859   int mxI;                        /* Index of largest aReadMark[] value */
41860   int i;                          /* Loop counter */
41861   int rc = SQLITE_OK;             /* Return code  */
41862
41863   assert( pWal->readLock<0 );     /* Not currently locked */
41864
41865   /* Take steps to avoid spinning forever if there is a protocol error. */
41866   if( cnt>5 ){
41867     if( cnt>100 ) return SQLITE_PROTOCOL;
41868     sqlite3OsSleep(pWal->pVfs, 1);
41869   }
41870
41871   if( !useWal ){
41872     rc = walIndexReadHdr(pWal, pChanged);
41873     if( rc==SQLITE_BUSY ){
41874       /* If there is not a recovery running in another thread or process
41875       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
41876       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
41877       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
41878       ** would be technically correct.  But the race is benign since with
41879       ** WAL_RETRY this routine will be called again and will probably be
41880       ** right on the second iteration.
41881       */
41882       if( pWal->apWiData[0]==0 ){
41883         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
41884         ** We assume this is a transient condition, so return WAL_RETRY. The
41885         ** xShmMap() implementation used by the default unix and win32 VFS 
41886         ** modules may return SQLITE_BUSY due to a race condition in the 
41887         ** code that determines whether or not the shared-memory region 
41888         ** must be zeroed before the requested page is returned.
41889         */
41890         rc = WAL_RETRY;
41891       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
41892         walUnlockShared(pWal, WAL_RECOVER_LOCK);
41893         rc = WAL_RETRY;
41894       }else if( rc==SQLITE_BUSY ){
41895         rc = SQLITE_BUSY_RECOVERY;
41896       }
41897     }
41898     if( rc!=SQLITE_OK ){
41899       return rc;
41900     }
41901   }
41902
41903   pInfo = walCkptInfo(pWal);
41904   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
41905     /* The WAL has been completely backfilled (or it is empty).
41906     ** and can be safely ignored.
41907     */
41908     rc = walLockShared(pWal, WAL_READ_LOCK(0));
41909     sqlite3OsShmBarrier(pWal->pDbFd);
41910     if( rc==SQLITE_OK ){
41911       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
41912         /* It is not safe to allow the reader to continue here if frames
41913         ** may have been appended to the log before READ_LOCK(0) was obtained.
41914         ** When holding READ_LOCK(0), the reader ignores the entire log file,
41915         ** which implies that the database file contains a trustworthy
41916         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
41917         ** happening, this is usually correct.
41918         **
41919         ** However, if frames have been appended to the log (or if the log 
41920         ** is wrapped and written for that matter) before the READ_LOCK(0)
41921         ** is obtained, that is not necessarily true. A checkpointer may
41922         ** have started to backfill the appended frames but crashed before
41923         ** it finished. Leaving a corrupt image in the database file.
41924         */
41925         walUnlockShared(pWal, WAL_READ_LOCK(0));
41926         return WAL_RETRY;
41927       }
41928       pWal->readLock = 0;
41929       return SQLITE_OK;
41930     }else if( rc!=SQLITE_BUSY ){
41931       return rc;
41932     }
41933   }
41934
41935   /* If we get this far, it means that the reader will want to use
41936   ** the WAL to get at content from recent commits.  The job now is
41937   ** to select one of the aReadMark[] entries that is closest to
41938   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
41939   */
41940   mxReadMark = 0;
41941   mxI = 0;
41942   for(i=1; i<WAL_NREADER; i++){
41943     u32 thisMark = pInfo->aReadMark[i];
41944     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
41945       assert( thisMark!=READMARK_NOT_USED );
41946       mxReadMark = thisMark;
41947       mxI = i;
41948     }
41949   }
41950   if( mxI==0 ){
41951     /* If we get here, it means that all of the aReadMark[] entries between
41952     ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
41953     ** be mxFrame, then retry.
41954     */
41955     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
41956     if( rc==SQLITE_OK ){
41957       pInfo->aReadMark[1] = pWal->hdr.mxFrame;
41958       walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
41959       rc = WAL_RETRY;
41960     }else if( rc==SQLITE_BUSY ){
41961       rc = WAL_RETRY;
41962     }
41963     return rc;
41964   }else{
41965     if( mxReadMark < pWal->hdr.mxFrame ){
41966       for(i=1; i<WAL_NREADER; i++){
41967         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41968         if( rc==SQLITE_OK ){
41969           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
41970           mxI = i;
41971           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41972           break;
41973         }else if( rc!=SQLITE_BUSY ){
41974           return rc;
41975         }
41976       }
41977     }
41978
41979     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
41980     if( rc ){
41981       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
41982     }
41983     /* Now that the read-lock has been obtained, check that neither the
41984     ** value in the aReadMark[] array or the contents of the wal-index
41985     ** header have changed.
41986     **
41987     ** It is necessary to check that the wal-index header did not change
41988     ** between the time it was read and when the shared-lock was obtained
41989     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
41990     ** that the log file may have been wrapped by a writer, or that frames
41991     ** that occur later in the log than pWal->hdr.mxFrame may have been
41992     ** copied into the database by a checkpointer. If either of these things
41993     ** happened, then reading the database with the current value of
41994     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
41995     ** instead.
41996     **
41997     ** This does not guarantee that the copy of the wal-index header is up to
41998     ** date before proceeding. That would not be possible without somehow
41999     ** blocking writers. It only guarantees that a dangerous checkpoint or 
42000     ** log-wrap (either of which would require an exclusive lock on
42001     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
42002     */
42003     sqlite3OsShmBarrier(pWal->pDbFd);
42004     if( pInfo->aReadMark[mxI]!=mxReadMark
42005      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
42006     ){
42007       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
42008       return WAL_RETRY;
42009     }else{
42010       assert( mxReadMark<=pWal->hdr.mxFrame );
42011       pWal->readLock = (i16)mxI;
42012     }
42013   }
42014   return rc;
42015 }
42016
42017 /*
42018 ** Begin a read transaction on the database.
42019 **
42020 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
42021 ** it takes a snapshot of the state of the WAL and wal-index for the current
42022 ** instant in time.  The current thread will continue to use this snapshot.
42023 ** Other threads might append new content to the WAL and wal-index but
42024 ** that extra content is ignored by the current thread.
42025 **
42026 ** If the database contents have changes since the previous read
42027 ** transaction, then *pChanged is set to 1 before returning.  The
42028 ** Pager layer will use this to know that is cache is stale and
42029 ** needs to be flushed.
42030 */
42031 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
42032   int rc;                         /* Return code */
42033   int cnt = 0;                    /* Number of TryBeginRead attempts */
42034
42035   do{
42036     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
42037   }while( rc==WAL_RETRY );
42038   return rc;
42039 }
42040
42041 /*
42042 ** Finish with a read transaction.  All this does is release the
42043 ** read-lock.
42044 */
42045 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
42046   if( pWal->readLock>=0 ){
42047     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42048     pWal->readLock = -1;
42049   }
42050 }
42051
42052 /*
42053 ** Read a page from the WAL, if it is present in the WAL and if the 
42054 ** current read transaction is configured to use the WAL.  
42055 **
42056 ** The *pInWal is set to 1 if the requested page is in the WAL and
42057 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
42058 ** the WAL and needs to be read out of the database.
42059 */
42060 SQLITE_PRIVATE int sqlite3WalRead(
42061   Wal *pWal,                      /* WAL handle */
42062   Pgno pgno,                      /* Database page number to read data for */
42063   int *pInWal,                    /* OUT: True if data is read from WAL */
42064   int nOut,                       /* Size of buffer pOut in bytes */
42065   u8 *pOut                        /* Buffer to write page data to */
42066 ){
42067   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
42068   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
42069   int iHash;                      /* Used to loop through N hash tables */
42070
42071   /* This routine is only be called from within a read transaction. */
42072   assert( pWal->readLock>=0 || pWal->lockError );
42073
42074   /* If the "last page" field of the wal-index header snapshot is 0, then
42075   ** no data will be read from the wal under any circumstances. Return early
42076   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
42077   ** then the WAL is ignored by the reader so return early, as if the 
42078   ** WAL were empty.
42079   */
42080   if( iLast==0 || pWal->readLock==0 ){
42081     *pInWal = 0;
42082     return SQLITE_OK;
42083   }
42084
42085   /* Search the hash table or tables for an entry matching page number
42086   ** pgno. Each iteration of the following for() loop searches one
42087   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
42088   **
42089   ** This code might run concurrently to the code in walIndexAppend()
42090   ** that adds entries to the wal-index (and possibly to this hash 
42091   ** table). This means the value just read from the hash 
42092   ** slot (aHash[iKey]) may have been added before or after the 
42093   ** current read transaction was opened. Values added after the
42094   ** read transaction was opened may have been written incorrectly -
42095   ** i.e. these slots may contain garbage data. However, we assume
42096   ** that any slots written before the current read transaction was
42097   ** opened remain unmodified.
42098   **
42099   ** For the reasons above, the if(...) condition featured in the inner
42100   ** loop of the following block is more stringent that would be required 
42101   ** if we had exclusive access to the hash-table:
42102   **
42103   **   (aPgno[iFrame]==pgno): 
42104   **     This condition filters out normal hash-table collisions.
42105   **
42106   **   (iFrame<=iLast): 
42107   **     This condition filters out entries that were added to the hash
42108   **     table after the current read-transaction had started.
42109   */
42110   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
42111     volatile ht_slot *aHash;      /* Pointer to hash table */
42112     volatile u32 *aPgno;          /* Pointer to array of page numbers */
42113     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
42114     int iKey;                     /* Hash slot index */
42115     int nCollide;                 /* Number of hash collisions remaining */
42116     int rc;                       /* Error code */
42117
42118     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
42119     if( rc!=SQLITE_OK ){
42120       return rc;
42121     }
42122     nCollide = HASHTABLE_NSLOT;
42123     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
42124       u32 iFrame = aHash[iKey] + iZero;
42125       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
42126         assert( iFrame>iRead );
42127         iRead = iFrame;
42128       }
42129       if( (nCollide--)==0 ){
42130         return SQLITE_CORRUPT_BKPT;
42131       }
42132     }
42133   }
42134
42135 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42136   /* If expensive assert() statements are available, do a linear search
42137   ** of the wal-index file content. Make sure the results agree with the
42138   ** result obtained using the hash indexes above.  */
42139   {
42140     u32 iRead2 = 0;
42141     u32 iTest;
42142     for(iTest=iLast; iTest>0; iTest--){
42143       if( walFramePgno(pWal, iTest)==pgno ){
42144         iRead2 = iTest;
42145         break;
42146       }
42147     }
42148     assert( iRead==iRead2 );
42149   }
42150 #endif
42151
42152   /* If iRead is non-zero, then it is the log frame number that contains the
42153   ** required page. Read and return data from the log file.
42154   */
42155   if( iRead ){
42156     i64 iOffset = walFrameOffset(iRead, pWal->hdr.szPage) + WAL_FRAME_HDRSIZE;
42157     *pInWal = 1;
42158     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42159     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
42160   }
42161
42162   *pInWal = 0;
42163   return SQLITE_OK;
42164 }
42165
42166
42167 /* 
42168 ** Set *pPgno to the size of the database file (or zero, if unknown).
42169 */
42170 SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
42171   assert( pWal->readLock>=0 || pWal->lockError );
42172   *pPgno = pWal->hdr.nPage;
42173 }
42174
42175
42176 /* 
42177 ** This function starts a write transaction on the WAL.
42178 **
42179 ** A read transaction must have already been started by a prior call
42180 ** to sqlite3WalBeginReadTransaction().
42181 **
42182 ** If another thread or process has written into the database since
42183 ** the read transaction was started, then it is not possible for this
42184 ** thread to write as doing so would cause a fork.  So this routine
42185 ** returns SQLITE_BUSY in that case and no write transaction is started.
42186 **
42187 ** There can only be a single writer active at a time.
42188 */
42189 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
42190   int rc;
42191
42192   /* Cannot start a write transaction without first holding a read
42193   ** transaction. */
42194   assert( pWal->readLock>=0 );
42195
42196   if( pWal->readOnly ){
42197     return SQLITE_READONLY;
42198   }
42199
42200   /* Only one writer allowed at a time.  Get the write lock.  Return
42201   ** SQLITE_BUSY if unable.
42202   */
42203   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
42204   if( rc ){
42205     return rc;
42206   }
42207   pWal->writeLock = 1;
42208
42209   /* If another connection has written to the database file since the
42210   ** time the read transaction on this connection was started, then
42211   ** the write is disallowed.
42212   */
42213   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
42214     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42215     pWal->writeLock = 0;
42216     rc = SQLITE_BUSY;
42217   }
42218
42219   return rc;
42220 }
42221
42222 /*
42223 ** End a write transaction.  The commit has already been done.  This
42224 ** routine merely releases the lock.
42225 */
42226 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
42227   if( pWal->writeLock ){
42228     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42229     pWal->writeLock = 0;
42230   }
42231   return SQLITE_OK;
42232 }
42233
42234 /*
42235 ** If any data has been written (but not committed) to the log file, this
42236 ** function moves the write-pointer back to the start of the transaction.
42237 **
42238 ** Additionally, the callback function is invoked for each frame written
42239 ** to the WAL since the start of the transaction. If the callback returns
42240 ** other than SQLITE_OK, it is not invoked again and the error code is
42241 ** returned to the caller.
42242 **
42243 ** Otherwise, if the callback function does not return an error, this
42244 ** function returns SQLITE_OK.
42245 */
42246 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
42247   int rc = SQLITE_OK;
42248   if( pWal->writeLock ){
42249     Pgno iMax = pWal->hdr.mxFrame;
42250     Pgno iFrame;
42251   
42252     /* Restore the clients cache of the wal-index header to the state it
42253     ** was in before the client began writing to the database. 
42254     */
42255     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
42256
42257     for(iFrame=pWal->hdr.mxFrame+1; 
42258         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
42259         iFrame++
42260     ){
42261       /* This call cannot fail. Unless the page for which the page number
42262       ** is passed as the second argument is (a) in the cache and 
42263       ** (b) has an outstanding reference, then xUndo is either a no-op
42264       ** (if (a) is false) or simply expels the page from the cache (if (b)
42265       ** is false).
42266       **
42267       ** If the upper layer is doing a rollback, it is guaranteed that there
42268       ** are no outstanding references to any page other than page 1. And
42269       ** page 1 is never written to the log until the transaction is
42270       ** committed. As a result, the call to xUndo may not fail.
42271       */
42272       assert( walFramePgno(pWal, iFrame)!=1 );
42273       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
42274     }
42275     walCleanupHash(pWal);
42276   }
42277   assert( rc==SQLITE_OK );
42278   return rc;
42279 }
42280
42281 /* 
42282 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
42283 ** values. This function populates the array with values required to 
42284 ** "rollback" the write position of the WAL handle back to the current 
42285 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
42286 */
42287 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
42288   assert( pWal->writeLock );
42289   aWalData[0] = pWal->hdr.mxFrame;
42290   aWalData[1] = pWal->hdr.aFrameCksum[0];
42291   aWalData[2] = pWal->hdr.aFrameCksum[1];
42292   aWalData[3] = pWal->nCkpt;
42293 }
42294
42295 /* 
42296 ** Move the write position of the WAL back to the point identified by
42297 ** the values in the aWalData[] array. aWalData must point to an array
42298 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
42299 ** by a call to WalSavepoint().
42300 */
42301 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
42302   int rc = SQLITE_OK;
42303
42304   assert( pWal->writeLock );
42305   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
42306
42307   if( aWalData[3]!=pWal->nCkpt ){
42308     /* This savepoint was opened immediately after the write-transaction
42309     ** was started. Right after that, the writer decided to wrap around
42310     ** to the start of the log. Update the savepoint values to match.
42311     */
42312     aWalData[0] = 0;
42313     aWalData[3] = pWal->nCkpt;
42314   }
42315
42316   if( aWalData[0]<pWal->hdr.mxFrame ){
42317     pWal->hdr.mxFrame = aWalData[0];
42318     pWal->hdr.aFrameCksum[0] = aWalData[1];
42319     pWal->hdr.aFrameCksum[1] = aWalData[2];
42320     walCleanupHash(pWal);
42321   }
42322
42323   return rc;
42324 }
42325
42326 /*
42327 ** This function is called just before writing a set of frames to the log
42328 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
42329 ** to the current log file, it is possible to overwrite the start of the
42330 ** existing log file with the new frames (i.e. "reset" the log). If so,
42331 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
42332 ** unchanged.
42333 **
42334 ** SQLITE_OK is returned if no error is encountered (regardless of whether
42335 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
42336 ** if some error 
42337 */
42338 static int walRestartLog(Wal *pWal){
42339   int rc = SQLITE_OK;
42340   int cnt;
42341
42342   if( pWal->readLock==0 ){
42343     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
42344     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
42345     if( pInfo->nBackfill>0 ){
42346       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42347       if( rc==SQLITE_OK ){
42348         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
42349         ** readers are currently using the WAL), then the transactions
42350         ** frames will overwrite the start of the existing log. Update the
42351         ** wal-index header to reflect this.
42352         **
42353         ** In theory it would be Ok to update the cache of the header only
42354         ** at this point. But updating the actual wal-index header is also
42355         ** safe and means there is no special case for sqlite3WalUndo()
42356         ** to handle if this transaction is rolled back.
42357         */
42358         int i;                    /* Loop counter */
42359         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
42360         pWal->nCkpt++;
42361         pWal->hdr.mxFrame = 0;
42362         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
42363         sqlite3_randomness(4, &aSalt[1]);
42364         walIndexWriteHdr(pWal);
42365         pInfo->nBackfill = 0;
42366         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42367         assert( pInfo->aReadMark[0]==0 );
42368         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42369       }
42370     }
42371     walUnlockShared(pWal, WAL_READ_LOCK(0));
42372     pWal->readLock = -1;
42373     cnt = 0;
42374     do{
42375       int notUsed;
42376       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
42377     }while( rc==WAL_RETRY );
42378   }
42379   return rc;
42380 }
42381
42382 /* 
42383 ** Write a set of frames to the log. The caller must hold the write-lock
42384 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
42385 */
42386 SQLITE_PRIVATE int sqlite3WalFrames(
42387   Wal *pWal,                      /* Wal handle to write to */
42388   int szPage,                     /* Database page-size in bytes */
42389   PgHdr *pList,                   /* List of dirty pages to write */
42390   Pgno nTruncate,                 /* Database size after this commit */
42391   int isCommit,                   /* True if this is a commit */
42392   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
42393 ){
42394   int rc;                         /* Used to catch return codes */
42395   u32 iFrame;                     /* Next frame address */
42396   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
42397   PgHdr *p;                       /* Iterator to run through pList with. */
42398   PgHdr *pLast = 0;               /* Last frame in list */
42399   int nLast = 0;                  /* Number of extra copies of last page */
42400
42401   assert( pList );
42402   assert( pWal->writeLock );
42403
42404 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
42405   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
42406     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
42407               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
42408   }
42409 #endif
42410
42411   /* See if it is possible to write these frames into the start of the
42412   ** log file, instead of appending to it at pWal->hdr.mxFrame.
42413   */
42414   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
42415     return rc;
42416   }
42417
42418   /* If this is the first frame written into the log, write the WAL
42419   ** header to the start of the WAL file. See comments at the top of
42420   ** this source file for a description of the WAL header format.
42421   */
42422   iFrame = pWal->hdr.mxFrame;
42423   if( iFrame==0 ){
42424     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
42425     u32 aCksum[2];                /* Checksum for wal-header */
42426
42427     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
42428     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
42429     sqlite3Put4byte(&aWalHdr[8], szPage);
42430     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
42431     sqlite3_randomness(8, pWal->hdr.aSalt);
42432     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
42433     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
42434     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
42435     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
42436     
42437     pWal->szPage = (u16)szPage;
42438     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
42439     pWal->hdr.aFrameCksum[0] = aCksum[0];
42440     pWal->hdr.aFrameCksum[1] = aCksum[1];
42441
42442     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
42443     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
42444     if( rc!=SQLITE_OK ){
42445       return rc;
42446     }
42447   }
42448   assert( pWal->szPage==szPage );
42449
42450   /* Write the log file. */
42451   for(p=pList; p; p=p->pDirty){
42452     u32 nDbsize;                  /* Db-size field for frame header */
42453     i64 iOffset;                  /* Write offset in log file */
42454     void *pData;
42455    
42456     iOffset = walFrameOffset(++iFrame, szPage);
42457     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42458     
42459     /* Populate and write the frame header */
42460     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
42461 #if defined(SQLITE_HAS_CODEC)
42462     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
42463 #else
42464     pData = p->pData;
42465 #endif
42466     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
42467     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42468     if( rc!=SQLITE_OK ){
42469       return rc;
42470     }
42471
42472     /* Write the page data */
42473     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
42474     if( rc!=SQLITE_OK ){
42475       return rc;
42476     }
42477     pLast = p;
42478   }
42479
42480   /* Sync the log file if the 'isSync' flag was specified. */
42481   if( sync_flags ){
42482     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
42483     i64 iOffset = walFrameOffset(iFrame+1, szPage);
42484
42485     assert( isCommit );
42486     assert( iSegment>0 );
42487
42488     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
42489     while( iOffset<iSegment ){
42490       void *pData;
42491 #if defined(SQLITE_HAS_CODEC)
42492       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
42493 #else
42494       pData = pLast->pData;
42495 #endif
42496       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
42497       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42498       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42499       if( rc!=SQLITE_OK ){
42500         return rc;
42501       }
42502       iOffset += WAL_FRAME_HDRSIZE;
42503       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
42504       if( rc!=SQLITE_OK ){
42505         return rc;
42506       }
42507       nLast++;
42508       iOffset += szPage;
42509     }
42510
42511     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42512   }
42513
42514   /* Append data to the wal-index. It is not necessary to lock the 
42515   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
42516   ** guarantees that there are no other writers, and no data that may
42517   ** be in use by existing readers is being overwritten.
42518   */
42519   iFrame = pWal->hdr.mxFrame;
42520   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
42521     iFrame++;
42522     rc = walIndexAppend(pWal, iFrame, p->pgno);
42523   }
42524   while( nLast>0 && rc==SQLITE_OK ){
42525     iFrame++;
42526     nLast--;
42527     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
42528   }
42529
42530   if( rc==SQLITE_OK ){
42531     /* Update the private copy of the header. */
42532     pWal->hdr.szPage = (u16)szPage;
42533     pWal->hdr.mxFrame = iFrame;
42534     if( isCommit ){
42535       pWal->hdr.iChange++;
42536       pWal->hdr.nPage = nTruncate;
42537     }
42538     /* If this is a commit, update the wal-index header too. */
42539     if( isCommit ){
42540       walIndexWriteHdr(pWal);
42541       pWal->iCallback = iFrame;
42542     }
42543   }
42544
42545   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
42546   return rc;
42547 }
42548
42549 /* 
42550 ** This routine is called to implement sqlite3_wal_checkpoint() and
42551 ** related interfaces.
42552 **
42553 ** Obtain a CHECKPOINT lock and then backfill as much information as
42554 ** we can from WAL into the database.
42555 */
42556 SQLITE_PRIVATE int sqlite3WalCheckpoint(
42557   Wal *pWal,                      /* Wal connection */
42558   int sync_flags,                 /* Flags to sync db file with (or 0) */
42559   int nBuf,                       /* Size of temporary buffer */
42560   u8 *zBuf                        /* Temporary buffer to use */
42561 ){
42562   int rc;                         /* Return code */
42563   int isChanged = 0;              /* True if a new wal-index header is loaded */
42564
42565   assert( pWal->ckptLock==0 );
42566
42567   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
42568   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
42569   if( rc ){
42570     /* Usually this is SQLITE_BUSY meaning that another thread or process
42571     ** is already running a checkpoint, or maybe a recovery.  But it might
42572     ** also be SQLITE_IOERR. */
42573     return rc;
42574   }
42575   pWal->ckptLock = 1;
42576
42577   /* Copy data from the log to the database file. */
42578   rc = walIndexReadHdr(pWal, &isChanged);
42579   if( rc==SQLITE_OK ){
42580     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
42581   }
42582   if( isChanged ){
42583     /* If a new wal-index header was loaded before the checkpoint was 
42584     ** performed, then the pager-cache associated with pWal is now
42585     ** out of date. So zero the cached wal-index header to ensure that
42586     ** next time the pager opens a snapshot on this database it knows that
42587     ** the cache needs to be reset.
42588     */
42589     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42590   }
42591
42592   /* Release the locks. */
42593   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
42594   pWal->ckptLock = 0;
42595   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
42596   return rc;
42597 }
42598
42599 /* Return the value to pass to a sqlite3_wal_hook callback, the
42600 ** number of frames in the WAL at the point of the last commit since
42601 ** sqlite3WalCallback() was called.  If no commits have occurred since
42602 ** the last call, then return 0.
42603 */
42604 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
42605   u32 ret = 0;
42606   if( pWal ){
42607     ret = pWal->iCallback;
42608     pWal->iCallback = 0;
42609   }
42610   return (int)ret;
42611 }
42612
42613 /*
42614 ** This function is called to change the WAL subsystem into or out
42615 ** of locking_mode=EXCLUSIVE.
42616 **
42617 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
42618 ** into locking_mode=NORMAL.  This means that we must acquire a lock
42619 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
42620 ** or if the acquisition of the lock fails, then return 0.  If the
42621 ** transition out of exclusive-mode is successful, return 1.  This
42622 ** operation must occur while the pager is still holding the exclusive
42623 ** lock on the main database file.
42624 **
42625 ** If op is one, then change from locking_mode=NORMAL into 
42626 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
42627 ** be released.  Return 1 if the transition is made and 0 if the
42628 ** WAL is already in exclusive-locking mode - meaning that this
42629 ** routine is a no-op.  The pager must already hold the exclusive lock
42630 ** on the main database file before invoking this operation.
42631 **
42632 ** If op is negative, then do a dry-run of the op==1 case but do
42633 ** not actually change anything.  The pager uses this to see if it
42634 ** should acquire the database exclusive lock prior to invoking
42635 ** the op==1 case.
42636 */
42637 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
42638   int rc;
42639   assert( pWal->writeLock==0 );
42640
42641   /* pWal->readLock is usually set, but might be -1 if there was a 
42642   ** prior error while attempting to acquire are read-lock. This cannot 
42643   ** happen if the connection is actually in exclusive mode (as no xShmLock
42644   ** locks are taken in this case). Nor should the pager attempt to
42645   ** upgrade to exclusive-mode following such an error.
42646   */
42647   assert( pWal->readLock>=0 || pWal->lockError );
42648   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
42649
42650   if( op==0 ){
42651     if( pWal->exclusiveMode ){
42652       pWal->exclusiveMode = 0;
42653       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
42654         pWal->exclusiveMode = 1;
42655       }
42656       rc = pWal->exclusiveMode==0;
42657     }else{
42658       /* Already in locking_mode=NORMAL */
42659       rc = 0;
42660     }
42661   }else if( op>0 ){
42662     assert( pWal->exclusiveMode==0 );
42663     assert( pWal->readLock>=0 );
42664     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42665     pWal->exclusiveMode = 1;
42666     rc = 1;
42667   }else{
42668     rc = pWal->exclusiveMode==0;
42669   }
42670   return rc;
42671 }
42672
42673 #endif /* #ifndef SQLITE_OMIT_WAL */
42674
42675 /************** End of wal.c *************************************************/
42676 /************** Begin file btmutex.c *****************************************/
42677 /*
42678 ** 2007 August 27
42679 **
42680 ** The author disclaims copyright to this source code.  In place of
42681 ** a legal notice, here is a blessing:
42682 **
42683 **    May you do good and not evil.
42684 **    May you find forgiveness for yourself and forgive others.
42685 **    May you share freely, never taking more than you give.
42686 **
42687 *************************************************************************
42688 **
42689 ** This file contains code used to implement mutexes on Btree objects.
42690 ** This code really belongs in btree.c.  But btree.c is getting too
42691 ** big and we want to break it down some.  This packaged seemed like
42692 ** a good breakout.
42693 */
42694 /************** Include btreeInt.h in the middle of btmutex.c ****************/
42695 /************** Begin file btreeInt.h ****************************************/
42696 /*
42697 ** 2004 April 6
42698 **
42699 ** The author disclaims copyright to this source code.  In place of
42700 ** a legal notice, here is a blessing:
42701 **
42702 **    May you do good and not evil.
42703 **    May you find forgiveness for yourself and forgive others.
42704 **    May you share freely, never taking more than you give.
42705 **
42706 *************************************************************************
42707 ** This file implements a external (disk-based) database using BTrees.
42708 ** For a detailed discussion of BTrees, refer to
42709 **
42710 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
42711 **     "Sorting And Searching", pages 473-480. Addison-Wesley
42712 **     Publishing Company, Reading, Massachusetts.
42713 **
42714 ** The basic idea is that each page of the file contains N database
42715 ** entries and N+1 pointers to subpages.
42716 **
42717 **   ----------------------------------------------------------------
42718 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
42719 **   ----------------------------------------------------------------
42720 **
42721 ** All of the keys on the page that Ptr(0) points to have values less
42722 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
42723 ** values greater than Key(0) and less than Key(1).  All of the keys
42724 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
42725 ** so forth.
42726 **
42727 ** Finding a particular key requires reading O(log(M)) pages from the 
42728 ** disk where M is the number of entries in the tree.
42729 **
42730 ** In this implementation, a single file can hold one or more separate 
42731 ** BTrees.  Each BTree is identified by the index of its root page.  The
42732 ** key and data for any entry are combined to form the "payload".  A
42733 ** fixed amount of payload can be carried directly on the database
42734 ** page.  If the payload is larger than the preset amount then surplus
42735 ** bytes are stored on overflow pages.  The payload for an entry
42736 ** and the preceding pointer are combined to form a "Cell".  Each 
42737 ** page has a small header which contains the Ptr(N) pointer and other
42738 ** information such as the size of key and data.
42739 **
42740 ** FORMAT DETAILS
42741 **
42742 ** The file is divided into pages.  The first page is called page 1,
42743 ** the second is page 2, and so forth.  A page number of zero indicates
42744 ** "no such page".  The page size can be any power of 2 between 512 and 32768.
42745 ** Each page can be either a btree page, a freelist page, an overflow
42746 ** page, or a pointer-map page.
42747 **
42748 ** The first page is always a btree page.  The first 100 bytes of the first
42749 ** page contain a special header (the "file header") that describes the file.
42750 ** The format of the file header is as follows:
42751 **
42752 **   OFFSET   SIZE    DESCRIPTION
42753 **      0      16     Header string: "SQLite format 3\000"
42754 **     16       2     Page size in bytes.  
42755 **     18       1     File format write version
42756 **     19       1     File format read version
42757 **     20       1     Bytes of unused space at the end of each page
42758 **     21       1     Max embedded payload fraction
42759 **     22       1     Min embedded payload fraction
42760 **     23       1     Min leaf payload fraction
42761 **     24       4     File change counter
42762 **     28       4     Reserved for future use
42763 **     32       4     First freelist page
42764 **     36       4     Number of freelist pages in the file
42765 **     40      60     15 4-byte meta values passed to higher layers
42766 **
42767 **     40       4     Schema cookie
42768 **     44       4     File format of schema layer
42769 **     48       4     Size of page cache
42770 **     52       4     Largest root-page (auto/incr_vacuum)
42771 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
42772 **     60       4     User version
42773 **     64       4     Incremental vacuum mode
42774 **     68       4     unused
42775 **     72       4     unused
42776 **     76       4     unused
42777 **
42778 ** All of the integer values are big-endian (most significant byte first).
42779 **
42780 ** The file change counter is incremented when the database is changed
42781 ** This counter allows other processes to know when the file has changed
42782 ** and thus when they need to flush their cache.
42783 **
42784 ** The max embedded payload fraction is the amount of the total usable
42785 ** space in a page that can be consumed by a single cell for standard
42786 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
42787 ** is to limit the maximum cell size so that at least 4 cells will fit
42788 ** on one page.  Thus the default max embedded payload fraction is 64.
42789 **
42790 ** If the payload for a cell is larger than the max payload, then extra
42791 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
42792 ** as many bytes as possible are moved into the overflow pages without letting
42793 ** the cell size drop below the min embedded payload fraction.
42794 **
42795 ** The min leaf payload fraction is like the min embedded payload fraction
42796 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
42797 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
42798 ** not specified in the header.
42799 **
42800 ** Each btree pages is divided into three sections:  The header, the
42801 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
42802 ** file header that occurs before the page header.
42803 **
42804 **      |----------------|
42805 **      | file header    |   100 bytes.  Page 1 only.
42806 **      |----------------|
42807 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
42808 **      |----------------|
42809 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
42810 **      | array          |   |  Grows downward
42811 **      |                |   v
42812 **      |----------------|
42813 **      | unallocated    |
42814 **      | space          |
42815 **      |----------------|   ^  Grows upwards
42816 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
42817 **      | area           |   |  and free space fragments.
42818 **      |----------------|
42819 **
42820 ** The page headers looks like this:
42821 **
42822 **   OFFSET   SIZE     DESCRIPTION
42823 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
42824 **      1       2      byte offset to the first freeblock
42825 **      3       2      number of cells on this page
42826 **      5       2      first byte of the cell content area
42827 **      7       1      number of fragmented free bytes
42828 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
42829 **
42830 ** The flags define the format of this btree page.  The leaf flag means that
42831 ** this page has no children.  The zerodata flag means that this page carries
42832 ** only keys and no data.  The intkey flag means that the key is a integer
42833 ** which is stored in the key size entry of the cell header rather than in
42834 ** the payload area.
42835 **
42836 ** The cell pointer array begins on the first byte after the page header.
42837 ** The cell pointer array contains zero or more 2-byte numbers which are
42838 ** offsets from the beginning of the page to the cell content in the cell
42839 ** content area.  The cell pointers occur in sorted order.  The system strives
42840 ** to keep free space after the last cell pointer so that new cells can
42841 ** be easily added without having to defragment the page.
42842 **
42843 ** Cell content is stored at the very end of the page and grows toward the
42844 ** beginning of the page.
42845 **
42846 ** Unused space within the cell content area is collected into a linked list of
42847 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
42848 ** to the first freeblock is given in the header.  Freeblocks occur in
42849 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
42850 ** any group of 3 or fewer unused bytes in the cell content area cannot
42851 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
42852 ** a fragment.  The total number of bytes in all fragments is recorded.
42853 ** in the page header at offset 7.
42854 **
42855 **    SIZE    DESCRIPTION
42856 **      2     Byte offset of the next freeblock
42857 **      2     Bytes in this freeblock
42858 **
42859 ** Cells are of variable length.  Cells are stored in the cell content area at
42860 ** the end of the page.  Pointers to the cells are in the cell pointer array
42861 ** that immediately follows the page header.  Cells is not necessarily
42862 ** contiguous or in order, but cell pointers are contiguous and in order.
42863 **
42864 ** Cell content makes use of variable length integers.  A variable
42865 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
42866 ** byte are used.  The integer consists of all bytes that have bit 8 set and
42867 ** the first byte with bit 8 clear.  The most significant byte of the integer
42868 ** appears first.  A variable-length integer may not be more than 9 bytes long.
42869 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
42870 ** allows a 64-bit integer to be encoded in 9 bytes.
42871 **
42872 **    0x00                      becomes  0x00000000
42873 **    0x7f                      becomes  0x0000007f
42874 **    0x81 0x00                 becomes  0x00000080
42875 **    0x82 0x00                 becomes  0x00000100
42876 **    0x80 0x7f                 becomes  0x0000007f
42877 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
42878 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
42879 **
42880 ** Variable length integers are used for rowids and to hold the number of
42881 ** bytes of key and data in a btree cell.
42882 **
42883 ** The content of a cell looks like this:
42884 **
42885 **    SIZE    DESCRIPTION
42886 **      4     Page number of the left child. Omitted if leaf flag is set.
42887 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
42888 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
42889 **      *     Payload
42890 **      4     First page of the overflow chain.  Omitted if no overflow
42891 **
42892 ** Overflow pages form a linked list.  Each page except the last is completely
42893 ** filled with data (pagesize - 4 bytes).  The last page can have as little
42894 ** as 1 byte of data.
42895 **
42896 **    SIZE    DESCRIPTION
42897 **      4     Page number of next overflow page
42898 **      *     Data
42899 **
42900 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
42901 ** file header points to the first in a linked list of trunk page.  Each trunk
42902 ** page points to multiple leaf pages.  The content of a leaf page is
42903 ** unspecified.  A trunk page looks like this:
42904 **
42905 **    SIZE    DESCRIPTION
42906 **      4     Page number of next trunk page
42907 **      4     Number of leaf pointers on this page
42908 **      *     zero or more pages numbers of leaves
42909 */
42910
42911
42912 /* The following value is the maximum cell size assuming a maximum page
42913 ** size give above.
42914 */
42915 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
42916
42917 /* The maximum number of cells on a single page of the database.  This
42918 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
42919 ** plus 2 bytes for the index to the cell in the page header).  Such
42920 ** small cells will be rare, but they are possible.
42921 */
42922 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
42923
42924 /* Forward declarations */
42925 typedef struct MemPage MemPage;
42926 typedef struct BtLock BtLock;
42927
42928 /*
42929 ** This is a magic string that appears at the beginning of every
42930 ** SQLite database in order to identify the file as a real database.
42931 **
42932 ** You can change this value at compile-time by specifying a
42933 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
42934 ** header must be exactly 16 bytes including the zero-terminator so
42935 ** the string itself should be 15 characters long.  If you change
42936 ** the header, then your custom library will not be able to read 
42937 ** databases generated by the standard tools and the standard tools
42938 ** will not be able to read databases created by your custom library.
42939 */
42940 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
42941 #  define SQLITE_FILE_HEADER "SQLite format 3"
42942 #endif
42943
42944 /*
42945 ** Page type flags.  An ORed combination of these flags appear as the
42946 ** first byte of on-disk image of every BTree page.
42947 */
42948 #define PTF_INTKEY    0x01
42949 #define PTF_ZERODATA  0x02
42950 #define PTF_LEAFDATA  0x04
42951 #define PTF_LEAF      0x08
42952
42953 /*
42954 ** As each page of the file is loaded into memory, an instance of the following
42955 ** structure is appended and initialized to zero.  This structure stores
42956 ** information about the page that is decoded from the raw file page.
42957 **
42958 ** The pParent field points back to the parent page.  This allows us to
42959 ** walk up the BTree from any leaf to the root.  Care must be taken to
42960 ** unref() the parent page pointer when this page is no longer referenced.
42961 ** The pageDestructor() routine handles that chore.
42962 **
42963 ** Access to all fields of this structure is controlled by the mutex
42964 ** stored in MemPage.pBt->mutex.
42965 */
42966 struct MemPage {
42967   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
42968   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
42969   u8 intKey;           /* True if intkey flag is set */
42970   u8 leaf;             /* True if leaf flag is set */
42971   u8 hasData;          /* True if this page stores data */
42972   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
42973   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
42974   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
42975   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
42976   u16 cellOffset;      /* Index in aData of first cell pointer */
42977   u16 nFree;           /* Number of free bytes on the page */
42978   u16 nCell;           /* Number of cells on this page, local and ovfl */
42979   u16 maskPage;        /* Mask for page offset */
42980   struct _OvflCell {   /* Cells that will not fit on aData[] */
42981     u8 *pCell;          /* Pointers to the body of the overflow cell */
42982     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
42983   } aOvfl[5];
42984   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
42985   u8 *aData;           /* Pointer to disk image of the page data */
42986   DbPage *pDbPage;     /* Pager page handle */
42987   Pgno pgno;           /* Page number for this page */
42988 };
42989
42990 /*
42991 ** The in-memory image of a disk page has the auxiliary information appended
42992 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
42993 ** that extra information.
42994 */
42995 #define EXTRA_SIZE sizeof(MemPage)
42996
42997 /*
42998 ** A linked list of the following structures is stored at BtShared.pLock.
42999 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
43000 ** is opened on the table with root page BtShared.iTable. Locks are removed
43001 ** from this list when a transaction is committed or rolled back, or when
43002 ** a btree handle is closed.
43003 */
43004 struct BtLock {
43005   Btree *pBtree;        /* Btree handle holding this lock */
43006   Pgno iTable;          /* Root page of table */
43007   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
43008   BtLock *pNext;        /* Next in BtShared.pLock list */
43009 };
43010
43011 /* Candidate values for BtLock.eLock */
43012 #define READ_LOCK     1
43013 #define WRITE_LOCK    2
43014
43015 /* A Btree handle
43016 **
43017 ** A database connection contains a pointer to an instance of
43018 ** this object for every database file that it has open.  This structure
43019 ** is opaque to the database connection.  The database connection cannot
43020 ** see the internals of this structure and only deals with pointers to
43021 ** this structure.
43022 **
43023 ** For some database files, the same underlying database cache might be 
43024 ** shared between multiple connections.  In that case, each connection
43025 ** has it own instance of this object.  But each instance of this object
43026 ** points to the same BtShared object.  The database cache and the
43027 ** schema associated with the database file are all contained within
43028 ** the BtShared object.
43029 **
43030 ** All fields in this structure are accessed under sqlite3.mutex.
43031 ** The pBt pointer itself may not be changed while there exists cursors 
43032 ** in the referenced BtShared that point back to this Btree since those
43033 ** cursors have to do go through this Btree to find their BtShared and
43034 ** they often do so without holding sqlite3.mutex.
43035 */
43036 struct Btree {
43037   sqlite3 *db;       /* The database connection holding this btree */
43038   BtShared *pBt;     /* Sharable content of this btree */
43039   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
43040   u8 sharable;       /* True if we can share pBt with another db */
43041   u8 locked;         /* True if db currently has pBt locked */
43042   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
43043   int nBackup;       /* Number of backup operations reading this btree */
43044   Btree *pNext;      /* List of other sharable Btrees from the same db */
43045   Btree *pPrev;      /* Back pointer of the same list */
43046 #ifndef SQLITE_OMIT_SHARED_CACHE
43047   BtLock lock;       /* Object used to lock page 1 */
43048 #endif
43049 };
43050
43051 /*
43052 ** Btree.inTrans may take one of the following values.
43053 **
43054 ** If the shared-data extension is enabled, there may be multiple users
43055 ** of the Btree structure. At most one of these may open a write transaction,
43056 ** but any number may have active read transactions.
43057 */
43058 #define TRANS_NONE  0
43059 #define TRANS_READ  1
43060 #define TRANS_WRITE 2
43061
43062 /*
43063 ** An instance of this object represents a single database file.
43064 ** 
43065 ** A single database file can be in use as the same time by two
43066 ** or more database connections.  When two or more connections are
43067 ** sharing the same database file, each connection has it own
43068 ** private Btree object for the file and each of those Btrees points
43069 ** to this one BtShared object.  BtShared.nRef is the number of
43070 ** connections currently sharing this database file.
43071 **
43072 ** Fields in this structure are accessed under the BtShared.mutex
43073 ** mutex, except for nRef and pNext which are accessed under the
43074 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
43075 ** may not be modified once it is initially set as long as nRef>0.
43076 ** The pSchema field may be set once under BtShared.mutex and
43077 ** thereafter is unchanged as long as nRef>0.
43078 **
43079 ** isPending:
43080 **
43081 **   If a BtShared client fails to obtain a write-lock on a database
43082 **   table (because there exists one or more read-locks on the table),
43083 **   the shared-cache enters 'pending-lock' state and isPending is
43084 **   set to true.
43085 **
43086 **   The shared-cache leaves the 'pending lock' state when either of
43087 **   the following occur:
43088 **
43089 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
43090 **     2) The number of locks held by other connections drops to zero.
43091 **
43092 **   while in the 'pending-lock' state, no connection may start a new
43093 **   transaction.
43094 **
43095 **   This feature is included to help prevent writer-starvation.
43096 */
43097 struct BtShared {
43098   Pager *pPager;        /* The page cache */
43099   sqlite3 *db;          /* Database connection currently using this Btree */
43100   BtCursor *pCursor;    /* A list of all open cursors */
43101   MemPage *pPage1;      /* First page of the database */
43102   u8 readOnly;          /* True if the underlying file is readonly */
43103   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
43104   u8 secureDelete;      /* True if secure_delete is enabled */
43105   u8 initiallyEmpty;    /* Database is empty at start of transaction */
43106 #ifndef SQLITE_OMIT_AUTOVACUUM
43107   u8 autoVacuum;        /* True if auto-vacuum is enabled */
43108   u8 incrVacuum;        /* True if incr-vacuum is enabled */
43109 #endif
43110   u16 pageSize;         /* Total number of bytes on a page */
43111   u16 usableSize;       /* Number of usable bytes on each page */
43112   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
43113   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
43114   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
43115   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
43116   u8 inTransaction;     /* Transaction state */
43117   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
43118   int nTransaction;     /* Number of open transactions (read + write) */
43119   u32 nPage;            /* Number of pages in the database */
43120   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
43121   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
43122   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
43123   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
43124 #ifndef SQLITE_OMIT_SHARED_CACHE
43125   int nRef;             /* Number of references to this structure */
43126   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
43127   BtLock *pLock;        /* List of locks held on this shared-btree struct */
43128   Btree *pWriter;       /* Btree with currently open write transaction */
43129   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
43130   u8 isPending;         /* If waiting for read-locks to clear */
43131 #endif
43132   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
43133 };
43134
43135 /*
43136 ** An instance of the following structure is used to hold information
43137 ** about a cell.  The parseCellPtr() function fills in this structure
43138 ** based on information extract from the raw disk page.
43139 */
43140 typedef struct CellInfo CellInfo;
43141 struct CellInfo {
43142   u8 *pCell;     /* Pointer to the start of cell content */
43143   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
43144   u32 nData;     /* Number of bytes of data */
43145   u32 nPayload;  /* Total amount of payload */
43146   u16 nHeader;   /* Size of the cell content header in bytes */
43147   u16 nLocal;    /* Amount of payload held locally */
43148   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
43149   u16 nSize;     /* Size of the cell content on the main b-tree page */
43150 };
43151
43152 /*
43153 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
43154 ** this will be declared corrupt. This value is calculated based on a
43155 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
43156 ** root-node and 3 for all other internal nodes.
43157 **
43158 ** If a tree that appears to be taller than this is encountered, it is
43159 ** assumed that the database is corrupt.
43160 */
43161 #define BTCURSOR_MAX_DEPTH 20
43162
43163 /*
43164 ** A cursor is a pointer to a particular entry within a particular
43165 ** b-tree within a database file.
43166 **
43167 ** The entry is identified by its MemPage and the index in
43168 ** MemPage.aCell[] of the entry.
43169 **
43170 ** A single database file can shared by two more database connections,
43171 ** but cursors cannot be shared.  Each cursor is associated with a
43172 ** particular database connection identified BtCursor.pBtree.db.
43173 **
43174 ** Fields in this structure are accessed under the BtShared.mutex
43175 ** found at self->pBt->mutex. 
43176 */
43177 struct BtCursor {
43178   Btree *pBtree;            /* The Btree to which this cursor belongs */
43179   BtShared *pBt;            /* The BtShared this cursor points to */
43180   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
43181   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
43182   Pgno pgnoRoot;            /* The root page of this tree */
43183   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
43184   CellInfo info;            /* A parse of the cell we are pointing at */
43185   u8 wrFlag;                /* True if writable */
43186   u8 atLast;                /* Cursor pointing to the last entry */
43187   u8 validNKey;             /* True if info.nKey is valid */
43188   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
43189   void *pKey;      /* Saved key that was cursor's last known position */
43190   i64 nKey;        /* Size of pKey, or last integer key */
43191   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
43192 #ifndef SQLITE_OMIT_INCRBLOB
43193   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
43194   Pgno *aOverflow;          /* Cache of overflow page locations */
43195 #endif
43196   i16 iPage;                            /* Index of current page in apPage */
43197   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
43198   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
43199 };
43200
43201 /*
43202 ** Potential values for BtCursor.eState.
43203 **
43204 ** CURSOR_VALID:
43205 **   Cursor points to a valid entry. getPayload() etc. may be called.
43206 **
43207 ** CURSOR_INVALID:
43208 **   Cursor does not point to a valid entry. This can happen (for example) 
43209 **   because the table is empty or because BtreeCursorFirst() has not been
43210 **   called.
43211 **
43212 ** CURSOR_REQUIRESEEK:
43213 **   The table that this cursor was opened on still exists, but has been 
43214 **   modified since the cursor was last used. The cursor position is saved
43215 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
43216 **   this state, restoreCursorPosition() can be called to attempt to
43217 **   seek the cursor to the saved position.
43218 **
43219 ** CURSOR_FAULT:
43220 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
43221 **   on a different connection that shares the BtShared cache with this
43222 **   cursor.  The error has left the cache in an inconsistent state.
43223 **   Do nothing else with this cursor.  Any attempt to use the cursor
43224 **   should return the error code stored in BtCursor.skip
43225 */
43226 #define CURSOR_INVALID           0
43227 #define CURSOR_VALID             1
43228 #define CURSOR_REQUIRESEEK       2
43229 #define CURSOR_FAULT             3
43230
43231 /* 
43232 ** The database page the PENDING_BYTE occupies. This page is never used.
43233 */
43234 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
43235
43236 /*
43237 ** These macros define the location of the pointer-map entry for a 
43238 ** database page. The first argument to each is the number of usable
43239 ** bytes on each page of the database (often 1024). The second is the
43240 ** page number to look up in the pointer map.
43241 **
43242 ** PTRMAP_PAGENO returns the database page number of the pointer-map
43243 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
43244 ** the offset of the requested map entry.
43245 **
43246 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
43247 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
43248 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
43249 ** this test.
43250 */
43251 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
43252 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
43253 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
43254
43255 /*
43256 ** The pointer map is a lookup table that identifies the parent page for
43257 ** each child page in the database file.  The parent page is the page that
43258 ** contains a pointer to the child.  Every page in the database contains
43259 ** 0 or 1 parent pages.  (In this context 'database page' refers
43260 ** to any page that is not part of the pointer map itself.)  Each pointer map
43261 ** entry consists of a single byte 'type' and a 4 byte parent page number.
43262 ** The PTRMAP_XXX identifiers below are the valid types.
43263 **
43264 ** The purpose of the pointer map is to facility moving pages from one
43265 ** position in the file to another as part of autovacuum.  When a page
43266 ** is moved, the pointer in its parent must be updated to point to the
43267 ** new location.  The pointer map is used to locate the parent page quickly.
43268 **
43269 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
43270 **                  used in this case.
43271 **
43272 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
43273 **                  is not used in this case.
43274 **
43275 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
43276 **                   overflow pages. The page number identifies the page that
43277 **                   contains the cell with a pointer to this overflow page.
43278 **
43279 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
43280 **                   overflow pages. The page-number identifies the previous
43281 **                   page in the overflow page list.
43282 **
43283 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
43284 **               identifies the parent page in the btree.
43285 */
43286 #define PTRMAP_ROOTPAGE 1
43287 #define PTRMAP_FREEPAGE 2
43288 #define PTRMAP_OVERFLOW1 3
43289 #define PTRMAP_OVERFLOW2 4
43290 #define PTRMAP_BTREE 5
43291
43292 /* A bunch of assert() statements to check the transaction state variables
43293 ** of handle p (type Btree*) are internally consistent.
43294 */
43295 #define btreeIntegrity(p) \
43296   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
43297   assert( p->pBt->inTransaction>=p->inTrans ); 
43298
43299
43300 /*
43301 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
43302 ** if the database supports auto-vacuum or not. Because it is used
43303 ** within an expression that is an argument to another macro 
43304 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
43305 ** So, this macro is defined instead.
43306 */
43307 #ifndef SQLITE_OMIT_AUTOVACUUM
43308 #define ISAUTOVACUUM (pBt->autoVacuum)
43309 #else
43310 #define ISAUTOVACUUM 0
43311 #endif
43312
43313
43314 /*
43315 ** This structure is passed around through all the sanity checking routines
43316 ** in order to keep track of some global state information.
43317 */
43318 typedef struct IntegrityCk IntegrityCk;
43319 struct IntegrityCk {
43320   BtShared *pBt;    /* The tree being checked out */
43321   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
43322   Pgno nPage;       /* Number of pages in the database */
43323   int *anRef;       /* Number of times each page is referenced */
43324   int mxErr;        /* Stop accumulating errors when this reaches zero */
43325   int nErr;         /* Number of messages written to zErrMsg so far */
43326   int mallocFailed; /* A memory allocation error has occurred */
43327   StrAccum errMsg;  /* Accumulate the error message text here */
43328 };
43329
43330 /*
43331 ** Read or write a two- and four-byte big-endian integer values.
43332 */
43333 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
43334 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
43335 #define get4byte sqlite3Get4byte
43336 #define put4byte sqlite3Put4byte
43337
43338 /************** End of btreeInt.h ********************************************/
43339 /************** Continuing where we left off in btmutex.c ********************/
43340 #ifndef SQLITE_OMIT_SHARED_CACHE
43341 #if SQLITE_THREADSAFE
43342
43343 /*
43344 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
43345 ** set BtShared.db to the database handle associated with p and the
43346 ** p->locked boolean to true.
43347 */
43348 static void lockBtreeMutex(Btree *p){
43349   assert( p->locked==0 );
43350   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
43351   assert( sqlite3_mutex_held(p->db->mutex) );
43352
43353   sqlite3_mutex_enter(p->pBt->mutex);
43354   p->pBt->db = p->db;
43355   p->locked = 1;
43356 }
43357
43358 /*
43359 ** Release the BtShared mutex associated with B-Tree handle p and
43360 ** clear the p->locked boolean.
43361 */
43362 static void unlockBtreeMutex(Btree *p){
43363   assert( p->locked==1 );
43364   assert( sqlite3_mutex_held(p->pBt->mutex) );
43365   assert( sqlite3_mutex_held(p->db->mutex) );
43366   assert( p->db==p->pBt->db );
43367
43368   sqlite3_mutex_leave(p->pBt->mutex);
43369   p->locked = 0;
43370 }
43371
43372 /*
43373 ** Enter a mutex on the given BTree object.
43374 **
43375 ** If the object is not sharable, then no mutex is ever required
43376 ** and this routine is a no-op.  The underlying mutex is non-recursive.
43377 ** But we keep a reference count in Btree.wantToLock so the behavior
43378 ** of this interface is recursive.
43379 **
43380 ** To avoid deadlocks, multiple Btrees are locked in the same order
43381 ** by all database connections.  The p->pNext is a list of other
43382 ** Btrees belonging to the same database connection as the p Btree
43383 ** which need to be locked after p.  If we cannot get a lock on
43384 ** p, then first unlock all of the others on p->pNext, then wait
43385 ** for the lock to become available on p, then relock all of the
43386 ** subsequent Btrees that desire a lock.
43387 */
43388 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43389   Btree *pLater;
43390
43391   /* Some basic sanity checking on the Btree.  The list of Btrees
43392   ** connected by pNext and pPrev should be in sorted order by
43393   ** Btree.pBt value. All elements of the list should belong to
43394   ** the same connection. Only shared Btrees are on the list. */
43395   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
43396   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
43397   assert( p->pNext==0 || p->pNext->db==p->db );
43398   assert( p->pPrev==0 || p->pPrev->db==p->db );
43399   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
43400
43401   /* Check for locking consistency */
43402   assert( !p->locked || p->wantToLock>0 );
43403   assert( p->sharable || p->wantToLock==0 );
43404
43405   /* We should already hold a lock on the database connection */
43406   assert( sqlite3_mutex_held(p->db->mutex) );
43407
43408   /* Unless the database is sharable and unlocked, then BtShared.db
43409   ** should already be set correctly. */
43410   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43411
43412   if( !p->sharable ) return;
43413   p->wantToLock++;
43414   if( p->locked ) return;
43415
43416   /* In most cases, we should be able to acquire the lock we
43417   ** want without having to go throught the ascending lock
43418   ** procedure that follows.  Just be sure not to block.
43419   */
43420   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
43421     p->pBt->db = p->db;
43422     p->locked = 1;
43423     return;
43424   }
43425
43426   /* To avoid deadlock, first release all locks with a larger
43427   ** BtShared address.  Then acquire our lock.  Then reacquire
43428   ** the other BtShared locks that we used to hold in ascending
43429   ** order.
43430   */
43431   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43432     assert( pLater->sharable );
43433     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
43434     assert( !pLater->locked || pLater->wantToLock>0 );
43435     if( pLater->locked ){
43436       unlockBtreeMutex(pLater);
43437     }
43438   }
43439   lockBtreeMutex(p);
43440   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43441     if( pLater->wantToLock ){
43442       lockBtreeMutex(pLater);
43443     }
43444   }
43445 }
43446
43447 /*
43448 ** Exit the recursive mutex on a Btree.
43449 */
43450 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
43451   if( p->sharable ){
43452     assert( p->wantToLock>0 );
43453     p->wantToLock--;
43454     if( p->wantToLock==0 ){
43455       unlockBtreeMutex(p);
43456     }
43457   }
43458 }
43459
43460 #ifndef NDEBUG
43461 /*
43462 ** Return true if the BtShared mutex is held on the btree, or if the
43463 ** B-Tree is not marked as sharable.
43464 **
43465 ** This routine is used only from within assert() statements.
43466 */
43467 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
43468   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
43469   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
43470   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
43471   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
43472
43473   return (p->sharable==0 || p->locked);
43474 }
43475 #endif
43476
43477
43478 #ifndef SQLITE_OMIT_INCRBLOB
43479 /*
43480 ** Enter and leave a mutex on a Btree given a cursor owned by that
43481 ** Btree.  These entry points are used by incremental I/O and can be
43482 ** omitted if that module is not used.
43483 */
43484 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
43485   sqlite3BtreeEnter(pCur->pBtree);
43486 }
43487 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
43488   sqlite3BtreeLeave(pCur->pBtree);
43489 }
43490 #endif /* SQLITE_OMIT_INCRBLOB */
43491
43492
43493 /*
43494 ** Enter the mutex on every Btree associated with a database
43495 ** connection.  This is needed (for example) prior to parsing
43496 ** a statement since we will be comparing table and column names
43497 ** against all schemas and we do not want those schemas being
43498 ** reset out from under us.
43499 **
43500 ** There is a corresponding leave-all procedures.
43501 **
43502 ** Enter the mutexes in accending order by BtShared pointer address
43503 ** to avoid the possibility of deadlock when two threads with
43504 ** two or more btrees in common both try to lock all their btrees
43505 ** at the same instant.
43506 */
43507 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43508   int i;
43509   Btree *p, *pLater;
43510   assert( sqlite3_mutex_held(db->mutex) );
43511   for(i=0; i<db->nDb; i++){
43512     p = db->aDb[i].pBt;
43513     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43514     if( p && p->sharable ){
43515       p->wantToLock++;
43516       if( !p->locked ){
43517         assert( p->wantToLock==1 );
43518         while( p->pPrev ) p = p->pPrev;
43519         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
43520         ** the chain.  Otherwise the !p->locked test above would have failed */
43521         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
43522         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
43523           if( pLater->locked ){
43524             unlockBtreeMutex(pLater);
43525           }
43526         }
43527         while( p ){
43528           lockBtreeMutex(p);
43529           p = p->pNext;
43530         }
43531       }
43532     }
43533   }
43534 }
43535 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
43536   int i;
43537   Btree *p;
43538   assert( sqlite3_mutex_held(db->mutex) );
43539   for(i=0; i<db->nDb; i++){
43540     p = db->aDb[i].pBt;
43541     if( p && p->sharable ){
43542       assert( p->wantToLock>0 );
43543       p->wantToLock--;
43544       if( p->wantToLock==0 ){
43545         unlockBtreeMutex(p);
43546       }
43547     }
43548   }
43549 }
43550
43551 #ifndef NDEBUG
43552 /*
43553 ** Return true if the current thread holds the database connection
43554 ** mutex and all required BtShared mutexes.
43555 **
43556 ** This routine is used inside assert() statements only.
43557 */
43558 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
43559   int i;
43560   if( !sqlite3_mutex_held(db->mutex) ){
43561     return 0;
43562   }
43563   for(i=0; i<db->nDb; i++){
43564     Btree *p;
43565     p = db->aDb[i].pBt;
43566     if( p && p->sharable &&
43567          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
43568       return 0;
43569     }
43570   }
43571   return 1;
43572 }
43573 #endif /* NDEBUG */
43574
43575 /*
43576 ** Add a new Btree pointer to a BtreeMutexArray. 
43577 ** if the pointer can possibly be shared with
43578 ** another database connection.
43579 **
43580 ** The pointers are kept in sorted order by pBtree->pBt.  That
43581 ** way when we go to enter all the mutexes, we can enter them
43582 ** in order without every having to backup and retry and without
43583 ** worrying about deadlock.
43584 **
43585 ** The number of shared btrees will always be small (usually 0 or 1)
43586 ** so an insertion sort is an adequate algorithm here.
43587 */
43588 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
43589   int i, j;
43590   BtShared *pBt;
43591   if( pBtree==0 || pBtree->sharable==0 ) return;
43592 #ifndef NDEBUG
43593   {
43594     for(i=0; i<pArray->nMutex; i++){
43595       assert( pArray->aBtree[i]!=pBtree );
43596     }
43597   }
43598 #endif
43599   assert( pArray->nMutex>=0 );
43600   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
43601   pBt = pBtree->pBt;
43602   for(i=0; i<pArray->nMutex; i++){
43603     assert( pArray->aBtree[i]!=pBtree );
43604     if( pArray->aBtree[i]->pBt>pBt ){
43605       for(j=pArray->nMutex; j>i; j--){
43606         pArray->aBtree[j] = pArray->aBtree[j-1];
43607       }
43608       pArray->aBtree[i] = pBtree;
43609       pArray->nMutex++;
43610       return;
43611     }
43612   }
43613   pArray->aBtree[pArray->nMutex++] = pBtree;
43614 }
43615
43616 /*
43617 ** Enter the mutex of every btree in the array.  This routine is
43618 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
43619 ** exited at the end of the same function.
43620 */
43621 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
43622   int i;
43623   for(i=0; i<pArray->nMutex; i++){
43624     Btree *p = pArray->aBtree[i];
43625     /* Some basic sanity checking */
43626     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43627     assert( !p->locked || p->wantToLock>0 );
43628
43629     /* We should already hold a lock on the database connection */
43630     assert( sqlite3_mutex_held(p->db->mutex) );
43631
43632     /* The Btree is sharable because only sharable Btrees are entered
43633     ** into the array in the first place. */
43634     assert( p->sharable );
43635
43636     p->wantToLock++;
43637     if( !p->locked ){
43638       lockBtreeMutex(p);
43639     }
43640   }
43641 }
43642
43643 /*
43644 ** Leave the mutex of every btree in the group.
43645 */
43646 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
43647   int i;
43648   for(i=0; i<pArray->nMutex; i++){
43649     Btree *p = pArray->aBtree[i];
43650     /* Some basic sanity checking */
43651     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43652     assert( p->locked );
43653     assert( p->wantToLock>0 );
43654
43655     /* We should already hold a lock on the database connection */
43656     assert( sqlite3_mutex_held(p->db->mutex) );
43657
43658     p->wantToLock--;
43659     if( p->wantToLock==0 ){
43660       unlockBtreeMutex(p);
43661     }
43662   }
43663 }
43664
43665 #else
43666 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43667   p->pBt->db = p->db;
43668 }
43669 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43670   int i;
43671   for(i=0; i<db->nDb; i++){
43672     Btree *p = db->aDb[i].pBt;
43673     if( p ){
43674       p->pBt->db = p->db;
43675     }
43676   }
43677 }
43678 #endif /* if SQLITE_THREADSAFE */
43679 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
43680
43681 /************** End of btmutex.c *********************************************/
43682 /************** Begin file btree.c *******************************************/
43683 /*
43684 ** 2004 April 6
43685 **
43686 ** The author disclaims copyright to this source code.  In place of
43687 ** a legal notice, here is a blessing:
43688 **
43689 **    May you do good and not evil.
43690 **    May you find forgiveness for yourself and forgive others.
43691 **    May you share freely, never taking more than you give.
43692 **
43693 *************************************************************************
43694 ** This file implements a external (disk-based) database using BTrees.
43695 ** See the header comment on "btreeInt.h" for additional information.
43696 ** Including a description of file format and an overview of operation.
43697 */
43698
43699 /*
43700 ** The header string that appears at the beginning of every
43701 ** SQLite database.
43702 */
43703 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
43704
43705 /*
43706 ** Set this global variable to 1 to enable tracing using the TRACE
43707 ** macro.
43708 */
43709 #if 0
43710 int sqlite3BtreeTrace=1;  /* True to enable tracing */
43711 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
43712 #else
43713 # define TRACE(X)
43714 #endif
43715
43716
43717
43718 #ifndef SQLITE_OMIT_SHARED_CACHE
43719 /*
43720 ** A list of BtShared objects that are eligible for participation
43721 ** in shared cache.  This variable has file scope during normal builds,
43722 ** but the test harness needs to access it so we make it global for 
43723 ** test builds.
43724 **
43725 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
43726 */
43727 #ifdef SQLITE_TEST
43728 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43729 #else
43730 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43731 #endif
43732 #endif /* SQLITE_OMIT_SHARED_CACHE */
43733
43734 #ifndef SQLITE_OMIT_SHARED_CACHE
43735 /*
43736 ** Enable or disable the shared pager and schema features.
43737 **
43738 ** This routine has no effect on existing database connections.
43739 ** The shared cache setting effects only future calls to
43740 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
43741 */
43742 SQLITE_API int sqlite3_enable_shared_cache(int enable){
43743   sqlite3GlobalConfig.sharedCacheEnabled = enable;
43744   return SQLITE_OK;
43745 }
43746 #endif
43747
43748
43749
43750 #ifdef SQLITE_OMIT_SHARED_CACHE
43751   /*
43752   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
43753   ** and clearAllSharedCacheTableLocks()
43754   ** manipulate entries in the BtShared.pLock linked list used to store
43755   ** shared-cache table level locks. If the library is compiled with the
43756   ** shared-cache feature disabled, then there is only ever one user
43757   ** of each BtShared structure and so this locking is not necessary. 
43758   ** So define the lock related functions as no-ops.
43759   */
43760   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
43761   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
43762   #define clearAllSharedCacheTableLocks(a)
43763   #define downgradeAllSharedCacheTableLocks(a)
43764   #define hasSharedCacheTableLock(a,b,c,d) 1
43765   #define hasReadConflicts(a, b) 0
43766 #endif
43767
43768 #ifndef SQLITE_OMIT_SHARED_CACHE
43769
43770 #ifdef SQLITE_DEBUG
43771 /*
43772 **** This function is only used as part of an assert() statement. ***
43773 **
43774 ** Check to see if pBtree holds the required locks to read or write to the 
43775 ** table with root page iRoot.   Return 1 if it does and 0 if not.
43776 **
43777 ** For example, when writing to a table with root-page iRoot via 
43778 ** Btree connection pBtree:
43779 **
43780 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
43781 **
43782 ** When writing to an index that resides in a sharable database, the 
43783 ** caller should have first obtained a lock specifying the root page of
43784 ** the corresponding table. This makes things a bit more complicated,
43785 ** as this module treats each table as a separate structure. To determine
43786 ** the table corresponding to the index being written, this
43787 ** function has to search through the database schema.
43788 **
43789 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
43790 ** hold a write-lock on the schema table (root page 1). This is also
43791 ** acceptable.
43792 */
43793 static int hasSharedCacheTableLock(
43794   Btree *pBtree,         /* Handle that must hold lock */
43795   Pgno iRoot,            /* Root page of b-tree */
43796   int isIndex,           /* True if iRoot is the root of an index b-tree */
43797   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
43798 ){
43799   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
43800   Pgno iTab = 0;
43801   BtLock *pLock;
43802
43803   /* If this database is not shareable, or if the client is reading
43804   ** and has the read-uncommitted flag set, then no lock is required. 
43805   ** Return true immediately.
43806   */
43807   if( (pBtree->sharable==0)
43808    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
43809   ){
43810     return 1;
43811   }
43812
43813   /* If the client is reading  or writing an index and the schema is
43814   ** not loaded, then it is too difficult to actually check to see if
43815   ** the correct locks are held.  So do not bother - just return true.
43816   ** This case does not come up very often anyhow.
43817   */
43818   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
43819     return 1;
43820   }
43821
43822   /* Figure out the root-page that the lock should be held on. For table
43823   ** b-trees, this is just the root page of the b-tree being read or
43824   ** written. For index b-trees, it is the root page of the associated
43825   ** table.  */
43826   if( isIndex ){
43827     HashElem *p;
43828     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
43829       Index *pIdx = (Index *)sqliteHashData(p);
43830       if( pIdx->tnum==(int)iRoot ){
43831         iTab = pIdx->pTable->tnum;
43832       }
43833     }
43834   }else{
43835     iTab = iRoot;
43836   }
43837
43838   /* Search for the required lock. Either a write-lock on root-page iTab, a 
43839   ** write-lock on the schema table, or (if the client is reading) a
43840   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
43841   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
43842     if( pLock->pBtree==pBtree 
43843      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
43844      && pLock->eLock>=eLockType 
43845     ){
43846       return 1;
43847     }
43848   }
43849
43850   /* Failed to find the required lock. */
43851   return 0;
43852 }
43853 #endif /* SQLITE_DEBUG */
43854
43855 #ifdef SQLITE_DEBUG
43856 /*
43857 **** This function may be used as part of assert() statements only. ****
43858 **
43859 ** Return true if it would be illegal for pBtree to write into the
43860 ** table or index rooted at iRoot because other shared connections are
43861 ** simultaneously reading that same table or index.
43862 **
43863 ** It is illegal for pBtree to write if some other Btree object that
43864 ** shares the same BtShared object is currently reading or writing
43865 ** the iRoot table.  Except, if the other Btree object has the
43866 ** read-uncommitted flag set, then it is OK for the other object to
43867 ** have a read cursor.
43868 **
43869 ** For example, before writing to any part of the table or index
43870 ** rooted at page iRoot, one should call:
43871 **
43872 **    assert( !hasReadConflicts(pBtree, iRoot) );
43873 */
43874 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
43875   BtCursor *p;
43876   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
43877     if( p->pgnoRoot==iRoot 
43878      && p->pBtree!=pBtree
43879      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
43880     ){
43881       return 1;
43882     }
43883   }
43884   return 0;
43885 }
43886 #endif    /* #ifdef SQLITE_DEBUG */
43887
43888 /*
43889 ** Query to see if Btree handle p may obtain a lock of type eLock 
43890 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
43891 ** SQLITE_OK if the lock may be obtained (by calling
43892 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
43893 */
43894 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
43895   BtShared *pBt = p->pBt;
43896   BtLock *pIter;
43897
43898   assert( sqlite3BtreeHoldsMutex(p) );
43899   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43900   assert( p->db!=0 );
43901   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
43902   
43903   /* If requesting a write-lock, then the Btree must have an open write
43904   ** transaction on this file. And, obviously, for this to be so there 
43905   ** must be an open write transaction on the file itself.
43906   */
43907   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
43908   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
43909   
43910   /* This routine is a no-op if the shared-cache is not enabled */
43911   if( !p->sharable ){
43912     return SQLITE_OK;
43913   }
43914
43915   /* If some other connection is holding an exclusive lock, the
43916   ** requested lock may not be obtained.
43917   */
43918   if( pBt->pWriter!=p && pBt->isExclusive ){
43919     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
43920     return SQLITE_LOCKED_SHAREDCACHE;
43921   }
43922
43923   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43924     /* The condition (pIter->eLock!=eLock) in the following if(...) 
43925     ** statement is a simplification of:
43926     **
43927     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
43928     **
43929     ** since we know that if eLock==WRITE_LOCK, then no other connection
43930     ** may hold a WRITE_LOCK on any table in this file (since there can
43931     ** only be a single writer).
43932     */
43933     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
43934     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
43935     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
43936       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
43937       if( eLock==WRITE_LOCK ){
43938         assert( p==pBt->pWriter );
43939         pBt->isPending = 1;
43940       }
43941       return SQLITE_LOCKED_SHAREDCACHE;
43942     }
43943   }
43944   return SQLITE_OK;
43945 }
43946 #endif /* !SQLITE_OMIT_SHARED_CACHE */
43947
43948 #ifndef SQLITE_OMIT_SHARED_CACHE
43949 /*
43950 ** Add a lock on the table with root-page iTable to the shared-btree used
43951 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
43952 ** WRITE_LOCK.
43953 **
43954 ** This function assumes the following:
43955 **
43956 **   (a) The specified Btree object p is connected to a sharable
43957 **       database (one with the BtShared.sharable flag set), and
43958 **
43959 **   (b) No other Btree objects hold a lock that conflicts
43960 **       with the requested lock (i.e. querySharedCacheTableLock() has
43961 **       already been called and returned SQLITE_OK).
43962 **
43963 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
43964 ** is returned if a malloc attempt fails.
43965 */
43966 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
43967   BtShared *pBt = p->pBt;
43968   BtLock *pLock = 0;
43969   BtLock *pIter;
43970
43971   assert( sqlite3BtreeHoldsMutex(p) );
43972   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43973   assert( p->db!=0 );
43974
43975   /* A connection with the read-uncommitted flag set will never try to
43976   ** obtain a read-lock using this function. The only read-lock obtained
43977   ** by a connection in read-uncommitted mode is on the sqlite_master 
43978   ** table, and that lock is obtained in BtreeBeginTrans().  */
43979   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
43980
43981   /* This function should only be called on a sharable b-tree after it 
43982   ** has been determined that no other b-tree holds a conflicting lock.  */
43983   assert( p->sharable );
43984   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
43985
43986   /* First search the list for an existing lock on this table. */
43987   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43988     if( pIter->iTable==iTable && pIter->pBtree==p ){
43989       pLock = pIter;
43990       break;
43991     }
43992   }
43993
43994   /* If the above search did not find a BtLock struct associating Btree p
43995   ** with table iTable, allocate one and link it into the list.
43996   */
43997   if( !pLock ){
43998     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
43999     if( !pLock ){
44000       return SQLITE_NOMEM;
44001     }
44002     pLock->iTable = iTable;
44003     pLock->pBtree = p;
44004     pLock->pNext = pBt->pLock;
44005     pBt->pLock = pLock;
44006   }
44007
44008   /* Set the BtLock.eLock variable to the maximum of the current lock
44009   ** and the requested lock. This means if a write-lock was already held
44010   ** and a read-lock requested, we don't incorrectly downgrade the lock.
44011   */
44012   assert( WRITE_LOCK>READ_LOCK );
44013   if( eLock>pLock->eLock ){
44014     pLock->eLock = eLock;
44015   }
44016
44017   return SQLITE_OK;
44018 }
44019 #endif /* !SQLITE_OMIT_SHARED_CACHE */
44020
44021 #ifndef SQLITE_OMIT_SHARED_CACHE
44022 /*
44023 ** Release all the table locks (locks obtained via calls to
44024 ** the setSharedCacheTableLock() procedure) held by Btree object p.
44025 **
44026 ** This function assumes that Btree p has an open read or write 
44027 ** transaction. If it does not, then the BtShared.isPending variable
44028 ** may be incorrectly cleared.
44029 */
44030 static void clearAllSharedCacheTableLocks(Btree *p){
44031   BtShared *pBt = p->pBt;
44032   BtLock **ppIter = &pBt->pLock;
44033
44034   assert( sqlite3BtreeHoldsMutex(p) );
44035   assert( p->sharable || 0==*ppIter );
44036   assert( p->inTrans>0 );
44037
44038   while( *ppIter ){
44039     BtLock *pLock = *ppIter;
44040     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
44041     assert( pLock->pBtree->inTrans>=pLock->eLock );
44042     if( pLock->pBtree==p ){
44043       *ppIter = pLock->pNext;
44044       assert( pLock->iTable!=1 || pLock==&p->lock );
44045       if( pLock->iTable!=1 ){
44046         sqlite3_free(pLock);
44047       }
44048     }else{
44049       ppIter = &pLock->pNext;
44050     }
44051   }
44052
44053   assert( pBt->isPending==0 || pBt->pWriter );
44054   if( pBt->pWriter==p ){
44055     pBt->pWriter = 0;
44056     pBt->isExclusive = 0;
44057     pBt->isPending = 0;
44058   }else if( pBt->nTransaction==2 ){
44059     /* This function is called when Btree p is concluding its 
44060     ** transaction. If there currently exists a writer, and p is not
44061     ** that writer, then the number of locks held by connections other
44062     ** than the writer must be about to drop to zero. In this case
44063     ** set the isPending flag to 0.
44064     **
44065     ** If there is not currently a writer, then BtShared.isPending must
44066     ** be zero already. So this next line is harmless in that case.
44067     */
44068     pBt->isPending = 0;
44069   }
44070 }
44071
44072 /*
44073 ** This function changes all write-locks held by Btree p into read-locks.
44074 */
44075 static void downgradeAllSharedCacheTableLocks(Btree *p){
44076   BtShared *pBt = p->pBt;
44077   if( pBt->pWriter==p ){
44078     BtLock *pLock;
44079     pBt->pWriter = 0;
44080     pBt->isExclusive = 0;
44081     pBt->isPending = 0;
44082     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
44083       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
44084       pLock->eLock = READ_LOCK;
44085     }
44086   }
44087 }
44088
44089 #endif /* SQLITE_OMIT_SHARED_CACHE */
44090
44091 static void releasePage(MemPage *pPage);  /* Forward reference */
44092
44093 /*
44094 ***** This routine is used inside of assert() only ****
44095 **
44096 ** Verify that the cursor holds the mutex on its BtShared
44097 */
44098 #ifdef SQLITE_DEBUG
44099 static int cursorHoldsMutex(BtCursor *p){
44100   return sqlite3_mutex_held(p->pBt->mutex);
44101 }
44102 #endif
44103
44104
44105 #ifndef SQLITE_OMIT_INCRBLOB
44106 /*
44107 ** Invalidate the overflow page-list cache for cursor pCur, if any.
44108 */
44109 static void invalidateOverflowCache(BtCursor *pCur){
44110   assert( cursorHoldsMutex(pCur) );
44111   sqlite3_free(pCur->aOverflow);
44112   pCur->aOverflow = 0;
44113 }
44114
44115 /*
44116 ** Invalidate the overflow page-list cache for all cursors opened
44117 ** on the shared btree structure pBt.
44118 */
44119 static void invalidateAllOverflowCache(BtShared *pBt){
44120   BtCursor *p;
44121   assert( sqlite3_mutex_held(pBt->mutex) );
44122   for(p=pBt->pCursor; p; p=p->pNext){
44123     invalidateOverflowCache(p);
44124   }
44125 }
44126
44127 /*
44128 ** This function is called before modifying the contents of a table
44129 ** to invalidate any incrblob cursors that are open on the
44130 ** row or one of the rows being modified.
44131 **
44132 ** If argument isClearTable is true, then the entire contents of the
44133 ** table is about to be deleted. In this case invalidate all incrblob
44134 ** cursors open on any row within the table with root-page pgnoRoot.
44135 **
44136 ** Otherwise, if argument isClearTable is false, then the row with
44137 ** rowid iRow is being replaced or deleted. In this case invalidate
44138 ** only those incrblob cursors open on that specific row.
44139 */
44140 static void invalidateIncrblobCursors(
44141   Btree *pBtree,          /* The database file to check */
44142   i64 iRow,               /* The rowid that might be changing */
44143   int isClearTable        /* True if all rows are being deleted */
44144 ){
44145   BtCursor *p;
44146   BtShared *pBt = pBtree->pBt;
44147   assert( sqlite3BtreeHoldsMutex(pBtree) );
44148   for(p=pBt->pCursor; p; p=p->pNext){
44149     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
44150       p->eState = CURSOR_INVALID;
44151     }
44152   }
44153 }
44154
44155 #else
44156   /* Stub functions when INCRBLOB is omitted */
44157   #define invalidateOverflowCache(x)
44158   #define invalidateAllOverflowCache(x)
44159   #define invalidateIncrblobCursors(x,y,z)
44160 #endif /* SQLITE_OMIT_INCRBLOB */
44161
44162 /*
44163 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
44164 ** when a page that previously contained data becomes a free-list leaf 
44165 ** page.
44166 **
44167 ** The BtShared.pHasContent bitvec exists to work around an obscure
44168 ** bug caused by the interaction of two useful IO optimizations surrounding
44169 ** free-list leaf pages:
44170 **
44171 **   1) When all data is deleted from a page and the page becomes
44172 **      a free-list leaf page, the page is not written to the database
44173 **      (as free-list leaf pages contain no meaningful data). Sometimes
44174 **      such a page is not even journalled (as it will not be modified,
44175 **      why bother journalling it?).
44176 **
44177 **   2) When a free-list leaf page is reused, its content is not read
44178 **      from the database or written to the journal file (why should it
44179 **      be, if it is not at all meaningful?).
44180 **
44181 ** By themselves, these optimizations work fine and provide a handy
44182 ** performance boost to bulk delete or insert operations. However, if
44183 ** a page is moved to the free-list and then reused within the same
44184 ** transaction, a problem comes up. If the page is not journalled when
44185 ** it is moved to the free-list and it is also not journalled when it
44186 ** is extracted from the free-list and reused, then the original data
44187 ** may be lost. In the event of a rollback, it may not be possible
44188 ** to restore the database to its original configuration.
44189 **
44190 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
44191 ** moved to become a free-list leaf page, the corresponding bit is
44192 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
44193 ** optimization 2 above is omitted if the corresponding bit is already
44194 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
44195 ** at the end of every transaction.
44196 */
44197 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
44198   int rc = SQLITE_OK;
44199   if( !pBt->pHasContent ){
44200     assert( pgno<=pBt->nPage );
44201     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
44202     if( !pBt->pHasContent ){
44203       rc = SQLITE_NOMEM;
44204     }
44205   }
44206   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
44207     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
44208   }
44209   return rc;
44210 }
44211
44212 /*
44213 ** Query the BtShared.pHasContent vector.
44214 **
44215 ** This function is called when a free-list leaf page is removed from the
44216 ** free-list for reuse. It returns false if it is safe to retrieve the
44217 ** page from the pager layer with the 'no-content' flag set. True otherwise.
44218 */
44219 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
44220   Bitvec *p = pBt->pHasContent;
44221   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
44222 }
44223
44224 /*
44225 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
44226 ** invoked at the conclusion of each write-transaction.
44227 */
44228 static void btreeClearHasContent(BtShared *pBt){
44229   sqlite3BitvecDestroy(pBt->pHasContent);
44230   pBt->pHasContent = 0;
44231 }
44232
44233 /*
44234 ** Save the current cursor position in the variables BtCursor.nKey 
44235 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
44236 **
44237 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
44238 ** prior to calling this routine.  
44239 */
44240 static int saveCursorPosition(BtCursor *pCur){
44241   int rc;
44242
44243   assert( CURSOR_VALID==pCur->eState );
44244   assert( 0==pCur->pKey );
44245   assert( cursorHoldsMutex(pCur) );
44246
44247   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
44248   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
44249
44250   /* If this is an intKey table, then the above call to BtreeKeySize()
44251   ** stores the integer key in pCur->nKey. In this case this value is
44252   ** all that is required. Otherwise, if pCur is not open on an intKey
44253   ** table, then malloc space for and store the pCur->nKey bytes of key 
44254   ** data.
44255   */
44256   if( 0==pCur->apPage[0]->intKey ){
44257     void *pKey = sqlite3Malloc( (int)pCur->nKey );
44258     if( pKey ){
44259       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
44260       if( rc==SQLITE_OK ){
44261         pCur->pKey = pKey;
44262       }else{
44263         sqlite3_free(pKey);
44264       }
44265     }else{
44266       rc = SQLITE_NOMEM;
44267     }
44268   }
44269   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
44270
44271   if( rc==SQLITE_OK ){
44272     int i;
44273     for(i=0; i<=pCur->iPage; i++){
44274       releasePage(pCur->apPage[i]);
44275       pCur->apPage[i] = 0;
44276     }
44277     pCur->iPage = -1;
44278     pCur->eState = CURSOR_REQUIRESEEK;
44279   }
44280
44281   invalidateOverflowCache(pCur);
44282   return rc;
44283 }
44284
44285 /*
44286 ** Save the positions of all cursors (except pExcept) that are open on
44287 ** the table  with root-page iRoot. Usually, this is called just before cursor
44288 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
44289 */
44290 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
44291   BtCursor *p;
44292   assert( sqlite3_mutex_held(pBt->mutex) );
44293   assert( pExcept==0 || pExcept->pBt==pBt );
44294   for(p=pBt->pCursor; p; p=p->pNext){
44295     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
44296         p->eState==CURSOR_VALID ){
44297       int rc = saveCursorPosition(p);
44298       if( SQLITE_OK!=rc ){
44299         return rc;
44300       }
44301     }
44302   }
44303   return SQLITE_OK;
44304 }
44305
44306 /*
44307 ** Clear the current cursor position.
44308 */
44309 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
44310   assert( cursorHoldsMutex(pCur) );
44311   sqlite3_free(pCur->pKey);
44312   pCur->pKey = 0;
44313   pCur->eState = CURSOR_INVALID;
44314 }
44315
44316 /*
44317 ** In this version of BtreeMoveto, pKey is a packed index record
44318 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
44319 ** record and then call BtreeMovetoUnpacked() to do the work.
44320 */
44321 static int btreeMoveto(
44322   BtCursor *pCur,     /* Cursor open on the btree to be searched */
44323   const void *pKey,   /* Packed key if the btree is an index */
44324   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
44325   int bias,           /* Bias search to the high end */
44326   int *pRes           /* Write search results here */
44327 ){
44328   int rc;                    /* Status code */
44329   UnpackedRecord *pIdxKey;   /* Unpacked index key */
44330   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
44331
44332   if( pKey ){
44333     assert( nKey==(i64)(int)nKey );
44334     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
44335                                       aSpace, sizeof(aSpace));
44336     if( pIdxKey==0 ) return SQLITE_NOMEM;
44337   }else{
44338     pIdxKey = 0;
44339   }
44340   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
44341   if( pKey ){
44342     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
44343   }
44344   return rc;
44345 }
44346
44347 /*
44348 ** Restore the cursor to the position it was in (or as close to as possible)
44349 ** when saveCursorPosition() was called. Note that this call deletes the 
44350 ** saved position info stored by saveCursorPosition(), so there can be
44351 ** at most one effective restoreCursorPosition() call after each 
44352 ** saveCursorPosition().
44353 */
44354 static int btreeRestoreCursorPosition(BtCursor *pCur){
44355   int rc;
44356   assert( cursorHoldsMutex(pCur) );
44357   assert( pCur->eState>=CURSOR_REQUIRESEEK );
44358   if( pCur->eState==CURSOR_FAULT ){
44359     return pCur->skipNext;
44360   }
44361   pCur->eState = CURSOR_INVALID;
44362   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
44363   if( rc==SQLITE_OK ){
44364     sqlite3_free(pCur->pKey);
44365     pCur->pKey = 0;
44366     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
44367   }
44368   return rc;
44369 }
44370
44371 #define restoreCursorPosition(p) \
44372   (p->eState>=CURSOR_REQUIRESEEK ? \
44373          btreeRestoreCursorPosition(p) : \
44374          SQLITE_OK)
44375
44376 /*
44377 ** Determine whether or not a cursor has moved from the position it
44378 ** was last placed at.  Cursors can move when the row they are pointing
44379 ** at is deleted out from under them.
44380 **
44381 ** This routine returns an error code if something goes wrong.  The
44382 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
44383 */
44384 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
44385   int rc;
44386
44387   rc = restoreCursorPosition(pCur);
44388   if( rc ){
44389     *pHasMoved = 1;
44390     return rc;
44391   }
44392   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
44393     *pHasMoved = 1;
44394   }else{
44395     *pHasMoved = 0;
44396   }
44397   return SQLITE_OK;
44398 }
44399
44400 #ifndef SQLITE_OMIT_AUTOVACUUM
44401 /*
44402 ** Given a page number of a regular database page, return the page
44403 ** number for the pointer-map page that contains the entry for the
44404 ** input page number.
44405 */
44406 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
44407   int nPagesPerMapPage;
44408   Pgno iPtrMap, ret;
44409   assert( sqlite3_mutex_held(pBt->mutex) );
44410   nPagesPerMapPage = (pBt->usableSize/5)+1;
44411   iPtrMap = (pgno-2)/nPagesPerMapPage;
44412   ret = (iPtrMap*nPagesPerMapPage) + 2; 
44413   if( ret==PENDING_BYTE_PAGE(pBt) ){
44414     ret++;
44415   }
44416   return ret;
44417 }
44418
44419 /*
44420 ** Write an entry into the pointer map.
44421 **
44422 ** This routine updates the pointer map entry for page number 'key'
44423 ** so that it maps to type 'eType' and parent page number 'pgno'.
44424 **
44425 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
44426 ** a no-op.  If an error occurs, the appropriate error code is written
44427 ** into *pRC.
44428 */
44429 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
44430   DbPage *pDbPage;  /* The pointer map page */
44431   u8 *pPtrmap;      /* The pointer map data */
44432   Pgno iPtrmap;     /* The pointer map page number */
44433   int offset;       /* Offset in pointer map page */
44434   int rc;           /* Return code from subfunctions */
44435
44436   if( *pRC ) return;
44437
44438   assert( sqlite3_mutex_held(pBt->mutex) );
44439   /* The master-journal page number must never be used as a pointer map page */
44440   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
44441
44442   assert( pBt->autoVacuum );
44443   if( key==0 ){
44444     *pRC = SQLITE_CORRUPT_BKPT;
44445     return;
44446   }
44447   iPtrmap = PTRMAP_PAGENO(pBt, key);
44448   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44449   if( rc!=SQLITE_OK ){
44450     *pRC = rc;
44451     return;
44452   }
44453   offset = PTRMAP_PTROFFSET(iPtrmap, key);
44454   if( offset<0 ){
44455     *pRC = SQLITE_CORRUPT_BKPT;
44456     goto ptrmap_exit;
44457   }
44458   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44459
44460   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
44461     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
44462     *pRC= rc = sqlite3PagerWrite(pDbPage);
44463     if( rc==SQLITE_OK ){
44464       pPtrmap[offset] = eType;
44465       put4byte(&pPtrmap[offset+1], parent);
44466     }
44467   }
44468
44469 ptrmap_exit:
44470   sqlite3PagerUnref(pDbPage);
44471 }
44472
44473 /*
44474 ** Read an entry from the pointer map.
44475 **
44476 ** This routine retrieves the pointer map entry for page 'key', writing
44477 ** the type and parent page number to *pEType and *pPgno respectively.
44478 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
44479 */
44480 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
44481   DbPage *pDbPage;   /* The pointer map page */
44482   int iPtrmap;       /* Pointer map page index */
44483   u8 *pPtrmap;       /* Pointer map page data */
44484   int offset;        /* Offset of entry in pointer map */
44485   int rc;
44486
44487   assert( sqlite3_mutex_held(pBt->mutex) );
44488
44489   iPtrmap = PTRMAP_PAGENO(pBt, key);
44490   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44491   if( rc!=0 ){
44492     return rc;
44493   }
44494   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44495
44496   offset = PTRMAP_PTROFFSET(iPtrmap, key);
44497   assert( pEType!=0 );
44498   *pEType = pPtrmap[offset];
44499   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
44500
44501   sqlite3PagerUnref(pDbPage);
44502   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
44503   return SQLITE_OK;
44504 }
44505
44506 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
44507   #define ptrmapPut(w,x,y,z,rc)
44508   #define ptrmapGet(w,x,y,z) SQLITE_OK
44509   #define ptrmapPutOvflPtr(x, y, rc)
44510 #endif
44511
44512 /*
44513 ** Given a btree page and a cell index (0 means the first cell on
44514 ** the page, 1 means the second cell, and so forth) return a pointer
44515 ** to the cell content.
44516 **
44517 ** This routine works only for pages that do not contain overflow cells.
44518 */
44519 #define findCell(P,I) \
44520   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
44521
44522 /*
44523 ** This a more complex version of findCell() that works for
44524 ** pages that do contain overflow cells.
44525 */
44526 static u8 *findOverflowCell(MemPage *pPage, int iCell){
44527   int i;
44528   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44529   for(i=pPage->nOverflow-1; i>=0; i--){
44530     int k;
44531     struct _OvflCell *pOvfl;
44532     pOvfl = &pPage->aOvfl[i];
44533     k = pOvfl->idx;
44534     if( k<=iCell ){
44535       if( k==iCell ){
44536         return pOvfl->pCell;
44537       }
44538       iCell--;
44539     }
44540   }
44541   return findCell(pPage, iCell);
44542 }
44543
44544 /*
44545 ** Parse a cell content block and fill in the CellInfo structure.  There
44546 ** are two versions of this function.  btreeParseCell() takes a 
44547 ** cell index as the second argument and btreeParseCellPtr() 
44548 ** takes a pointer to the body of the cell as its second argument.
44549 **
44550 ** Within this file, the parseCell() macro can be called instead of
44551 ** btreeParseCellPtr(). Using some compilers, this will be faster.
44552 */
44553 static void btreeParseCellPtr(
44554   MemPage *pPage,         /* Page containing the cell */
44555   u8 *pCell,              /* Pointer to the cell text. */
44556   CellInfo *pInfo         /* Fill in this structure */
44557 ){
44558   u16 n;                  /* Number bytes in cell content header */
44559   u32 nPayload;           /* Number of bytes of cell payload */
44560
44561   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44562
44563   pInfo->pCell = pCell;
44564   assert( pPage->leaf==0 || pPage->leaf==1 );
44565   n = pPage->childPtrSize;
44566   assert( n==4-4*pPage->leaf );
44567   if( pPage->intKey ){
44568     if( pPage->hasData ){
44569       n += getVarint32(&pCell[n], nPayload);
44570     }else{
44571       nPayload = 0;
44572     }
44573     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
44574     pInfo->nData = nPayload;
44575   }else{
44576     pInfo->nData = 0;
44577     n += getVarint32(&pCell[n], nPayload);
44578     pInfo->nKey = nPayload;
44579   }
44580   pInfo->nPayload = nPayload;
44581   pInfo->nHeader = n;
44582   testcase( nPayload==pPage->maxLocal );
44583   testcase( nPayload==pPage->maxLocal+1 );
44584   if( likely(nPayload<=pPage->maxLocal) ){
44585     /* This is the (easy) common case where the entire payload fits
44586     ** on the local page.  No overflow is required.
44587     */
44588     int nSize;          /* Total size of cell content in bytes */
44589     nSize = nPayload + n;
44590     pInfo->nLocal = (u16)nPayload;
44591     pInfo->iOverflow = 0;
44592     if( (nSize & ~3)==0 ){
44593       nSize = 4;        /* Minimum cell size is 4 */
44594     }
44595     pInfo->nSize = (u16)nSize;
44596   }else{
44597     /* If the payload will not fit completely on the local page, we have
44598     ** to decide how much to store locally and how much to spill onto
44599     ** overflow pages.  The strategy is to minimize the amount of unused
44600     ** space on overflow pages while keeping the amount of local storage
44601     ** in between minLocal and maxLocal.
44602     **
44603     ** Warning:  changing the way overflow payload is distributed in any
44604     ** way will result in an incompatible file format.
44605     */
44606     int minLocal;  /* Minimum amount of payload held locally */
44607     int maxLocal;  /* Maximum amount of payload held locally */
44608     int surplus;   /* Overflow payload available for local storage */
44609
44610     minLocal = pPage->minLocal;
44611     maxLocal = pPage->maxLocal;
44612     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
44613     testcase( surplus==maxLocal );
44614     testcase( surplus==maxLocal+1 );
44615     if( surplus <= maxLocal ){
44616       pInfo->nLocal = (u16)surplus;
44617     }else{
44618       pInfo->nLocal = (u16)minLocal;
44619     }
44620     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
44621     pInfo->nSize = pInfo->iOverflow + 4;
44622   }
44623 }
44624 #define parseCell(pPage, iCell, pInfo) \
44625   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
44626 static void btreeParseCell(
44627   MemPage *pPage,         /* Page containing the cell */
44628   int iCell,              /* The cell index.  First cell is 0 */
44629   CellInfo *pInfo         /* Fill in this structure */
44630 ){
44631   parseCell(pPage, iCell, pInfo);
44632 }
44633
44634 /*
44635 ** Compute the total number of bytes that a Cell needs in the cell
44636 ** data area of the btree-page.  The return number includes the cell
44637 ** data header and the local payload, but not any overflow page or
44638 ** the space used by the cell pointer.
44639 */
44640 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
44641   u8 *pIter = &pCell[pPage->childPtrSize];
44642   u32 nSize;
44643
44644 #ifdef SQLITE_DEBUG
44645   /* The value returned by this function should always be the same as
44646   ** the (CellInfo.nSize) value found by doing a full parse of the
44647   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
44648   ** this function verifies that this invariant is not violated. */
44649   CellInfo debuginfo;
44650   btreeParseCellPtr(pPage, pCell, &debuginfo);
44651 #endif
44652
44653   if( pPage->intKey ){
44654     u8 *pEnd;
44655     if( pPage->hasData ){
44656       pIter += getVarint32(pIter, nSize);
44657     }else{
44658       nSize = 0;
44659     }
44660
44661     /* pIter now points at the 64-bit integer key value, a variable length 
44662     ** integer. The following block moves pIter to point at the first byte
44663     ** past the end of the key value. */
44664     pEnd = &pIter[9];
44665     while( (*pIter++)&0x80 && pIter<pEnd );
44666   }else{
44667     pIter += getVarint32(pIter, nSize);
44668   }
44669
44670   testcase( nSize==pPage->maxLocal );
44671   testcase( nSize==pPage->maxLocal+1 );
44672   if( nSize>pPage->maxLocal ){
44673     int minLocal = pPage->minLocal;
44674     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
44675     testcase( nSize==pPage->maxLocal );
44676     testcase( nSize==pPage->maxLocal+1 );
44677     if( nSize>pPage->maxLocal ){
44678       nSize = minLocal;
44679     }
44680     nSize += 4;
44681   }
44682   nSize += (u32)(pIter - pCell);
44683
44684   /* The minimum size of any cell is 4 bytes. */
44685   if( nSize<4 ){
44686     nSize = 4;
44687   }
44688
44689   assert( nSize==debuginfo.nSize );
44690   return (u16)nSize;
44691 }
44692
44693 #ifdef SQLITE_DEBUG
44694 /* This variation on cellSizePtr() is used inside of assert() statements
44695 ** only. */
44696 static u16 cellSize(MemPage *pPage, int iCell){
44697   return cellSizePtr(pPage, findCell(pPage, iCell));
44698 }
44699 #endif
44700
44701 #ifndef SQLITE_OMIT_AUTOVACUUM
44702 /*
44703 ** If the cell pCell, part of page pPage contains a pointer
44704 ** to an overflow page, insert an entry into the pointer-map
44705 ** for the overflow page.
44706 */
44707 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
44708   CellInfo info;
44709   if( *pRC ) return;
44710   assert( pCell!=0 );
44711   btreeParseCellPtr(pPage, pCell, &info);
44712   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
44713   if( info.iOverflow ){
44714     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
44715     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
44716   }
44717 }
44718 #endif
44719
44720
44721 /*
44722 ** Defragment the page given.  All Cells are moved to the
44723 ** end of the page and all free space is collected into one
44724 ** big FreeBlk that occurs in between the header and cell
44725 ** pointer array and the cell content area.
44726 */
44727 static int defragmentPage(MemPage *pPage){
44728   int i;                     /* Loop counter */
44729   int pc;                    /* Address of a i-th cell */
44730   int hdr;                   /* Offset to the page header */
44731   int size;                  /* Size of a cell */
44732   int usableSize;            /* Number of usable bytes on a page */
44733   int cellOffset;            /* Offset to the cell pointer array */
44734   int cbrk;                  /* Offset to the cell content area */
44735   int nCell;                 /* Number of cells on the page */
44736   unsigned char *data;       /* The page data */
44737   unsigned char *temp;       /* Temp area for cell content */
44738   int iCellFirst;            /* First allowable cell index */
44739   int iCellLast;             /* Last possible cell index */
44740
44741
44742   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44743   assert( pPage->pBt!=0 );
44744   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
44745   assert( pPage->nOverflow==0 );
44746   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44747   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
44748   data = pPage->aData;
44749   hdr = pPage->hdrOffset;
44750   cellOffset = pPage->cellOffset;
44751   nCell = pPage->nCell;
44752   assert( nCell==get2byte(&data[hdr+3]) );
44753   usableSize = pPage->pBt->usableSize;
44754   cbrk = get2byte(&data[hdr+5]);
44755   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
44756   cbrk = usableSize;
44757   iCellFirst = cellOffset + 2*nCell;
44758   iCellLast = usableSize - 4;
44759   for(i=0; i<nCell; i++){
44760     u8 *pAddr;     /* The i-th cell pointer */
44761     pAddr = &data[cellOffset + i*2];
44762     pc = get2byte(pAddr);
44763     testcase( pc==iCellFirst );
44764     testcase( pc==iCellLast );
44765 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44766     /* These conditions have already been verified in btreeInitPage()
44767     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
44768     */
44769     if( pc<iCellFirst || pc>iCellLast ){
44770       return SQLITE_CORRUPT_BKPT;
44771     }
44772 #endif
44773     assert( pc>=iCellFirst && pc<=iCellLast );
44774     size = cellSizePtr(pPage, &temp[pc]);
44775     cbrk -= size;
44776 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44777     if( cbrk<iCellFirst ){
44778       return SQLITE_CORRUPT_BKPT;
44779     }
44780 #else
44781     if( cbrk<iCellFirst || pc+size>usableSize ){
44782       return SQLITE_CORRUPT_BKPT;
44783     }
44784 #endif
44785     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
44786     testcase( cbrk+size==usableSize );
44787     testcase( pc+size==usableSize );
44788     memcpy(&data[cbrk], &temp[pc], size);
44789     put2byte(pAddr, cbrk);
44790   }
44791   assert( cbrk>=iCellFirst );
44792   put2byte(&data[hdr+5], cbrk);
44793   data[hdr+1] = 0;
44794   data[hdr+2] = 0;
44795   data[hdr+7] = 0;
44796   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
44797   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44798   if( cbrk-iCellFirst!=pPage->nFree ){
44799     return SQLITE_CORRUPT_BKPT;
44800   }
44801   return SQLITE_OK;
44802 }
44803
44804 /*
44805 ** Allocate nByte bytes of space from within the B-Tree page passed
44806 ** as the first argument. Write into *pIdx the index into pPage->aData[]
44807 ** of the first byte of allocated space. Return either SQLITE_OK or
44808 ** an error code (usually SQLITE_CORRUPT).
44809 **
44810 ** The caller guarantees that there is sufficient space to make the
44811 ** allocation.  This routine might need to defragment in order to bring
44812 ** all the space together, however.  This routine will avoid using
44813 ** the first two bytes past the cell pointer area since presumably this
44814 ** allocation is being made in order to insert a new cell, so we will
44815 ** also end up needing a new cell pointer.
44816 */
44817 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
44818   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
44819   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
44820   int nFrag;                           /* Number of fragmented bytes on pPage */
44821   int top;                             /* First byte of cell content area */
44822   int gap;        /* First byte of gap between cell pointers and cell content */
44823   int rc;         /* Integer return code */
44824   int usableSize; /* Usable size of the page */
44825   
44826   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44827   assert( pPage->pBt );
44828   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44829   assert( nByte>=0 );  /* Minimum cell size is 4 */
44830   assert( pPage->nFree>=nByte );
44831   assert( pPage->nOverflow==0 );
44832   usableSize = pPage->pBt->usableSize;
44833   assert( nByte < usableSize-8 );
44834
44835   nFrag = data[hdr+7];
44836   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
44837   gap = pPage->cellOffset + 2*pPage->nCell;
44838   top = get2byte(&data[hdr+5]);
44839   if( gap>top ) return SQLITE_CORRUPT_BKPT;
44840   testcase( gap+2==top );
44841   testcase( gap+1==top );
44842   testcase( gap==top );
44843
44844   if( nFrag>=60 ){
44845     /* Always defragment highly fragmented pages */
44846     rc = defragmentPage(pPage);
44847     if( rc ) return rc;
44848     top = get2byte(&data[hdr+5]);
44849   }else if( gap+2<=top ){
44850     /* Search the freelist looking for a free slot big enough to satisfy 
44851     ** the request. The allocation is made from the first free slot in 
44852     ** the list that is large enough to accomadate it.
44853     */
44854     int pc, addr;
44855     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
44856       int size;            /* Size of the free slot */
44857       if( pc>usableSize-4 || pc<addr+4 ){
44858         return SQLITE_CORRUPT_BKPT;
44859       }
44860       size = get2byte(&data[pc+2]);
44861       if( size>=nByte ){
44862         int x = size - nByte;
44863         testcase( x==4 );
44864         testcase( x==3 );
44865         if( x<4 ){
44866           /* Remove the slot from the free-list. Update the number of
44867           ** fragmented bytes within the page. */
44868           memcpy(&data[addr], &data[pc], 2);
44869           data[hdr+7] = (u8)(nFrag + x);
44870         }else if( size+pc > usableSize ){
44871           return SQLITE_CORRUPT_BKPT;
44872         }else{
44873           /* The slot remains on the free-list. Reduce its size to account
44874           ** for the portion used by the new allocation. */
44875           put2byte(&data[pc+2], x);
44876         }
44877         *pIdx = pc + x;
44878         return SQLITE_OK;
44879       }
44880     }
44881   }
44882
44883   /* Check to make sure there is enough space in the gap to satisfy
44884   ** the allocation.  If not, defragment.
44885   */
44886   testcase( gap+2+nByte==top );
44887   if( gap+2+nByte>top ){
44888     rc = defragmentPage(pPage);
44889     if( rc ) return rc;
44890     top = get2byte(&data[hdr+5]);
44891     assert( gap+nByte<=top );
44892   }
44893
44894
44895   /* Allocate memory from the gap in between the cell pointer array
44896   ** and the cell content area.  The btreeInitPage() call has already
44897   ** validated the freelist.  Given that the freelist is valid, there
44898   ** is no way that the allocation can extend off the end of the page.
44899   ** The assert() below verifies the previous sentence.
44900   */
44901   top -= nByte;
44902   put2byte(&data[hdr+5], top);
44903   assert( top+nByte <= pPage->pBt->usableSize );
44904   *pIdx = top;
44905   return SQLITE_OK;
44906 }
44907
44908 /*
44909 ** Return a section of the pPage->aData to the freelist.
44910 ** The first byte of the new free block is pPage->aDisk[start]
44911 ** and the size of the block is "size" bytes.
44912 **
44913 ** Most of the effort here is involved in coalesing adjacent
44914 ** free blocks into a single big free block.
44915 */
44916 static int freeSpace(MemPage *pPage, int start, int size){
44917   int addr, pbegin, hdr;
44918   int iLast;                        /* Largest possible freeblock offset */
44919   unsigned char *data = pPage->aData;
44920
44921   assert( pPage->pBt!=0 );
44922   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44923   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
44924   assert( (start + size)<=pPage->pBt->usableSize );
44925   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44926   assert( size>=0 );   /* Minimum cell size is 4 */
44927
44928   if( pPage->pBt->secureDelete ){
44929     /* Overwrite deleted information with zeros when the secure_delete
44930     ** option is enabled */
44931     memset(&data[start], 0, size);
44932   }
44933
44934   /* Add the space back into the linked list of freeblocks.  Note that
44935   ** even though the freeblock list was checked by btreeInitPage(),
44936   ** btreeInitPage() did not detect overlapping cells or
44937   ** freeblocks that overlapped cells.   Nor does it detect when the
44938   ** cell content area exceeds the value in the page header.  If these
44939   ** situations arise, then subsequent insert operations might corrupt
44940   ** the freelist.  So we do need to check for corruption while scanning
44941   ** the freelist.
44942   */
44943   hdr = pPage->hdrOffset;
44944   addr = hdr + 1;
44945   iLast = pPage->pBt->usableSize - 4;
44946   assert( start<=iLast );
44947   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
44948     if( pbegin<addr+4 ){
44949       return SQLITE_CORRUPT_BKPT;
44950     }
44951     addr = pbegin;
44952   }
44953   if( pbegin>iLast ){
44954     return SQLITE_CORRUPT_BKPT;
44955   }
44956   assert( pbegin>addr || pbegin==0 );
44957   put2byte(&data[addr], start);
44958   put2byte(&data[start], pbegin);
44959   put2byte(&data[start+2], size);
44960   pPage->nFree = pPage->nFree + (u16)size;
44961
44962   /* Coalesce adjacent free blocks */
44963   addr = hdr + 1;
44964   while( (pbegin = get2byte(&data[addr]))>0 ){
44965     int pnext, psize, x;
44966     assert( pbegin>addr );
44967     assert( pbegin<=pPage->pBt->usableSize-4 );
44968     pnext = get2byte(&data[pbegin]);
44969     psize = get2byte(&data[pbegin+2]);
44970     if( pbegin + psize + 3 >= pnext && pnext>0 ){
44971       int frag = pnext - (pbegin+psize);
44972       if( (frag<0) || (frag>(int)data[hdr+7]) ){
44973         return SQLITE_CORRUPT_BKPT;
44974       }
44975       data[hdr+7] -= (u8)frag;
44976       x = get2byte(&data[pnext]);
44977       put2byte(&data[pbegin], x);
44978       x = pnext + get2byte(&data[pnext+2]) - pbegin;
44979       put2byte(&data[pbegin+2], x);
44980     }else{
44981       addr = pbegin;
44982     }
44983   }
44984
44985   /* If the cell content area begins with a freeblock, remove it. */
44986   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
44987     int top;
44988     pbegin = get2byte(&data[hdr+1]);
44989     memcpy(&data[hdr+1], &data[pbegin], 2);
44990     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
44991     put2byte(&data[hdr+5], top);
44992   }
44993   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44994   return SQLITE_OK;
44995 }
44996
44997 /*
44998 ** Decode the flags byte (the first byte of the header) for a page
44999 ** and initialize fields of the MemPage structure accordingly.
45000 **
45001 ** Only the following combinations are supported.  Anything different
45002 ** indicates a corrupt database files:
45003 **
45004 **         PTF_ZERODATA
45005 **         PTF_ZERODATA | PTF_LEAF
45006 **         PTF_LEAFDATA | PTF_INTKEY
45007 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
45008 */
45009 static int decodeFlags(MemPage *pPage, int flagByte){
45010   BtShared *pBt;     /* A copy of pPage->pBt */
45011
45012   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
45013   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45014   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
45015   flagByte &= ~PTF_LEAF;
45016   pPage->childPtrSize = 4-4*pPage->leaf;
45017   pBt = pPage->pBt;
45018   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
45019     pPage->intKey = 1;
45020     pPage->hasData = pPage->leaf;
45021     pPage->maxLocal = pBt->maxLeaf;
45022     pPage->minLocal = pBt->minLeaf;
45023   }else if( flagByte==PTF_ZERODATA ){
45024     pPage->intKey = 0;
45025     pPage->hasData = 0;
45026     pPage->maxLocal = pBt->maxLocal;
45027     pPage->minLocal = pBt->minLocal;
45028   }else{
45029     return SQLITE_CORRUPT_BKPT;
45030   }
45031   return SQLITE_OK;
45032 }
45033
45034 /*
45035 ** Initialize the auxiliary information for a disk block.
45036 **
45037 ** Return SQLITE_OK on success.  If we see that the page does
45038 ** not contain a well-formed database page, then return 
45039 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
45040 ** guarantee that the page is well-formed.  It only shows that
45041 ** we failed to detect any corruption.
45042 */
45043 static int btreeInitPage(MemPage *pPage){
45044
45045   assert( pPage->pBt!=0 );
45046   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45047   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
45048   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
45049   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
45050
45051   if( !pPage->isInit ){
45052     u16 pc;            /* Address of a freeblock within pPage->aData[] */
45053     u8 hdr;            /* Offset to beginning of page header */
45054     u8 *data;          /* Equal to pPage->aData */
45055     BtShared *pBt;        /* The main btree structure */
45056     u16 usableSize;    /* Amount of usable space on each page */
45057     u16 cellOffset;    /* Offset from start of page to first cell pointer */
45058     u16 nFree;         /* Number of unused bytes on the page */
45059     u16 top;           /* First byte of the cell content area */
45060     int iCellFirst;    /* First allowable cell or freeblock offset */
45061     int iCellLast;     /* Last possible cell or freeblock offset */
45062
45063     pBt = pPage->pBt;
45064
45065     hdr = pPage->hdrOffset;
45066     data = pPage->aData;
45067     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
45068     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
45069     pPage->maskPage = pBt->pageSize - 1;
45070     pPage->nOverflow = 0;
45071     usableSize = pBt->usableSize;
45072     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
45073     top = get2byte(&data[hdr+5]);
45074     pPage->nCell = get2byte(&data[hdr+3]);
45075     if( pPage->nCell>MX_CELL(pBt) ){
45076       /* To many cells for a single page.  The page must be corrupt */
45077       return SQLITE_CORRUPT_BKPT;
45078     }
45079     testcase( pPage->nCell==MX_CELL(pBt) );
45080
45081     /* A malformed database page might cause us to read past the end
45082     ** of page when parsing a cell.  
45083     **
45084     ** The following block of code checks early to see if a cell extends
45085     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
45086     ** returned if it does.
45087     */
45088     iCellFirst = cellOffset + 2*pPage->nCell;
45089     iCellLast = usableSize - 4;
45090 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
45091     {
45092       int i;            /* Index into the cell pointer array */
45093       int sz;           /* Size of a cell */
45094
45095       if( !pPage->leaf ) iCellLast--;
45096       for(i=0; i<pPage->nCell; i++){
45097         pc = get2byte(&data[cellOffset+i*2]);
45098         testcase( pc==iCellFirst );
45099         testcase( pc==iCellLast );
45100         if( pc<iCellFirst || pc>iCellLast ){
45101           return SQLITE_CORRUPT_BKPT;
45102         }
45103         sz = cellSizePtr(pPage, &data[pc]);
45104         testcase( pc+sz==usableSize );
45105         if( pc+sz>usableSize ){
45106           return SQLITE_CORRUPT_BKPT;
45107         }
45108       }
45109       if( !pPage->leaf ) iCellLast++;
45110     }  
45111 #endif
45112
45113     /* Compute the total free space on the page */
45114     pc = get2byte(&data[hdr+1]);
45115     nFree = data[hdr+7] + top;
45116     while( pc>0 ){
45117       u16 next, size;
45118       if( pc<iCellFirst || pc>iCellLast ){
45119         /* Start of free block is off the page */
45120         return SQLITE_CORRUPT_BKPT; 
45121       }
45122       next = get2byte(&data[pc]);
45123       size = get2byte(&data[pc+2]);
45124       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
45125         /* Free blocks must be in ascending order. And the last byte of
45126         ** the free-block must lie on the database page.  */
45127         return SQLITE_CORRUPT_BKPT; 
45128       }
45129       nFree = nFree + size;
45130       pc = next;
45131     }
45132
45133     /* At this point, nFree contains the sum of the offset to the start
45134     ** of the cell-content area plus the number of free bytes within
45135     ** the cell-content area. If this is greater than the usable-size
45136     ** of the page, then the page must be corrupted. This check also
45137     ** serves to verify that the offset to the start of the cell-content
45138     ** area, according to the page header, lies within the page.
45139     */
45140     if( nFree>usableSize ){
45141       return SQLITE_CORRUPT_BKPT; 
45142     }
45143     pPage->nFree = (u16)(nFree - iCellFirst);
45144     pPage->isInit = 1;
45145   }
45146   return SQLITE_OK;
45147 }
45148
45149 /*
45150 ** Set up a raw page so that it looks like a database page holding
45151 ** no entries.
45152 */
45153 static void zeroPage(MemPage *pPage, int flags){
45154   unsigned char *data = pPage->aData;
45155   BtShared *pBt = pPage->pBt;
45156   u8 hdr = pPage->hdrOffset;
45157   u16 first;
45158
45159   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
45160   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
45161   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
45162   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45163   assert( sqlite3_mutex_held(pBt->mutex) );
45164   if( pBt->secureDelete ){
45165     memset(&data[hdr], 0, pBt->usableSize - hdr);
45166   }
45167   data[hdr] = (char)flags;
45168   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
45169   memset(&data[hdr+1], 0, 4);
45170   data[hdr+7] = 0;
45171   put2byte(&data[hdr+5], pBt->usableSize);
45172   pPage->nFree = pBt->usableSize - first;
45173   decodeFlags(pPage, flags);
45174   pPage->hdrOffset = hdr;
45175   pPage->cellOffset = first;
45176   pPage->nOverflow = 0;
45177   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
45178   pPage->maskPage = pBt->pageSize - 1;
45179   pPage->nCell = 0;
45180   pPage->isInit = 1;
45181 }
45182
45183
45184 /*
45185 ** Convert a DbPage obtained from the pager into a MemPage used by
45186 ** the btree layer.
45187 */
45188 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
45189   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
45190   pPage->aData = sqlite3PagerGetData(pDbPage);
45191   pPage->pDbPage = pDbPage;
45192   pPage->pBt = pBt;
45193   pPage->pgno = pgno;
45194   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
45195   return pPage; 
45196 }
45197
45198 /*
45199 ** Get a page from the pager.  Initialize the MemPage.pBt and
45200 ** MemPage.aData elements if needed.
45201 **
45202 ** If the noContent flag is set, it means that we do not care about
45203 ** the content of the page at this time.  So do not go to the disk
45204 ** to fetch the content.  Just fill in the content with zeros for now.
45205 ** If in the future we call sqlite3PagerWrite() on this page, that
45206 ** means we have started to be concerned about content and the disk
45207 ** read should occur at that point.
45208 */
45209 static int btreeGetPage(
45210   BtShared *pBt,       /* The btree */
45211   Pgno pgno,           /* Number of the page to fetch */
45212   MemPage **ppPage,    /* Return the page in this parameter */
45213   int noContent        /* Do not load page content if true */
45214 ){
45215   int rc;
45216   DbPage *pDbPage;
45217
45218   assert( sqlite3_mutex_held(pBt->mutex) );
45219   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
45220   if( rc ) return rc;
45221   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
45222   return SQLITE_OK;
45223 }
45224
45225 /*
45226 ** Retrieve a page from the pager cache. If the requested page is not
45227 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
45228 ** MemPage.aData elements if needed.
45229 */
45230 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
45231   DbPage *pDbPage;
45232   assert( sqlite3_mutex_held(pBt->mutex) );
45233   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
45234   if( pDbPage ){
45235     return btreePageFromDbPage(pDbPage, pgno, pBt);
45236   }
45237   return 0;
45238 }
45239
45240 /*
45241 ** Return the size of the database file in pages. If there is any kind of
45242 ** error, return ((unsigned int)-1).
45243 */
45244 static Pgno btreePagecount(BtShared *pBt){
45245   return pBt->nPage;
45246 }
45247 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
45248   assert( sqlite3BtreeHoldsMutex(p) );
45249   assert( ((p->pBt->nPage)&0x8000000)==0 );
45250   return (int)btreePagecount(p->pBt);
45251 }
45252
45253 /*
45254 ** Get a page from the pager and initialize it.  This routine is just a
45255 ** convenience wrapper around separate calls to btreeGetPage() and 
45256 ** btreeInitPage().
45257 **
45258 ** If an error occurs, then the value *ppPage is set to is undefined. It
45259 ** may remain unchanged, or it may be set to an invalid value.
45260 */
45261 static int getAndInitPage(
45262   BtShared *pBt,          /* The database file */
45263   Pgno pgno,           /* Number of the page to get */
45264   MemPage **ppPage     /* Write the page pointer here */
45265 ){
45266   int rc;
45267   assert( sqlite3_mutex_held(pBt->mutex) );
45268
45269   if( pgno>btreePagecount(pBt) ){
45270     rc = SQLITE_CORRUPT_BKPT;
45271   }else{
45272     rc = btreeGetPage(pBt, pgno, ppPage, 0);
45273     if( rc==SQLITE_OK ){
45274       rc = btreeInitPage(*ppPage);
45275       if( rc!=SQLITE_OK ){
45276         releasePage(*ppPage);
45277       }
45278     }
45279   }
45280
45281   testcase( pgno==0 );
45282   assert( pgno!=0 || rc==SQLITE_CORRUPT );
45283   return rc;
45284 }
45285
45286 /*
45287 ** Release a MemPage.  This should be called once for each prior
45288 ** call to btreeGetPage.
45289 */
45290 static void releasePage(MemPage *pPage){
45291   if( pPage ){
45292     assert( pPage->aData );
45293     assert( pPage->pBt );
45294     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
45295     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
45296     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45297     sqlite3PagerUnref(pPage->pDbPage);
45298   }
45299 }
45300
45301 /*
45302 ** During a rollback, when the pager reloads information into the cache
45303 ** so that the cache is restored to its original state at the start of
45304 ** the transaction, for each page restored this routine is called.
45305 **
45306 ** This routine needs to reset the extra data section at the end of the
45307 ** page to agree with the restored data.
45308 */
45309 static void pageReinit(DbPage *pData){
45310   MemPage *pPage;
45311   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
45312   assert( sqlite3PagerPageRefcount(pData)>0 );
45313   if( pPage->isInit ){
45314     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45315     pPage->isInit = 0;
45316     if( sqlite3PagerPageRefcount(pData)>1 ){
45317       /* pPage might not be a btree page;  it might be an overflow page
45318       ** or ptrmap page or a free page.  In those cases, the following
45319       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
45320       ** But no harm is done by this.  And it is very important that
45321       ** btreeInitPage() be called on every btree page so we make
45322       ** the call for every page that comes in for re-initing. */
45323       btreeInitPage(pPage);
45324     }
45325   }
45326 }
45327
45328 /*
45329 ** Invoke the busy handler for a btree.
45330 */
45331 static int btreeInvokeBusyHandler(void *pArg){
45332   BtShared *pBt = (BtShared*)pArg;
45333   assert( pBt->db );
45334   assert( sqlite3_mutex_held(pBt->db->mutex) );
45335   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
45336 }
45337
45338 /*
45339 ** Open a database file.
45340 ** 
45341 ** zFilename is the name of the database file.  If zFilename is NULL
45342 ** a new database with a random name is created.  This randomly named
45343 ** database file will be deleted when sqlite3BtreeClose() is called.
45344 ** If zFilename is ":memory:" then an in-memory database is created
45345 ** that is automatically destroyed when it is closed.
45346 **
45347 ** If the database is already opened in the same database connection
45348 ** and we are in shared cache mode, then the open will fail with an
45349 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
45350 ** objects in the same database connection since doing so will lead
45351 ** to problems with locking.
45352 */
45353 SQLITE_PRIVATE int sqlite3BtreeOpen(
45354   const char *zFilename,  /* Name of the file containing the BTree database */
45355   sqlite3 *db,            /* Associated database handle */
45356   Btree **ppBtree,        /* Pointer to new Btree object written here */
45357   int flags,              /* Options */
45358   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
45359 ){
45360   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
45361   BtShared *pBt = 0;             /* Shared part of btree structure */
45362   Btree *p;                      /* Handle to return */
45363   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
45364   int rc = SQLITE_OK;            /* Result code from this function */
45365   u8 nReserve;                   /* Byte of unused space on each page */
45366   unsigned char zDbHeader[100];  /* Database header content */
45367
45368   /* Set the variable isMemdb to true for an in-memory database, or 
45369   ** false for a file-based database. This symbol is only required if
45370   ** either of the shared-data or autovacuum features are compiled 
45371   ** into the library.
45372   */
45373 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
45374   #ifdef SQLITE_OMIT_MEMORYDB
45375     const int isMemdb = 0;
45376   #else
45377     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
45378   #endif
45379 #endif
45380
45381   assert( db!=0 );
45382   assert( sqlite3_mutex_held(db->mutex) );
45383
45384   pVfs = db->pVfs;
45385   p = sqlite3MallocZero(sizeof(Btree));
45386   if( !p ){
45387     return SQLITE_NOMEM;
45388   }
45389   p->inTrans = TRANS_NONE;
45390   p->db = db;
45391 #ifndef SQLITE_OMIT_SHARED_CACHE
45392   p->lock.pBtree = p;
45393   p->lock.iTable = 1;
45394 #endif
45395
45396 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45397   /*
45398   ** If this Btree is a candidate for shared cache, try to find an
45399   ** existing BtShared object that we can share with
45400   */
45401   if( isMemdb==0 && zFilename && zFilename[0] ){
45402     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
45403       int nFullPathname = pVfs->mxPathname+1;
45404       char *zFullPathname = sqlite3Malloc(nFullPathname);
45405       sqlite3_mutex *mutexShared;
45406       p->sharable = 1;
45407       if( !zFullPathname ){
45408         sqlite3_free(p);
45409         return SQLITE_NOMEM;
45410       }
45411       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
45412       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
45413       sqlite3_mutex_enter(mutexOpen);
45414       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45415       sqlite3_mutex_enter(mutexShared);
45416       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
45417         assert( pBt->nRef>0 );
45418         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
45419                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
45420           int iDb;
45421           for(iDb=db->nDb-1; iDb>=0; iDb--){
45422             Btree *pExisting = db->aDb[iDb].pBt;
45423             if( pExisting && pExisting->pBt==pBt ){
45424               sqlite3_mutex_leave(mutexShared);
45425               sqlite3_mutex_leave(mutexOpen);
45426               sqlite3_free(zFullPathname);
45427               sqlite3_free(p);
45428               return SQLITE_CONSTRAINT;
45429             }
45430           }
45431           p->pBt = pBt;
45432           pBt->nRef++;
45433           break;
45434         }
45435       }
45436       sqlite3_mutex_leave(mutexShared);
45437       sqlite3_free(zFullPathname);
45438     }
45439 #ifdef SQLITE_DEBUG
45440     else{
45441       /* In debug mode, we mark all persistent databases as sharable
45442       ** even when they are not.  This exercises the locking code and
45443       ** gives more opportunity for asserts(sqlite3_mutex_held())
45444       ** statements to find locking problems.
45445       */
45446       p->sharable = 1;
45447     }
45448 #endif
45449   }
45450 #endif
45451   if( pBt==0 ){
45452     /*
45453     ** The following asserts make sure that structures used by the btree are
45454     ** the right size.  This is to guard against size changes that result
45455     ** when compiling on a different architecture.
45456     */
45457     assert( sizeof(i64)==8 || sizeof(i64)==4 );
45458     assert( sizeof(u64)==8 || sizeof(u64)==4 );
45459     assert( sizeof(u32)==4 );
45460     assert( sizeof(u16)==2 );
45461     assert( sizeof(Pgno)==4 );
45462   
45463     pBt = sqlite3MallocZero( sizeof(*pBt) );
45464     if( pBt==0 ){
45465       rc = SQLITE_NOMEM;
45466       goto btree_open_out;
45467     }
45468     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
45469                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
45470     if( rc==SQLITE_OK ){
45471       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
45472     }
45473     if( rc!=SQLITE_OK ){
45474       goto btree_open_out;
45475     }
45476     pBt->db = db;
45477     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
45478     p->pBt = pBt;
45479   
45480     pBt->pCursor = 0;
45481     pBt->pPage1 = 0;
45482     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
45483 #ifdef SQLITE_SECURE_DELETE
45484     pBt->secureDelete = 1;
45485 #endif
45486     pBt->pageSize = get2byte(&zDbHeader[16]);
45487     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
45488          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
45489       pBt->pageSize = 0;
45490 #ifndef SQLITE_OMIT_AUTOVACUUM
45491       /* If the magic name ":memory:" will create an in-memory database, then
45492       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
45493       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
45494       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
45495       ** regular file-name. In this case the auto-vacuum applies as per normal.
45496       */
45497       if( zFilename && !isMemdb ){
45498         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
45499         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
45500       }
45501 #endif
45502       nReserve = 0;
45503     }else{
45504       nReserve = zDbHeader[20];
45505       pBt->pageSizeFixed = 1;
45506 #ifndef SQLITE_OMIT_AUTOVACUUM
45507       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
45508       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
45509 #endif
45510     }
45511     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45512     if( rc ) goto btree_open_out;
45513     pBt->usableSize = pBt->pageSize - nReserve;
45514     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
45515    
45516 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45517     /* Add the new BtShared object to the linked list sharable BtShareds.
45518     */
45519     if( p->sharable ){
45520       sqlite3_mutex *mutexShared;
45521       pBt->nRef = 1;
45522       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45523       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
45524         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
45525         if( pBt->mutex==0 ){
45526           rc = SQLITE_NOMEM;
45527           db->mallocFailed = 0;
45528           goto btree_open_out;
45529         }
45530       }
45531       sqlite3_mutex_enter(mutexShared);
45532       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
45533       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
45534       sqlite3_mutex_leave(mutexShared);
45535     }
45536 #endif
45537   }
45538
45539 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45540   /* If the new Btree uses a sharable pBtShared, then link the new
45541   ** Btree into the list of all sharable Btrees for the same connection.
45542   ** The list is kept in ascending order by pBt address.
45543   */
45544   if( p->sharable ){
45545     int i;
45546     Btree *pSib;
45547     for(i=0; i<db->nDb; i++){
45548       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
45549         while( pSib->pPrev ){ pSib = pSib->pPrev; }
45550         if( p->pBt<pSib->pBt ){
45551           p->pNext = pSib;
45552           p->pPrev = 0;
45553           pSib->pPrev = p;
45554         }else{
45555           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
45556             pSib = pSib->pNext;
45557           }
45558           p->pNext = pSib->pNext;
45559           p->pPrev = pSib;
45560           if( p->pNext ){
45561             p->pNext->pPrev = p;
45562           }
45563           pSib->pNext = p;
45564         }
45565         break;
45566       }
45567     }
45568   }
45569 #endif
45570   *ppBtree = p;
45571
45572 btree_open_out:
45573   if( rc!=SQLITE_OK ){
45574     if( pBt && pBt->pPager ){
45575       sqlite3PagerClose(pBt->pPager);
45576     }
45577     sqlite3_free(pBt);
45578     sqlite3_free(p);
45579     *ppBtree = 0;
45580   }
45581   if( mutexOpen ){
45582     assert( sqlite3_mutex_held(mutexOpen) );
45583     sqlite3_mutex_leave(mutexOpen);
45584   }
45585   return rc;
45586 }
45587
45588 /*
45589 ** Decrement the BtShared.nRef counter.  When it reaches zero,
45590 ** remove the BtShared structure from the sharing list.  Return
45591 ** true if the BtShared.nRef counter reaches zero and return
45592 ** false if it is still positive.
45593 */
45594 static int removeFromSharingList(BtShared *pBt){
45595 #ifndef SQLITE_OMIT_SHARED_CACHE
45596   sqlite3_mutex *pMaster;
45597   BtShared *pList;
45598   int removed = 0;
45599
45600   assert( sqlite3_mutex_notheld(pBt->mutex) );
45601   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45602   sqlite3_mutex_enter(pMaster);
45603   pBt->nRef--;
45604   if( pBt->nRef<=0 ){
45605     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
45606       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
45607     }else{
45608       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
45609       while( ALWAYS(pList) && pList->pNext!=pBt ){
45610         pList=pList->pNext;
45611       }
45612       if( ALWAYS(pList) ){
45613         pList->pNext = pBt->pNext;
45614       }
45615     }
45616     if( SQLITE_THREADSAFE ){
45617       sqlite3_mutex_free(pBt->mutex);
45618     }
45619     removed = 1;
45620   }
45621   sqlite3_mutex_leave(pMaster);
45622   return removed;
45623 #else
45624   return 1;
45625 #endif
45626 }
45627
45628 /*
45629 ** Make sure pBt->pTmpSpace points to an allocation of 
45630 ** MX_CELL_SIZE(pBt) bytes.
45631 */
45632 static void allocateTempSpace(BtShared *pBt){
45633   if( !pBt->pTmpSpace ){
45634     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
45635   }
45636 }
45637
45638 /*
45639 ** Free the pBt->pTmpSpace allocation
45640 */
45641 static void freeTempSpace(BtShared *pBt){
45642   sqlite3PageFree( pBt->pTmpSpace);
45643   pBt->pTmpSpace = 0;
45644 }
45645
45646 /*
45647 ** Close an open database and invalidate all cursors.
45648 */
45649 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
45650   BtShared *pBt = p->pBt;
45651   BtCursor *pCur;
45652
45653   /* Close all cursors opened via this handle.  */
45654   assert( sqlite3_mutex_held(p->db->mutex) );
45655   sqlite3BtreeEnter(p);
45656   pCur = pBt->pCursor;
45657   while( pCur ){
45658     BtCursor *pTmp = pCur;
45659     pCur = pCur->pNext;
45660     if( pTmp->pBtree==p ){
45661       sqlite3BtreeCloseCursor(pTmp);
45662     }
45663   }
45664
45665   /* Rollback any active transaction and free the handle structure.
45666   ** The call to sqlite3BtreeRollback() drops any table-locks held by
45667   ** this handle.
45668   */
45669   sqlite3BtreeRollback(p);
45670   sqlite3BtreeLeave(p);
45671
45672   /* If there are still other outstanding references to the shared-btree
45673   ** structure, return now. The remainder of this procedure cleans 
45674   ** up the shared-btree.
45675   */
45676   assert( p->wantToLock==0 && p->locked==0 );
45677   if( !p->sharable || removeFromSharingList(pBt) ){
45678     /* The pBt is no longer on the sharing list, so we can access
45679     ** it without having to hold the mutex.
45680     **
45681     ** Clean out and delete the BtShared object.
45682     */
45683     assert( !pBt->pCursor );
45684     sqlite3PagerClose(pBt->pPager);
45685     if( pBt->xFreeSchema && pBt->pSchema ){
45686       pBt->xFreeSchema(pBt->pSchema);
45687     }
45688     sqlite3_free(pBt->pSchema);
45689     freeTempSpace(pBt);
45690     sqlite3_free(pBt);
45691   }
45692
45693 #ifndef SQLITE_OMIT_SHARED_CACHE
45694   assert( p->wantToLock==0 );
45695   assert( p->locked==0 );
45696   if( p->pPrev ) p->pPrev->pNext = p->pNext;
45697   if( p->pNext ) p->pNext->pPrev = p->pPrev;
45698 #endif
45699
45700   sqlite3_free(p);
45701   return SQLITE_OK;
45702 }
45703
45704 /*
45705 ** Change the limit on the number of pages allowed in the cache.
45706 **
45707 ** The maximum number of cache pages is set to the absolute
45708 ** value of mxPage.  If mxPage is negative, the pager will
45709 ** operate asynchronously - it will not stop to do fsync()s
45710 ** to insure data is written to the disk surface before
45711 ** continuing.  Transactions still work if synchronous is off,
45712 ** and the database cannot be corrupted if this program
45713 ** crashes.  But if the operating system crashes or there is
45714 ** an abrupt power failure when synchronous is off, the database
45715 ** could be left in an inconsistent and unrecoverable state.
45716 ** Synchronous is on by default so database corruption is not
45717 ** normally a worry.
45718 */
45719 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
45720   BtShared *pBt = p->pBt;
45721   assert( sqlite3_mutex_held(p->db->mutex) );
45722   sqlite3BtreeEnter(p);
45723   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
45724   sqlite3BtreeLeave(p);
45725   return SQLITE_OK;
45726 }
45727
45728 /*
45729 ** Change the way data is synced to disk in order to increase or decrease
45730 ** how well the database resists damage due to OS crashes and power
45731 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
45732 ** there is a high probability of damage)  Level 2 is the default.  There
45733 ** is a very low but non-zero probability of damage.  Level 3 reduces the
45734 ** probability of damage to near zero but with a write performance reduction.
45735 */
45736 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
45737 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
45738   BtShared *pBt = p->pBt;
45739   assert( sqlite3_mutex_held(p->db->mutex) );
45740   sqlite3BtreeEnter(p);
45741   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
45742   sqlite3BtreeLeave(p);
45743   return SQLITE_OK;
45744 }
45745 #endif
45746
45747 /*
45748 ** Return TRUE if the given btree is set to safety level 1.  In other
45749 ** words, return TRUE if no sync() occurs on the disk files.
45750 */
45751 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
45752   BtShared *pBt = p->pBt;
45753   int rc;
45754   assert( sqlite3_mutex_held(p->db->mutex) );  
45755   sqlite3BtreeEnter(p);
45756   assert( pBt && pBt->pPager );
45757   rc = sqlite3PagerNosync(pBt->pPager);
45758   sqlite3BtreeLeave(p);
45759   return rc;
45760 }
45761
45762 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
45763 /*
45764 ** Change the default pages size and the number of reserved bytes per page.
45765 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
45766 ** without changing anything.
45767 **
45768 ** The page size must be a power of 2 between 512 and 65536.  If the page
45769 ** size supplied does not meet this constraint then the page size is not
45770 ** changed.
45771 **
45772 ** Page sizes are constrained to be a power of two so that the region
45773 ** of the database file used for locking (beginning at PENDING_BYTE,
45774 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
45775 ** at the beginning of a page.
45776 **
45777 ** If parameter nReserve is less than zero, then the number of reserved
45778 ** bytes per page is left unchanged.
45779 **
45780 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
45781 ** and autovacuum mode can no longer be changed.
45782 */
45783 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
45784   int rc = SQLITE_OK;
45785   BtShared *pBt = p->pBt;
45786   assert( nReserve>=-1 && nReserve<=255 );
45787   sqlite3BtreeEnter(p);
45788   if( pBt->pageSizeFixed ){
45789     sqlite3BtreeLeave(p);
45790     return SQLITE_READONLY;
45791   }
45792   if( nReserve<0 ){
45793     nReserve = pBt->pageSize - pBt->usableSize;
45794   }
45795   assert( nReserve>=0 && nReserve<=255 );
45796   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
45797         ((pageSize-1)&pageSize)==0 ){
45798     assert( (pageSize & 7)==0 );
45799     assert( !pBt->pPage1 && !pBt->pCursor );
45800     pBt->pageSize = (u16)pageSize;
45801     freeTempSpace(pBt);
45802   }
45803   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45804   pBt->usableSize = pBt->pageSize - (u16)nReserve;
45805   if( iFix ) pBt->pageSizeFixed = 1;
45806   sqlite3BtreeLeave(p);
45807   return rc;
45808 }
45809
45810 /*
45811 ** Return the currently defined page size
45812 */
45813 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
45814   return p->pBt->pageSize;
45815 }
45816
45817 /*
45818 ** Return the number of bytes of space at the end of every page that
45819 ** are intentually left unused.  This is the "reserved" space that is
45820 ** sometimes used by extensions.
45821 */
45822 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
45823   int n;
45824   sqlite3BtreeEnter(p);
45825   n = p->pBt->pageSize - p->pBt->usableSize;
45826   sqlite3BtreeLeave(p);
45827   return n;
45828 }
45829
45830 /*
45831 ** Set the maximum page count for a database if mxPage is positive.
45832 ** No changes are made if mxPage is 0 or negative.
45833 ** Regardless of the value of mxPage, return the maximum page count.
45834 */
45835 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
45836   int n;
45837   sqlite3BtreeEnter(p);
45838   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
45839   sqlite3BtreeLeave(p);
45840   return n;
45841 }
45842
45843 /*
45844 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
45845 ** then make no changes.  Always return the value of the secureDelete
45846 ** setting after the change.
45847 */
45848 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
45849   int b;
45850   if( p==0 ) return 0;
45851   sqlite3BtreeEnter(p);
45852   if( newFlag>=0 ){
45853     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
45854   } 
45855   b = p->pBt->secureDelete;
45856   sqlite3BtreeLeave(p);
45857   return b;
45858 }
45859 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
45860
45861 /*
45862 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
45863 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
45864 ** is disabled. The default value for the auto-vacuum property is 
45865 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
45866 */
45867 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
45868 #ifdef SQLITE_OMIT_AUTOVACUUM
45869   return SQLITE_READONLY;
45870 #else
45871   BtShared *pBt = p->pBt;
45872   int rc = SQLITE_OK;
45873   u8 av = (u8)autoVacuum;
45874
45875   sqlite3BtreeEnter(p);
45876   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
45877     rc = SQLITE_READONLY;
45878   }else{
45879     pBt->autoVacuum = av ?1:0;
45880     pBt->incrVacuum = av==2 ?1:0;
45881   }
45882   sqlite3BtreeLeave(p);
45883   return rc;
45884 #endif
45885 }
45886
45887 /*
45888 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
45889 ** enabled 1 is returned. Otherwise 0.
45890 */
45891 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
45892 #ifdef SQLITE_OMIT_AUTOVACUUM
45893   return BTREE_AUTOVACUUM_NONE;
45894 #else
45895   int rc;
45896   sqlite3BtreeEnter(p);
45897   rc = (
45898     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
45899     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
45900     BTREE_AUTOVACUUM_INCR
45901   );
45902   sqlite3BtreeLeave(p);
45903   return rc;
45904 #endif
45905 }
45906
45907
45908 /*
45909 ** Get a reference to pPage1 of the database file.  This will
45910 ** also acquire a readlock on that file.
45911 **
45912 ** SQLITE_OK is returned on success.  If the file is not a
45913 ** well-formed database file, then SQLITE_CORRUPT is returned.
45914 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
45915 ** is returned if we run out of memory. 
45916 */
45917 static int lockBtree(BtShared *pBt){
45918   int rc;              /* Result code from subfunctions */
45919   MemPage *pPage1;     /* Page 1 of the database file */
45920   int nPage;           /* Number of pages in the database */
45921   int nPageFile = 0;   /* Number of pages in the database file */
45922   int nPageHeader;     /* Number of pages in the database according to hdr */
45923
45924   assert( sqlite3_mutex_held(pBt->mutex) );
45925   assert( pBt->pPage1==0 );
45926   rc = sqlite3PagerSharedLock(pBt->pPager);
45927   if( rc!=SQLITE_OK ) return rc;
45928   rc = btreeGetPage(pBt, 1, &pPage1, 0);
45929   if( rc!=SQLITE_OK ) return rc;
45930
45931   /* Do some checking to help insure the file we opened really is
45932   ** a valid database file. 
45933   */
45934   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
45935   if( (rc = sqlite3PagerPagecount(pBt->pPager, &nPageFile))!=SQLITE_OK ){;
45936     goto page1_init_failed;
45937   }
45938   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
45939     nPage = nPageFile;
45940   }
45941   if( nPage>0 ){
45942     int pageSize;
45943     int usableSize;
45944     u8 *page1 = pPage1->aData;
45945     rc = SQLITE_NOTADB;
45946     if( memcmp(page1, zMagicHeader, 16)!=0 ){
45947       goto page1_init_failed;
45948     }
45949
45950 #ifdef SQLITE_OMIT_WAL
45951     if( page1[18]>1 ){
45952       pBt->readOnly = 1;
45953     }
45954     if( page1[19]>1 ){
45955       goto page1_init_failed;
45956     }
45957 #else
45958     if( page1[18]>2 ){
45959       pBt->readOnly = 1;
45960     }
45961     if( page1[19]>2 ){
45962       goto page1_init_failed;
45963     }
45964
45965     /* If the write version is set to 2, this database should be accessed
45966     ** in WAL mode. If the log is not already open, open it now. Then 
45967     ** return SQLITE_OK and return without populating BtShared.pPage1.
45968     ** The caller detects this and calls this function again. This is
45969     ** required as the version of page 1 currently in the page1 buffer
45970     ** may not be the latest version - there may be a newer one in the log
45971     ** file.
45972     */
45973     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
45974       int isOpen = 0;
45975       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
45976       if( rc!=SQLITE_OK ){
45977         goto page1_init_failed;
45978       }else if( isOpen==0 ){
45979         releasePage(pPage1);
45980         return SQLITE_OK;
45981       }
45982       rc = SQLITE_NOTADB;
45983     }
45984 #endif
45985
45986     /* The maximum embedded fraction must be exactly 25%.  And the minimum
45987     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
45988     ** The original design allowed these amounts to vary, but as of
45989     ** version 3.6.0, we require them to be fixed.
45990     */
45991     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
45992       goto page1_init_failed;
45993     }
45994     pageSize = get2byte(&page1[16]);
45995     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
45996         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
45997     ){
45998       goto page1_init_failed;
45999     }
46000     assert( (pageSize & 7)==0 );
46001     usableSize = pageSize - page1[20];
46002     if( pageSize!=pBt->pageSize ){
46003       /* After reading the first page of the database assuming a page size
46004       ** of BtShared.pageSize, we have discovered that the page-size is
46005       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
46006       ** zero and return SQLITE_OK. The caller will call this function
46007       ** again with the correct page-size.
46008       */
46009       releasePage(pPage1);
46010       pBt->usableSize = (u16)usableSize;
46011       pBt->pageSize = (u16)pageSize;
46012       freeTempSpace(pBt);
46013       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
46014                                    pageSize-usableSize);
46015       return rc;
46016     }
46017     if( nPageHeader>nPageFile ){
46018       rc = SQLITE_CORRUPT_BKPT;
46019       goto page1_init_failed;
46020     }
46021     if( usableSize<480 ){
46022       goto page1_init_failed;
46023     }
46024     pBt->pageSize = (u16)pageSize;
46025     pBt->usableSize = (u16)usableSize;
46026 #ifndef SQLITE_OMIT_AUTOVACUUM
46027     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
46028     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
46029 #endif
46030   }
46031
46032   /* maxLocal is the maximum amount of payload to store locally for
46033   ** a cell.  Make sure it is small enough so that at least minFanout
46034   ** cells can will fit on one page.  We assume a 10-byte page header.
46035   ** Besides the payload, the cell must store:
46036   **     2-byte pointer to the cell
46037   **     4-byte child pointer
46038   **     9-byte nKey value
46039   **     4-byte nData value
46040   **     4-byte overflow page pointer
46041   ** So a cell consists of a 2-byte poiner, a header which is as much as
46042   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
46043   ** page pointer.
46044   */
46045   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
46046   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
46047   pBt->maxLeaf = pBt->usableSize - 35;
46048   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
46049   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
46050   pBt->pPage1 = pPage1;
46051   pBt->nPage = nPage;
46052   return SQLITE_OK;
46053
46054 page1_init_failed:
46055   releasePage(pPage1);
46056   pBt->pPage1 = 0;
46057   return rc;
46058 }
46059
46060 /*
46061 ** If there are no outstanding cursors and we are not in the middle
46062 ** of a transaction but there is a read lock on the database, then
46063 ** this routine unrefs the first page of the database file which 
46064 ** has the effect of releasing the read lock.
46065 **
46066 ** If there is a transaction in progress, this routine is a no-op.
46067 */
46068 static void unlockBtreeIfUnused(BtShared *pBt){
46069   assert( sqlite3_mutex_held(pBt->mutex) );
46070   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
46071   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
46072     assert( pBt->pPage1->aData );
46073     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
46074     assert( pBt->pPage1->aData );
46075     releasePage(pBt->pPage1);
46076     pBt->pPage1 = 0;
46077   }
46078 }
46079
46080 /*
46081 ** If pBt points to an empty file then convert that empty file
46082 ** into a new empty database by initializing the first page of
46083 ** the database.
46084 */
46085 static int newDatabase(BtShared *pBt){
46086   MemPage *pP1;
46087   unsigned char *data;
46088   int rc;
46089
46090   assert( sqlite3_mutex_held(pBt->mutex) );
46091   if( pBt->nPage>0 ){
46092     return SQLITE_OK;
46093   }
46094   pP1 = pBt->pPage1;
46095   assert( pP1!=0 );
46096   data = pP1->aData;
46097   rc = sqlite3PagerWrite(pP1->pDbPage);
46098   if( rc ) return rc;
46099   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
46100   assert( sizeof(zMagicHeader)==16 );
46101   put2byte(&data[16], pBt->pageSize);
46102   data[18] = 1;
46103   data[19] = 1;
46104   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
46105   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
46106   data[21] = 64;
46107   data[22] = 32;
46108   data[23] = 32;
46109   memset(&data[24], 0, 100-24);
46110   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
46111   pBt->pageSizeFixed = 1;
46112 #ifndef SQLITE_OMIT_AUTOVACUUM
46113   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
46114   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
46115   put4byte(&data[36 + 4*4], pBt->autoVacuum);
46116   put4byte(&data[36 + 7*4], pBt->incrVacuum);
46117 #endif
46118   pBt->nPage = 1;
46119   data[31] = 1;
46120   return SQLITE_OK;
46121 }
46122
46123 /*
46124 ** Attempt to start a new transaction. A write-transaction
46125 ** is started if the second argument is nonzero, otherwise a read-
46126 ** transaction.  If the second argument is 2 or more and exclusive
46127 ** transaction is started, meaning that no other process is allowed
46128 ** to access the database.  A preexisting transaction may not be
46129 ** upgraded to exclusive by calling this routine a second time - the
46130 ** exclusivity flag only works for a new transaction.
46131 **
46132 ** A write-transaction must be started before attempting any 
46133 ** changes to the database.  None of the following routines 
46134 ** will work unless a transaction is started first:
46135 **
46136 **      sqlite3BtreeCreateTable()
46137 **      sqlite3BtreeCreateIndex()
46138 **      sqlite3BtreeClearTable()
46139 **      sqlite3BtreeDropTable()
46140 **      sqlite3BtreeInsert()
46141 **      sqlite3BtreeDelete()
46142 **      sqlite3BtreeUpdateMeta()
46143 **
46144 ** If an initial attempt to acquire the lock fails because of lock contention
46145 ** and the database was previously unlocked, then invoke the busy handler
46146 ** if there is one.  But if there was previously a read-lock, do not
46147 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
46148 ** returned when there is already a read-lock in order to avoid a deadlock.
46149 **
46150 ** Suppose there are two processes A and B.  A has a read lock and B has
46151 ** a reserved lock.  B tries to promote to exclusive but is blocked because
46152 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
46153 ** One or the other of the two processes must give way or there can be
46154 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
46155 ** when A already has a read lock, we encourage A to give up and let B
46156 ** proceed.
46157 */
46158 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
46159   sqlite3 *pBlock = 0;
46160   BtShared *pBt = p->pBt;
46161   int rc = SQLITE_OK;
46162
46163   sqlite3BtreeEnter(p);
46164   btreeIntegrity(p);
46165
46166   /* If the btree is already in a write-transaction, or it
46167   ** is already in a read-transaction and a read-transaction
46168   ** is requested, this is a no-op.
46169   */
46170   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
46171     goto trans_begun;
46172   }
46173
46174   /* Write transactions are not possible on a read-only database */
46175   if( pBt->readOnly && wrflag ){
46176     rc = SQLITE_READONLY;
46177     goto trans_begun;
46178   }
46179
46180 #ifndef SQLITE_OMIT_SHARED_CACHE
46181   /* If another database handle has already opened a write transaction 
46182   ** on this shared-btree structure and a second write transaction is
46183   ** requested, return SQLITE_LOCKED.
46184   */
46185   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
46186     pBlock = pBt->pWriter->db;
46187   }else if( wrflag>1 ){
46188     BtLock *pIter;
46189     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
46190       if( pIter->pBtree!=p ){
46191         pBlock = pIter->pBtree->db;
46192         break;
46193       }
46194     }
46195   }
46196   if( pBlock ){
46197     sqlite3ConnectionBlocked(p->db, pBlock);
46198     rc = SQLITE_LOCKED_SHAREDCACHE;
46199     goto trans_begun;
46200   }
46201 #endif
46202
46203   /* Any read-only or read-write transaction implies a read-lock on 
46204   ** page 1. So if some other shared-cache client already has a write-lock 
46205   ** on page 1, the transaction cannot be opened. */
46206   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
46207   if( SQLITE_OK!=rc ) goto trans_begun;
46208
46209   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
46210   do {
46211     /* Call lockBtree() until either pBt->pPage1 is populated or
46212     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
46213     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
46214     ** reading page 1 it discovers that the page-size of the database 
46215     ** file is not pBt->pageSize. In this case lockBtree() will update
46216     ** pBt->pageSize to the page-size of the file on disk.
46217     */
46218     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
46219
46220     if( rc==SQLITE_OK && wrflag ){
46221       if( pBt->readOnly ){
46222         rc = SQLITE_READONLY;
46223       }else{
46224         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
46225         if( rc==SQLITE_OK ){
46226           rc = newDatabase(pBt);
46227         }
46228       }
46229     }
46230   
46231     if( rc!=SQLITE_OK ){
46232       unlockBtreeIfUnused(pBt);
46233     }
46234   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
46235           btreeInvokeBusyHandler(pBt) );
46236
46237   if( rc==SQLITE_OK ){
46238     if( p->inTrans==TRANS_NONE ){
46239       pBt->nTransaction++;
46240 #ifndef SQLITE_OMIT_SHARED_CACHE
46241       if( p->sharable ){
46242         assert( p->lock.pBtree==p && p->lock.iTable==1 );
46243         p->lock.eLock = READ_LOCK;
46244         p->lock.pNext = pBt->pLock;
46245         pBt->pLock = &p->lock;
46246       }
46247 #endif
46248     }
46249     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
46250     if( p->inTrans>pBt->inTransaction ){
46251       pBt->inTransaction = p->inTrans;
46252     }
46253     if( wrflag ){
46254       MemPage *pPage1 = pBt->pPage1;
46255 #ifndef SQLITE_OMIT_SHARED_CACHE
46256       assert( !pBt->pWriter );
46257       pBt->pWriter = p;
46258       pBt->isExclusive = (u8)(wrflag>1);
46259 #endif
46260
46261       /* If the db-size header field is incorrect (as it may be if an old
46262       ** client has been writing the database file), update it now. Doing
46263       ** this sooner rather than later means the database size can safely 
46264       ** re-read the database size from page 1 if a savepoint or transaction
46265       ** rollback occurs within the transaction.
46266       */
46267       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
46268         rc = sqlite3PagerWrite(pPage1->pDbPage);
46269         if( rc==SQLITE_OK ){
46270           put4byte(&pPage1->aData[28], pBt->nPage);
46271         }
46272       }
46273     }
46274   }
46275
46276
46277 trans_begun:
46278   if( rc==SQLITE_OK && wrflag ){
46279     /* This call makes sure that the pager has the correct number of
46280     ** open savepoints. If the second parameter is greater than 0 and
46281     ** the sub-journal is not already open, then it will be opened here.
46282     */
46283     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
46284   }
46285
46286   btreeIntegrity(p);
46287   sqlite3BtreeLeave(p);
46288   return rc;
46289 }
46290
46291 #ifndef SQLITE_OMIT_AUTOVACUUM
46292
46293 /*
46294 ** Set the pointer-map entries for all children of page pPage. Also, if
46295 ** pPage contains cells that point to overflow pages, set the pointer
46296 ** map entries for the overflow pages as well.
46297 */
46298 static int setChildPtrmaps(MemPage *pPage){
46299   int i;                             /* Counter variable */
46300   int nCell;                         /* Number of cells in page pPage */
46301   int rc;                            /* Return code */
46302   BtShared *pBt = pPage->pBt;
46303   u8 isInitOrig = pPage->isInit;
46304   Pgno pgno = pPage->pgno;
46305
46306   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46307   rc = btreeInitPage(pPage);
46308   if( rc!=SQLITE_OK ){
46309     goto set_child_ptrmaps_out;
46310   }
46311   nCell = pPage->nCell;
46312
46313   for(i=0; i<nCell; i++){
46314     u8 *pCell = findCell(pPage, i);
46315
46316     ptrmapPutOvflPtr(pPage, pCell, &rc);
46317
46318     if( !pPage->leaf ){
46319       Pgno childPgno = get4byte(pCell);
46320       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
46321     }
46322   }
46323
46324   if( !pPage->leaf ){
46325     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
46326     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
46327   }
46328
46329 set_child_ptrmaps_out:
46330   pPage->isInit = isInitOrig;
46331   return rc;
46332 }
46333
46334 /*
46335 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
46336 ** that it points to iTo. Parameter eType describes the type of pointer to
46337 ** be modified, as  follows:
46338 **
46339 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
46340 **                   page of pPage.
46341 **
46342 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
46343 **                   page pointed to by one of the cells on pPage.
46344 **
46345 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
46346 **                   overflow page in the list.
46347 */
46348 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
46349   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46350   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46351   if( eType==PTRMAP_OVERFLOW2 ){
46352     /* The pointer is always the first 4 bytes of the page in this case.  */
46353     if( get4byte(pPage->aData)!=iFrom ){
46354       return SQLITE_CORRUPT_BKPT;
46355     }
46356     put4byte(pPage->aData, iTo);
46357   }else{
46358     u8 isInitOrig = pPage->isInit;
46359     int i;
46360     int nCell;
46361
46362     btreeInitPage(pPage);
46363     nCell = pPage->nCell;
46364
46365     for(i=0; i<nCell; i++){
46366       u8 *pCell = findCell(pPage, i);
46367       if( eType==PTRMAP_OVERFLOW1 ){
46368         CellInfo info;
46369         btreeParseCellPtr(pPage, pCell, &info);
46370         if( info.iOverflow ){
46371           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
46372             put4byte(&pCell[info.iOverflow], iTo);
46373             break;
46374           }
46375         }
46376       }else{
46377         if( get4byte(pCell)==iFrom ){
46378           put4byte(pCell, iTo);
46379           break;
46380         }
46381       }
46382     }
46383   
46384     if( i==nCell ){
46385       if( eType!=PTRMAP_BTREE || 
46386           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
46387         return SQLITE_CORRUPT_BKPT;
46388       }
46389       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
46390     }
46391
46392     pPage->isInit = isInitOrig;
46393   }
46394   return SQLITE_OK;
46395 }
46396
46397
46398 /*
46399 ** Move the open database page pDbPage to location iFreePage in the 
46400 ** database. The pDbPage reference remains valid.
46401 **
46402 ** The isCommit flag indicates that there is no need to remember that
46403 ** the journal needs to be sync()ed before database page pDbPage->pgno 
46404 ** can be written to. The caller has already promised not to write to that
46405 ** page.
46406 */
46407 static int relocatePage(
46408   BtShared *pBt,           /* Btree */
46409   MemPage *pDbPage,        /* Open page to move */
46410   u8 eType,                /* Pointer map 'type' entry for pDbPage */
46411   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
46412   Pgno iFreePage,          /* The location to move pDbPage to */
46413   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
46414 ){
46415   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
46416   Pgno iDbPage = pDbPage->pgno;
46417   Pager *pPager = pBt->pPager;
46418   int rc;
46419
46420   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
46421       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
46422   assert( sqlite3_mutex_held(pBt->mutex) );
46423   assert( pDbPage->pBt==pBt );
46424
46425   /* Move page iDbPage from its current location to page number iFreePage */
46426   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
46427       iDbPage, iFreePage, iPtrPage, eType));
46428   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
46429   if( rc!=SQLITE_OK ){
46430     return rc;
46431   }
46432   pDbPage->pgno = iFreePage;
46433
46434   /* If pDbPage was a btree-page, then it may have child pages and/or cells
46435   ** that point to overflow pages. The pointer map entries for all these
46436   ** pages need to be changed.
46437   **
46438   ** If pDbPage is an overflow page, then the first 4 bytes may store a
46439   ** pointer to a subsequent overflow page. If this is the case, then
46440   ** the pointer map needs to be updated for the subsequent overflow page.
46441   */
46442   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
46443     rc = setChildPtrmaps(pDbPage);
46444     if( rc!=SQLITE_OK ){
46445       return rc;
46446     }
46447   }else{
46448     Pgno nextOvfl = get4byte(pDbPage->aData);
46449     if( nextOvfl!=0 ){
46450       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
46451       if( rc!=SQLITE_OK ){
46452         return rc;
46453       }
46454     }
46455   }
46456
46457   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
46458   ** that it points at iFreePage. Also fix the pointer map entry for
46459   ** iPtrPage.
46460   */
46461   if( eType!=PTRMAP_ROOTPAGE ){
46462     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
46463     if( rc!=SQLITE_OK ){
46464       return rc;
46465     }
46466     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
46467     if( rc!=SQLITE_OK ){
46468       releasePage(pPtrPage);
46469       return rc;
46470     }
46471     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
46472     releasePage(pPtrPage);
46473     if( rc==SQLITE_OK ){
46474       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
46475     }
46476   }
46477   return rc;
46478 }
46479
46480 /* Forward declaration required by incrVacuumStep(). */
46481 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
46482
46483 /*
46484 ** Perform a single step of an incremental-vacuum. If successful,
46485 ** return SQLITE_OK. If there is no work to do (and therefore no
46486 ** point in calling this function again), return SQLITE_DONE.
46487 **
46488 ** More specificly, this function attempts to re-organize the 
46489 ** database so that the last page of the file currently in use
46490 ** is no longer in use.
46491 **
46492 ** If the nFin parameter is non-zero, this function assumes
46493 ** that the caller will keep calling incrVacuumStep() until
46494 ** it returns SQLITE_DONE or an error, and that nFin is the
46495 ** number of pages the database file will contain after this 
46496 ** process is complete.  If nFin is zero, it is assumed that
46497 ** incrVacuumStep() will be called a finite amount of times
46498 ** which may or may not empty the freelist.  A full autovacuum
46499 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
46500 */
46501 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
46502   Pgno nFreeList;           /* Number of pages still on the free-list */
46503   int rc;
46504
46505   assert( sqlite3_mutex_held(pBt->mutex) );
46506   assert( iLastPg>nFin );
46507
46508   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
46509     u8 eType;
46510     Pgno iPtrPage;
46511
46512     nFreeList = get4byte(&pBt->pPage1->aData[36]);
46513     if( nFreeList==0 ){
46514       return SQLITE_DONE;
46515     }
46516
46517     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
46518     if( rc!=SQLITE_OK ){
46519       return rc;
46520     }
46521     if( eType==PTRMAP_ROOTPAGE ){
46522       return SQLITE_CORRUPT_BKPT;
46523     }
46524
46525     if( eType==PTRMAP_FREEPAGE ){
46526       if( nFin==0 ){
46527         /* Remove the page from the files free-list. This is not required
46528         ** if nFin is non-zero. In that case, the free-list will be
46529         ** truncated to zero after this function returns, so it doesn't 
46530         ** matter if it still contains some garbage entries.
46531         */
46532         Pgno iFreePg;
46533         MemPage *pFreePg;
46534         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
46535         if( rc!=SQLITE_OK ){
46536           return rc;
46537         }
46538         assert( iFreePg==iLastPg );
46539         releasePage(pFreePg);
46540       }
46541     } else {
46542       Pgno iFreePg;             /* Index of free page to move pLastPg to */
46543       MemPage *pLastPg;
46544
46545       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
46546       if( rc!=SQLITE_OK ){
46547         return rc;
46548       }
46549
46550       /* If nFin is zero, this loop runs exactly once and page pLastPg
46551       ** is swapped with the first free page pulled off the free list.
46552       **
46553       ** On the other hand, if nFin is greater than zero, then keep
46554       ** looping until a free-page located within the first nFin pages
46555       ** of the file is found.
46556       */
46557       do {
46558         MemPage *pFreePg;
46559         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
46560         if( rc!=SQLITE_OK ){
46561           releasePage(pLastPg);
46562           return rc;
46563         }
46564         releasePage(pFreePg);
46565       }while( nFin!=0 && iFreePg>nFin );
46566       assert( iFreePg<iLastPg );
46567       
46568       rc = sqlite3PagerWrite(pLastPg->pDbPage);
46569       if( rc==SQLITE_OK ){
46570         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
46571       }
46572       releasePage(pLastPg);
46573       if( rc!=SQLITE_OK ){
46574         return rc;
46575       }
46576     }
46577   }
46578
46579   if( nFin==0 ){
46580     iLastPg--;
46581     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
46582       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
46583         MemPage *pPg;
46584         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
46585         if( rc!=SQLITE_OK ){
46586           return rc;
46587         }
46588         rc = sqlite3PagerWrite(pPg->pDbPage);
46589         releasePage(pPg);
46590         if( rc!=SQLITE_OK ){
46591           return rc;
46592         }
46593       }
46594       iLastPg--;
46595     }
46596     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
46597     pBt->nPage = iLastPg;
46598   }
46599   return SQLITE_OK;
46600 }
46601
46602 /*
46603 ** A write-transaction must be opened before calling this function.
46604 ** It performs a single unit of work towards an incremental vacuum.
46605 **
46606 ** If the incremental vacuum is finished after this function has run,
46607 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
46608 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
46609 */
46610 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
46611   int rc;
46612   BtShared *pBt = p->pBt;
46613
46614   sqlite3BtreeEnter(p);
46615   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
46616   if( !pBt->autoVacuum ){
46617     rc = SQLITE_DONE;
46618   }else{
46619     invalidateAllOverflowCache(pBt);
46620     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
46621     if( rc==SQLITE_OK ){
46622       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46623       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
46624     }
46625   }
46626   sqlite3BtreeLeave(p);
46627   return rc;
46628 }
46629
46630 /*
46631 ** This routine is called prior to sqlite3PagerCommit when a transaction
46632 ** is commited for an auto-vacuum database.
46633 **
46634 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
46635 ** the database file should be truncated to during the commit process. 
46636 ** i.e. the database has been reorganized so that only the first *pnTrunc
46637 ** pages are in use.
46638 */
46639 static int autoVacuumCommit(BtShared *pBt){
46640   int rc = SQLITE_OK;
46641   Pager *pPager = pBt->pPager;
46642   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
46643
46644   assert( sqlite3_mutex_held(pBt->mutex) );
46645   invalidateAllOverflowCache(pBt);
46646   assert(pBt->autoVacuum);
46647   if( !pBt->incrVacuum ){
46648     Pgno nFin;         /* Number of pages in database after autovacuuming */
46649     Pgno nFree;        /* Number of pages on the freelist initially */
46650     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
46651     Pgno iFree;        /* The next page to be freed */
46652     int nEntry;        /* Number of entries on one ptrmap page */
46653     Pgno nOrig;        /* Database size before freeing */
46654
46655     nOrig = btreePagecount(pBt);
46656     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
46657       /* It is not possible to create a database for which the final page
46658       ** is either a pointer-map page or the pending-byte page. If one
46659       ** is encountered, this indicates corruption.
46660       */
46661       return SQLITE_CORRUPT_BKPT;
46662     }
46663
46664     nFree = get4byte(&pBt->pPage1->aData[36]);
46665     nEntry = pBt->usableSize/5;
46666     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
46667     nFin = nOrig - nFree - nPtrmap;
46668     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
46669       nFin--;
46670     }
46671     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
46672       nFin--;
46673     }
46674     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
46675
46676     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
46677       rc = incrVacuumStep(pBt, nFin, iFree);
46678     }
46679     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
46680       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46681       put4byte(&pBt->pPage1->aData[32], 0);
46682       put4byte(&pBt->pPage1->aData[36], 0);
46683       put4byte(&pBt->pPage1->aData[28], nFin);
46684       sqlite3PagerTruncateImage(pBt->pPager, nFin);
46685       pBt->nPage = nFin;
46686     }
46687     if( rc!=SQLITE_OK ){
46688       sqlite3PagerRollback(pPager);
46689     }
46690   }
46691
46692   assert( nRef==sqlite3PagerRefcount(pPager) );
46693   return rc;
46694 }
46695
46696 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
46697 # define setChildPtrmaps(x) SQLITE_OK
46698 #endif
46699
46700 /*
46701 ** This routine does the first phase of a two-phase commit.  This routine
46702 ** causes a rollback journal to be created (if it does not already exist)
46703 ** and populated with enough information so that if a power loss occurs
46704 ** the database can be restored to its original state by playing back
46705 ** the journal.  Then the contents of the journal are flushed out to
46706 ** the disk.  After the journal is safely on oxide, the changes to the
46707 ** database are written into the database file and flushed to oxide.
46708 ** At the end of this call, the rollback journal still exists on the
46709 ** disk and we are still holding all locks, so the transaction has not
46710 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
46711 ** commit process.
46712 **
46713 ** This call is a no-op if no write-transaction is currently active on pBt.
46714 **
46715 ** Otherwise, sync the database file for the btree pBt. zMaster points to
46716 ** the name of a master journal file that should be written into the
46717 ** individual journal file, or is NULL, indicating no master journal file 
46718 ** (single database transaction).
46719 **
46720 ** When this is called, the master journal should already have been
46721 ** created, populated with this journal pointer and synced to disk.
46722 **
46723 ** Once this is routine has returned, the only thing required to commit
46724 ** the write-transaction for this database file is to delete the journal.
46725 */
46726 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
46727   int rc = SQLITE_OK;
46728   if( p->inTrans==TRANS_WRITE ){
46729     BtShared *pBt = p->pBt;
46730     sqlite3BtreeEnter(p);
46731 #ifndef SQLITE_OMIT_AUTOVACUUM
46732     if( pBt->autoVacuum ){
46733       rc = autoVacuumCommit(pBt);
46734       if( rc!=SQLITE_OK ){
46735         sqlite3BtreeLeave(p);
46736         return rc;
46737       }
46738     }
46739 #endif
46740     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
46741     sqlite3BtreeLeave(p);
46742   }
46743   return rc;
46744 }
46745
46746 /*
46747 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
46748 ** at the conclusion of a transaction.
46749 */
46750 static void btreeEndTransaction(Btree *p){
46751   BtShared *pBt = p->pBt;
46752   assert( sqlite3BtreeHoldsMutex(p) );
46753
46754   btreeClearHasContent(pBt);
46755   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
46756     /* If there are other active statements that belong to this database
46757     ** handle, downgrade to a read-only transaction. The other statements
46758     ** may still be reading from the database.  */
46759     downgradeAllSharedCacheTableLocks(p);
46760     p->inTrans = TRANS_READ;
46761   }else{
46762     /* If the handle had any kind of transaction open, decrement the 
46763     ** transaction count of the shared btree. If the transaction count 
46764     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
46765     ** call below will unlock the pager.  */
46766     if( p->inTrans!=TRANS_NONE ){
46767       clearAllSharedCacheTableLocks(p);
46768       pBt->nTransaction--;
46769       if( 0==pBt->nTransaction ){
46770         pBt->inTransaction = TRANS_NONE;
46771       }
46772     }
46773
46774     /* Set the current transaction state to TRANS_NONE and unlock the 
46775     ** pager if this call closed the only read or write transaction.  */
46776     p->inTrans = TRANS_NONE;
46777     unlockBtreeIfUnused(pBt);
46778   }
46779
46780   btreeIntegrity(p);
46781 }
46782
46783 /*
46784 ** Commit the transaction currently in progress.
46785 **
46786 ** This routine implements the second phase of a 2-phase commit.  The
46787 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
46788 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
46789 ** routine did all the work of writing information out to disk and flushing the
46790 ** contents so that they are written onto the disk platter.  All this
46791 ** routine has to do is delete or truncate or zero the header in the
46792 ** the rollback journal (which causes the transaction to commit) and
46793 ** drop locks.
46794 **
46795 ** This will release the write lock on the database file.  If there
46796 ** are no active cursors, it also releases the read lock.
46797 */
46798 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
46799   BtShared *pBt = p->pBt;
46800
46801   sqlite3BtreeEnter(p);
46802   btreeIntegrity(p);
46803
46804   /* If the handle has a write-transaction open, commit the shared-btrees 
46805   ** transaction and set the shared state to TRANS_READ.
46806   */
46807   if( p->inTrans==TRANS_WRITE ){
46808     int rc;
46809     assert( pBt->inTransaction==TRANS_WRITE );
46810     assert( pBt->nTransaction>0 );
46811     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
46812     if( rc!=SQLITE_OK ){
46813       sqlite3BtreeLeave(p);
46814       return rc;
46815     }
46816     pBt->inTransaction = TRANS_READ;
46817   }
46818
46819   btreeEndTransaction(p);
46820   sqlite3BtreeLeave(p);
46821   return SQLITE_OK;
46822 }
46823
46824 /*
46825 ** Do both phases of a commit.
46826 */
46827 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
46828   int rc;
46829   sqlite3BtreeEnter(p);
46830   rc = sqlite3BtreeCommitPhaseOne(p, 0);
46831   if( rc==SQLITE_OK ){
46832     rc = sqlite3BtreeCommitPhaseTwo(p);
46833   }
46834   sqlite3BtreeLeave(p);
46835   return rc;
46836 }
46837
46838 #ifndef NDEBUG
46839 /*
46840 ** Return the number of write-cursors open on this handle. This is for use
46841 ** in assert() expressions, so it is only compiled if NDEBUG is not
46842 ** defined.
46843 **
46844 ** For the purposes of this routine, a write-cursor is any cursor that
46845 ** is capable of writing to the databse.  That means the cursor was
46846 ** originally opened for writing and the cursor has not be disabled
46847 ** by having its state changed to CURSOR_FAULT.
46848 */
46849 static int countWriteCursors(BtShared *pBt){
46850   BtCursor *pCur;
46851   int r = 0;
46852   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
46853     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
46854   }
46855   return r;
46856 }
46857 #endif
46858
46859 /*
46860 ** This routine sets the state to CURSOR_FAULT and the error
46861 ** code to errCode for every cursor on BtShared that pBtree
46862 ** references.
46863 **
46864 ** Every cursor is tripped, including cursors that belong
46865 ** to other database connections that happen to be sharing
46866 ** the cache with pBtree.
46867 **
46868 ** This routine gets called when a rollback occurs.
46869 ** All cursors using the same cache must be tripped
46870 ** to prevent them from trying to use the btree after
46871 ** the rollback.  The rollback may have deleted tables
46872 ** or moved root pages, so it is not sufficient to
46873 ** save the state of the cursor.  The cursor must be
46874 ** invalidated.
46875 */
46876 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
46877   BtCursor *p;
46878   sqlite3BtreeEnter(pBtree);
46879   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
46880     int i;
46881     sqlite3BtreeClearCursor(p);
46882     p->eState = CURSOR_FAULT;
46883     p->skipNext = errCode;
46884     for(i=0; i<=p->iPage; i++){
46885       releasePage(p->apPage[i]);
46886       p->apPage[i] = 0;
46887     }
46888   }
46889   sqlite3BtreeLeave(pBtree);
46890 }
46891
46892 /*
46893 ** Rollback the transaction in progress.  All cursors will be
46894 ** invalided by this operation.  Any attempt to use a cursor
46895 ** that was open at the beginning of this operation will result
46896 ** in an error.
46897 **
46898 ** This will release the write lock on the database file.  If there
46899 ** are no active cursors, it also releases the read lock.
46900 */
46901 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
46902   int rc;
46903   BtShared *pBt = p->pBt;
46904   MemPage *pPage1;
46905
46906   sqlite3BtreeEnter(p);
46907   rc = saveAllCursors(pBt, 0, 0);
46908 #ifndef SQLITE_OMIT_SHARED_CACHE
46909   if( rc!=SQLITE_OK ){
46910     /* This is a horrible situation. An IO or malloc() error occurred whilst
46911     ** trying to save cursor positions. If this is an automatic rollback (as
46912     ** the result of a constraint, malloc() failure or IO error) then 
46913     ** the cache may be internally inconsistent (not contain valid trees) so
46914     ** we cannot simply return the error to the caller. Instead, abort 
46915     ** all queries that may be using any of the cursors that failed to save.
46916     */
46917     sqlite3BtreeTripAllCursors(p, rc);
46918   }
46919 #endif
46920   btreeIntegrity(p);
46921
46922   if( p->inTrans==TRANS_WRITE ){
46923     int rc2;
46924
46925     assert( TRANS_WRITE==pBt->inTransaction );
46926     rc2 = sqlite3PagerRollback(pBt->pPager);
46927     if( rc2!=SQLITE_OK ){
46928       rc = rc2;
46929     }
46930
46931     /* The rollback may have destroyed the pPage1->aData value.  So
46932     ** call btreeGetPage() on page 1 again to make
46933     ** sure pPage1->aData is set correctly. */
46934     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
46935       int nPage = get4byte(28+(u8*)pPage1->aData);
46936       testcase( nPage==0 );
46937       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
46938       testcase( pBt->nPage!=nPage );
46939       pBt->nPage = nPage;
46940       releasePage(pPage1);
46941     }
46942     assert( countWriteCursors(pBt)==0 );
46943     pBt->inTransaction = TRANS_READ;
46944   }
46945
46946   btreeEndTransaction(p);
46947   sqlite3BtreeLeave(p);
46948   return rc;
46949 }
46950
46951 /*
46952 ** Start a statement subtransaction. The subtransaction can can be rolled
46953 ** back independently of the main transaction. You must start a transaction 
46954 ** before starting a subtransaction. The subtransaction is ended automatically 
46955 ** if the main transaction commits or rolls back.
46956 **
46957 ** Statement subtransactions are used around individual SQL statements
46958 ** that are contained within a BEGIN...COMMIT block.  If a constraint
46959 ** error occurs within the statement, the effect of that one statement
46960 ** can be rolled back without having to rollback the entire transaction.
46961 **
46962 ** A statement sub-transaction is implemented as an anonymous savepoint. The
46963 ** value passed as the second parameter is the total number of savepoints,
46964 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
46965 ** are no active savepoints and no other statement-transactions open,
46966 ** iStatement is 1. This anonymous savepoint can be released or rolled back
46967 ** using the sqlite3BtreeSavepoint() function.
46968 */
46969 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
46970   int rc;
46971   BtShared *pBt = p->pBt;
46972   sqlite3BtreeEnter(p);
46973   assert( p->inTrans==TRANS_WRITE );
46974   assert( pBt->readOnly==0 );
46975   assert( iStatement>0 );
46976   assert( iStatement>p->db->nSavepoint );
46977   assert( pBt->inTransaction==TRANS_WRITE );
46978   /* At the pager level, a statement transaction is a savepoint with
46979   ** an index greater than all savepoints created explicitly using
46980   ** SQL statements. It is illegal to open, release or rollback any
46981   ** such savepoints while the statement transaction savepoint is active.
46982   */
46983   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
46984   sqlite3BtreeLeave(p);
46985   return rc;
46986 }
46987
46988 /*
46989 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
46990 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
46991 ** savepoint identified by parameter iSavepoint, depending on the value 
46992 ** of op.
46993 **
46994 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
46995 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
46996 ** contents of the entire transaction are rolled back. This is different
46997 ** from a normal transaction rollback, as no locks are released and the
46998 ** transaction remains open.
46999 */
47000 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
47001   int rc = SQLITE_OK;
47002   if( p && p->inTrans==TRANS_WRITE ){
47003     BtShared *pBt = p->pBt;
47004     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
47005     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
47006     sqlite3BtreeEnter(p);
47007     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
47008     if( rc==SQLITE_OK ){
47009       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
47010       rc = newDatabase(pBt);
47011       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
47012       if( pBt->nPage==0 ){
47013         sqlite3PagerPagecount(pBt->pPager, (int*)&pBt->nPage);
47014       }
47015     }
47016     sqlite3BtreeLeave(p);
47017   }
47018   return rc;
47019 }
47020
47021 /*
47022 ** Create a new cursor for the BTree whose root is on the page
47023 ** iTable. If a read-only cursor is requested, it is assumed that
47024 ** the caller already has at least a read-only transaction open
47025 ** on the database already. If a write-cursor is requested, then
47026 ** the caller is assumed to have an open write transaction.
47027 **
47028 ** If wrFlag==0, then the cursor can only be used for reading.
47029 ** If wrFlag==1, then the cursor can be used for reading or for
47030 ** writing if other conditions for writing are also met.  These
47031 ** are the conditions that must be met in order for writing to
47032 ** be allowed:
47033 **
47034 ** 1:  The cursor must have been opened with wrFlag==1
47035 **
47036 ** 2:  Other database connections that share the same pager cache
47037 **     but which are not in the READ_UNCOMMITTED state may not have
47038 **     cursors open with wrFlag==0 on the same table.  Otherwise
47039 **     the changes made by this write cursor would be visible to
47040 **     the read cursors in the other database connection.
47041 **
47042 ** 3:  The database must be writable (not on read-only media)
47043 **
47044 ** 4:  There must be an active transaction.
47045 **
47046 ** No checking is done to make sure that page iTable really is the
47047 ** root page of a b-tree.  If it is not, then the cursor acquired
47048 ** will not work correctly.
47049 **
47050 ** It is assumed that the sqlite3BtreeCursorZero() has been called
47051 ** on pCur to initialize the memory space prior to invoking this routine.
47052 */
47053 static int btreeCursor(
47054   Btree *p,                              /* The btree */
47055   int iTable,                            /* Root page of table to open */
47056   int wrFlag,                            /* 1 to write. 0 read-only */
47057   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
47058   BtCursor *pCur                         /* Space for new cursor */
47059 ){
47060   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
47061
47062   assert( sqlite3BtreeHoldsMutex(p) );
47063   assert( wrFlag==0 || wrFlag==1 );
47064
47065   /* The following assert statements verify that if this is a sharable 
47066   ** b-tree database, the connection is holding the required table locks, 
47067   ** and that no other connection has any open cursor that conflicts with 
47068   ** this lock.  */
47069   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
47070   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
47071
47072   /* Assert that the caller has opened the required transaction. */
47073   assert( p->inTrans>TRANS_NONE );
47074   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
47075   assert( pBt->pPage1 && pBt->pPage1->aData );
47076
47077   if( NEVER(wrFlag && pBt->readOnly) ){
47078     return SQLITE_READONLY;
47079   }
47080   if( iTable==1 && btreePagecount(pBt)==0 ){
47081     return SQLITE_EMPTY;
47082   }
47083
47084   /* Now that no other errors can occur, finish filling in the BtCursor
47085   ** variables and link the cursor into the BtShared list.  */
47086   pCur->pgnoRoot = (Pgno)iTable;
47087   pCur->iPage = -1;
47088   pCur->pKeyInfo = pKeyInfo;
47089   pCur->pBtree = p;
47090   pCur->pBt = pBt;
47091   pCur->wrFlag = (u8)wrFlag;
47092   pCur->pNext = pBt->pCursor;
47093   if( pCur->pNext ){
47094     pCur->pNext->pPrev = pCur;
47095   }
47096   pBt->pCursor = pCur;
47097   pCur->eState = CURSOR_INVALID;
47098   pCur->cachedRowid = 0;
47099   return SQLITE_OK;
47100 }
47101 SQLITE_PRIVATE int sqlite3BtreeCursor(
47102   Btree *p,                                   /* The btree */
47103   int iTable,                                 /* Root page of table to open */
47104   int wrFlag,                                 /* 1 to write. 0 read-only */
47105   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
47106   BtCursor *pCur                              /* Write new cursor here */
47107 ){
47108   int rc;
47109   sqlite3BtreeEnter(p);
47110   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
47111   sqlite3BtreeLeave(p);
47112   return rc;
47113 }
47114
47115 /*
47116 ** Return the size of a BtCursor object in bytes.
47117 **
47118 ** This interfaces is needed so that users of cursors can preallocate
47119 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
47120 ** to users so they cannot do the sizeof() themselves - they must call
47121 ** this routine.
47122 */
47123 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
47124   return ROUND8(sizeof(BtCursor));
47125 }
47126
47127 /*
47128 ** Initialize memory that will be converted into a BtCursor object.
47129 **
47130 ** The simple approach here would be to memset() the entire object
47131 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
47132 ** do not need to be zeroed and they are large, so we can save a lot
47133 ** of run-time by skipping the initialization of those elements.
47134 */
47135 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
47136   memset(p, 0, offsetof(BtCursor, iPage));
47137 }
47138
47139 /*
47140 ** Set the cached rowid value of every cursor in the same database file
47141 ** as pCur and having the same root page number as pCur.  The value is
47142 ** set to iRowid.
47143 **
47144 ** Only positive rowid values are considered valid for this cache.
47145 ** The cache is initialized to zero, indicating an invalid cache.
47146 ** A btree will work fine with zero or negative rowids.  We just cannot
47147 ** cache zero or negative rowids, which means tables that use zero or
47148 ** negative rowids might run a little slower.  But in practice, zero
47149 ** or negative rowids are very uncommon so this should not be a problem.
47150 */
47151 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
47152   BtCursor *p;
47153   for(p=pCur->pBt->pCursor; p; p=p->pNext){
47154     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
47155   }
47156   assert( pCur->cachedRowid==iRowid );
47157 }
47158
47159 /*
47160 ** Return the cached rowid for the given cursor.  A negative or zero
47161 ** return value indicates that the rowid cache is invalid and should be
47162 ** ignored.  If the rowid cache has never before been set, then a
47163 ** zero is returned.
47164 */
47165 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
47166   return pCur->cachedRowid;
47167 }
47168
47169 /*
47170 ** Close a cursor.  The read lock on the database file is released
47171 ** when the last cursor is closed.
47172 */
47173 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
47174   Btree *pBtree = pCur->pBtree;
47175   if( pBtree ){
47176     int i;
47177     BtShared *pBt = pCur->pBt;
47178     sqlite3BtreeEnter(pBtree);
47179     sqlite3BtreeClearCursor(pCur);
47180     if( pCur->pPrev ){
47181       pCur->pPrev->pNext = pCur->pNext;
47182     }else{
47183       pBt->pCursor = pCur->pNext;
47184     }
47185     if( pCur->pNext ){
47186       pCur->pNext->pPrev = pCur->pPrev;
47187     }
47188     for(i=0; i<=pCur->iPage; i++){
47189       releasePage(pCur->apPage[i]);
47190     }
47191     unlockBtreeIfUnused(pBt);
47192     invalidateOverflowCache(pCur);
47193     /* sqlite3_free(pCur); */
47194     sqlite3BtreeLeave(pBtree);
47195   }
47196   return SQLITE_OK;
47197 }
47198
47199 /*
47200 ** Make sure the BtCursor* given in the argument has a valid
47201 ** BtCursor.info structure.  If it is not already valid, call
47202 ** btreeParseCell() to fill it in.
47203 **
47204 ** BtCursor.info is a cache of the information in the current cell.
47205 ** Using this cache reduces the number of calls to btreeParseCell().
47206 **
47207 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
47208 ** compiler to crash when getCellInfo() is implemented as a macro.
47209 ** But there is a measureable speed advantage to using the macro on gcc
47210 ** (when less compiler optimizations like -Os or -O0 are used and the
47211 ** compiler is not doing agressive inlining.)  So we use a real function
47212 ** for MSVC and a macro for everything else.  Ticket #2457.
47213 */
47214 #ifndef NDEBUG
47215   static void assertCellInfo(BtCursor *pCur){
47216     CellInfo info;
47217     int iPage = pCur->iPage;
47218     memset(&info, 0, sizeof(info));
47219     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
47220     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
47221   }
47222 #else
47223   #define assertCellInfo(x)
47224 #endif
47225 #ifdef _MSC_VER
47226   /* Use a real function in MSVC to work around bugs in that compiler. */
47227   static void getCellInfo(BtCursor *pCur){
47228     if( pCur->info.nSize==0 ){
47229       int iPage = pCur->iPage;
47230       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
47231       pCur->validNKey = 1;
47232     }else{
47233       assertCellInfo(pCur);
47234     }
47235   }
47236 #else /* if not _MSC_VER */
47237   /* Use a macro in all other compilers so that the function is inlined */
47238 #define getCellInfo(pCur)                                                      \
47239   if( pCur->info.nSize==0 ){                                                   \
47240     int iPage = pCur->iPage;                                                   \
47241     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
47242     pCur->validNKey = 1;                                                       \
47243   }else{                                                                       \
47244     assertCellInfo(pCur);                                                      \
47245   }
47246 #endif /* _MSC_VER */
47247
47248 #ifndef NDEBUG  /* The next routine used only within assert() statements */
47249 /*
47250 ** Return true if the given BtCursor is valid.  A valid cursor is one
47251 ** that is currently pointing to a row in a (non-empty) table.
47252 ** This is a verification routine is used only within assert() statements.
47253 */
47254 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
47255   return pCur && pCur->eState==CURSOR_VALID;
47256 }
47257 #endif /* NDEBUG */
47258
47259 /*
47260 ** Set *pSize to the size of the buffer needed to hold the value of
47261 ** the key for the current entry.  If the cursor is not pointing
47262 ** to a valid entry, *pSize is set to 0. 
47263 **
47264 ** For a table with the INTKEY flag set, this routine returns the key
47265 ** itself, not the number of bytes in the key.
47266 **
47267 ** The caller must position the cursor prior to invoking this routine.
47268 ** 
47269 ** This routine cannot fail.  It always returns SQLITE_OK.  
47270 */
47271 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
47272   assert( cursorHoldsMutex(pCur) );
47273   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
47274   if( pCur->eState!=CURSOR_VALID ){
47275     *pSize = 0;
47276   }else{
47277     getCellInfo(pCur);
47278     *pSize = pCur->info.nKey;
47279   }
47280   return SQLITE_OK;
47281 }
47282
47283 /*
47284 ** Set *pSize to the number of bytes of data in the entry the
47285 ** cursor currently points to.
47286 **
47287 ** The caller must guarantee that the cursor is pointing to a non-NULL
47288 ** valid entry.  In other words, the calling procedure must guarantee
47289 ** that the cursor has Cursor.eState==CURSOR_VALID.
47290 **
47291 ** Failure is not possible.  This function always returns SQLITE_OK.
47292 ** It might just as well be a procedure (returning void) but we continue
47293 ** to return an integer result code for historical reasons.
47294 */
47295 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
47296   assert( cursorHoldsMutex(pCur) );
47297   assert( pCur->eState==CURSOR_VALID );
47298   getCellInfo(pCur);
47299   *pSize = pCur->info.nData;
47300   return SQLITE_OK;
47301 }
47302
47303 /*
47304 ** Given the page number of an overflow page in the database (parameter
47305 ** ovfl), this function finds the page number of the next page in the 
47306 ** linked list of overflow pages. If possible, it uses the auto-vacuum
47307 ** pointer-map data instead of reading the content of page ovfl to do so. 
47308 **
47309 ** If an error occurs an SQLite error code is returned. Otherwise:
47310 **
47311 ** The page number of the next overflow page in the linked list is 
47312 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
47313 ** list, *pPgnoNext is set to zero. 
47314 **
47315 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
47316 ** to page number pOvfl was obtained, then *ppPage is set to point to that
47317 ** reference. It is the responsibility of the caller to call releasePage()
47318 ** on *ppPage to free the reference. In no reference was obtained (because
47319 ** the pointer-map was used to obtain the value for *pPgnoNext), then
47320 ** *ppPage is set to zero.
47321 */
47322 static int getOverflowPage(
47323   BtShared *pBt,               /* The database file */
47324   Pgno ovfl,                   /* Current overflow page number */
47325   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
47326   Pgno *pPgnoNext              /* OUT: Next overflow page number */
47327 ){
47328   Pgno next = 0;
47329   MemPage *pPage = 0;
47330   int rc = SQLITE_OK;
47331
47332   assert( sqlite3_mutex_held(pBt->mutex) );
47333   assert(pPgnoNext);
47334
47335 #ifndef SQLITE_OMIT_AUTOVACUUM
47336   /* Try to find the next page in the overflow list using the
47337   ** autovacuum pointer-map pages. Guess that the next page in 
47338   ** the overflow list is page number (ovfl+1). If that guess turns 
47339   ** out to be wrong, fall back to loading the data of page 
47340   ** number ovfl to determine the next page number.
47341   */
47342   if( pBt->autoVacuum ){
47343     Pgno pgno;
47344     Pgno iGuess = ovfl+1;
47345     u8 eType;
47346
47347     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
47348       iGuess++;
47349     }
47350
47351     if( iGuess<=btreePagecount(pBt) ){
47352       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
47353       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
47354         next = iGuess;
47355         rc = SQLITE_DONE;
47356       }
47357     }
47358   }
47359 #endif
47360
47361   assert( next==0 || rc==SQLITE_DONE );
47362   if( rc==SQLITE_OK ){
47363     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
47364     assert( rc==SQLITE_OK || pPage==0 );
47365     if( rc==SQLITE_OK ){
47366       next = get4byte(pPage->aData);
47367     }
47368   }
47369
47370   *pPgnoNext = next;
47371   if( ppPage ){
47372     *ppPage = pPage;
47373   }else{
47374     releasePage(pPage);
47375   }
47376   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
47377 }
47378
47379 /*
47380 ** Copy data from a buffer to a page, or from a page to a buffer.
47381 **
47382 ** pPayload is a pointer to data stored on database page pDbPage.
47383 ** If argument eOp is false, then nByte bytes of data are copied
47384 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
47385 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
47386 ** of data are copied from the buffer pBuf to pPayload.
47387 **
47388 ** SQLITE_OK is returned on success, otherwise an error code.
47389 */
47390 static int copyPayload(
47391   void *pPayload,           /* Pointer to page data */
47392   void *pBuf,               /* Pointer to buffer */
47393   int nByte,                /* Number of bytes to copy */
47394   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
47395   DbPage *pDbPage           /* Page containing pPayload */
47396 ){
47397   if( eOp ){
47398     /* Copy data from buffer to page (a write operation) */
47399     int rc = sqlite3PagerWrite(pDbPage);
47400     if( rc!=SQLITE_OK ){
47401       return rc;
47402     }
47403     memcpy(pPayload, pBuf, nByte);
47404   }else{
47405     /* Copy data from page to buffer (a read operation) */
47406     memcpy(pBuf, pPayload, nByte);
47407   }
47408   return SQLITE_OK;
47409 }
47410
47411 /*
47412 ** This function is used to read or overwrite payload information
47413 ** for the entry that the pCur cursor is pointing to. If the eOp
47414 ** parameter is 0, this is a read operation (data copied into
47415 ** buffer pBuf). If it is non-zero, a write (data copied from
47416 ** buffer pBuf).
47417 **
47418 ** A total of "amt" bytes are read or written beginning at "offset".
47419 ** Data is read to or from the buffer pBuf.
47420 **
47421 ** The content being read or written might appear on the main page
47422 ** or be scattered out on multiple overflow pages.
47423 **
47424 ** If the BtCursor.isIncrblobHandle flag is set, and the current
47425 ** cursor entry uses one or more overflow pages, this function
47426 ** allocates space for and lazily popluates the overflow page-list 
47427 ** cache array (BtCursor.aOverflow). Subsequent calls use this
47428 ** cache to make seeking to the supplied offset more efficient.
47429 **
47430 ** Once an overflow page-list cache has been allocated, it may be
47431 ** invalidated if some other cursor writes to the same table, or if
47432 ** the cursor is moved to a different row. Additionally, in auto-vacuum
47433 ** mode, the following events may invalidate an overflow page-list cache.
47434 **
47435 **   * An incremental vacuum,
47436 **   * A commit in auto_vacuum="full" mode,
47437 **   * Creating a table (may require moving an overflow page).
47438 */
47439 static int accessPayload(
47440   BtCursor *pCur,      /* Cursor pointing to entry to read from */
47441   u32 offset,          /* Begin reading this far into payload */
47442   u32 amt,             /* Read this many bytes */
47443   unsigned char *pBuf, /* Write the bytes into this buffer */ 
47444   int eOp              /* zero to read. non-zero to write. */
47445 ){
47446   unsigned char *aPayload;
47447   int rc = SQLITE_OK;
47448   u32 nKey;
47449   int iIdx = 0;
47450   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
47451   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
47452
47453   assert( pPage );
47454   assert( pCur->eState==CURSOR_VALID );
47455   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47456   assert( cursorHoldsMutex(pCur) );
47457
47458   getCellInfo(pCur);
47459   aPayload = pCur->info.pCell + pCur->info.nHeader;
47460   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
47461
47462   if( NEVER(offset+amt > nKey+pCur->info.nData) 
47463    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
47464   ){
47465     /* Trying to read or write past the end of the data is an error */
47466     return SQLITE_CORRUPT_BKPT;
47467   }
47468
47469   /* Check if data must be read/written to/from the btree page itself. */
47470   if( offset<pCur->info.nLocal ){
47471     int a = amt;
47472     if( a+offset>pCur->info.nLocal ){
47473       a = pCur->info.nLocal - offset;
47474     }
47475     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
47476     offset = 0;
47477     pBuf += a;
47478     amt -= a;
47479   }else{
47480     offset -= pCur->info.nLocal;
47481   }
47482
47483   if( rc==SQLITE_OK && amt>0 ){
47484     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
47485     Pgno nextPage;
47486
47487     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
47488
47489 #ifndef SQLITE_OMIT_INCRBLOB
47490     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
47491     ** has not been allocated, allocate it now. The array is sized at
47492     ** one entry for each overflow page in the overflow chain. The
47493     ** page number of the first overflow page is stored in aOverflow[0],
47494     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
47495     ** (the cache is lazily populated).
47496     */
47497     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
47498       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
47499       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
47500       /* nOvfl is always positive.  If it were zero, fetchPayload would have
47501       ** been used instead of this routine. */
47502       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
47503         rc = SQLITE_NOMEM;
47504       }
47505     }
47506
47507     /* If the overflow page-list cache has been allocated and the
47508     ** entry for the first required overflow page is valid, skip
47509     ** directly to it.
47510     */
47511     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
47512       iIdx = (offset/ovflSize);
47513       nextPage = pCur->aOverflow[iIdx];
47514       offset = (offset%ovflSize);
47515     }
47516 #endif
47517
47518     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
47519
47520 #ifndef SQLITE_OMIT_INCRBLOB
47521       /* If required, populate the overflow page-list cache. */
47522       if( pCur->aOverflow ){
47523         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
47524         pCur->aOverflow[iIdx] = nextPage;
47525       }
47526 #endif
47527
47528       if( offset>=ovflSize ){
47529         /* The only reason to read this page is to obtain the page
47530         ** number for the next page in the overflow chain. The page
47531         ** data is not required. So first try to lookup the overflow
47532         ** page-list cache, if any, then fall back to the getOverflowPage()
47533         ** function.
47534         */
47535 #ifndef SQLITE_OMIT_INCRBLOB
47536         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
47537           nextPage = pCur->aOverflow[iIdx+1];
47538         } else 
47539 #endif
47540           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
47541         offset -= ovflSize;
47542       }else{
47543         /* Need to read this page properly. It contains some of the
47544         ** range of data that is being read (eOp==0) or written (eOp!=0).
47545         */
47546         DbPage *pDbPage;
47547         int a = amt;
47548         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
47549         if( rc==SQLITE_OK ){
47550           aPayload = sqlite3PagerGetData(pDbPage);
47551           nextPage = get4byte(aPayload);
47552           if( a + offset > ovflSize ){
47553             a = ovflSize - offset;
47554           }
47555           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
47556           sqlite3PagerUnref(pDbPage);
47557           offset = 0;
47558           amt -= a;
47559           pBuf += a;
47560         }
47561       }
47562     }
47563   }
47564
47565   if( rc==SQLITE_OK && amt>0 ){
47566     return SQLITE_CORRUPT_BKPT;
47567   }
47568   return rc;
47569 }
47570
47571 /*
47572 ** Read part of the key associated with cursor pCur.  Exactly
47573 ** "amt" bytes will be transfered into pBuf[].  The transfer
47574 ** begins at "offset".
47575 **
47576 ** The caller must ensure that pCur is pointing to a valid row
47577 ** in the table.
47578 **
47579 ** Return SQLITE_OK on success or an error code if anything goes
47580 ** wrong.  An error is returned if "offset+amt" is larger than
47581 ** the available payload.
47582 */
47583 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47584   assert( cursorHoldsMutex(pCur) );
47585   assert( pCur->eState==CURSOR_VALID );
47586   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47587   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47588   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
47589 }
47590
47591 /*
47592 ** Read part of the data associated with cursor pCur.  Exactly
47593 ** "amt" bytes will be transfered into pBuf[].  The transfer
47594 ** begins at "offset".
47595 **
47596 ** Return SQLITE_OK on success or an error code if anything goes
47597 ** wrong.  An error is returned if "offset+amt" is larger than
47598 ** the available payload.
47599 */
47600 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47601   int rc;
47602
47603 #ifndef SQLITE_OMIT_INCRBLOB
47604   if ( pCur->eState==CURSOR_INVALID ){
47605     return SQLITE_ABORT;
47606   }
47607 #endif
47608
47609   assert( cursorHoldsMutex(pCur) );
47610   rc = restoreCursorPosition(pCur);
47611   if( rc==SQLITE_OK ){
47612     assert( pCur->eState==CURSOR_VALID );
47613     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47614     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47615     rc = accessPayload(pCur, offset, amt, pBuf, 0);
47616   }
47617   return rc;
47618 }
47619
47620 /*
47621 ** Return a pointer to payload information from the entry that the 
47622 ** pCur cursor is pointing to.  The pointer is to the beginning of
47623 ** the key if skipKey==0 and it points to the beginning of data if
47624 ** skipKey==1.  The number of bytes of available key/data is written
47625 ** into *pAmt.  If *pAmt==0, then the value returned will not be
47626 ** a valid pointer.
47627 **
47628 ** This routine is an optimization.  It is common for the entire key
47629 ** and data to fit on the local page and for there to be no overflow
47630 ** pages.  When that is so, this routine can be used to access the
47631 ** key and data without making a copy.  If the key and/or data spills
47632 ** onto overflow pages, then accessPayload() must be used to reassemble
47633 ** the key/data and copy it into a preallocated buffer.
47634 **
47635 ** The pointer returned by this routine looks directly into the cached
47636 ** page of the database.  The data might change or move the next time
47637 ** any btree routine is called.
47638 */
47639 static const unsigned char *fetchPayload(
47640   BtCursor *pCur,      /* Cursor pointing to entry to read from */
47641   int *pAmt,           /* Write the number of available bytes here */
47642   int skipKey          /* read beginning at data if this is true */
47643 ){
47644   unsigned char *aPayload;
47645   MemPage *pPage;
47646   u32 nKey;
47647   u32 nLocal;
47648
47649   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
47650   assert( pCur->eState==CURSOR_VALID );
47651   assert( cursorHoldsMutex(pCur) );
47652   pPage = pCur->apPage[pCur->iPage];
47653   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47654   if( NEVER(pCur->info.nSize==0) ){
47655     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
47656                    &pCur->info);
47657   }
47658   aPayload = pCur->info.pCell;
47659   aPayload += pCur->info.nHeader;
47660   if( pPage->intKey ){
47661     nKey = 0;
47662   }else{
47663     nKey = (int)pCur->info.nKey;
47664   }
47665   if( skipKey ){
47666     aPayload += nKey;
47667     nLocal = pCur->info.nLocal - nKey;
47668   }else{
47669     nLocal = pCur->info.nLocal;
47670     assert( nLocal<=nKey );
47671   }
47672   *pAmt = nLocal;
47673   return aPayload;
47674 }
47675
47676
47677 /*
47678 ** For the entry that cursor pCur is point to, return as
47679 ** many bytes of the key or data as are available on the local
47680 ** b-tree page.  Write the number of available bytes into *pAmt.
47681 **
47682 ** The pointer returned is ephemeral.  The key/data may move
47683 ** or be destroyed on the next call to any Btree routine,
47684 ** including calls from other threads against the same cache.
47685 ** Hence, a mutex on the BtShared should be held prior to calling
47686 ** this routine.
47687 **
47688 ** These routines is used to get quick access to key and data
47689 ** in the common case where no overflow pages are used.
47690 */
47691 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
47692   const void *p = 0;
47693   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47694   assert( cursorHoldsMutex(pCur) );
47695   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47696     p = (const void*)fetchPayload(pCur, pAmt, 0);
47697   }
47698   return p;
47699 }
47700 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
47701   const void *p = 0;
47702   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47703   assert( cursorHoldsMutex(pCur) );
47704   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47705     p = (const void*)fetchPayload(pCur, pAmt, 1);
47706   }
47707   return p;
47708 }
47709
47710
47711 /*
47712 ** Move the cursor down to a new child page.  The newPgno argument is the
47713 ** page number of the child page to move to.
47714 **
47715 ** This function returns SQLITE_CORRUPT if the page-header flags field of
47716 ** the new child page does not match the flags field of the parent (i.e.
47717 ** if an intkey page appears to be the parent of a non-intkey page, or
47718 ** vice-versa).
47719 */
47720 static int moveToChild(BtCursor *pCur, u32 newPgno){
47721   int rc;
47722   int i = pCur->iPage;
47723   MemPage *pNewPage;
47724   BtShared *pBt = pCur->pBt;
47725
47726   assert( cursorHoldsMutex(pCur) );
47727   assert( pCur->eState==CURSOR_VALID );
47728   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
47729   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
47730     return SQLITE_CORRUPT_BKPT;
47731   }
47732   rc = getAndInitPage(pBt, newPgno, &pNewPage);
47733   if( rc ) return rc;
47734   pCur->apPage[i+1] = pNewPage;
47735   pCur->aiIdx[i+1] = 0;
47736   pCur->iPage++;
47737
47738   pCur->info.nSize = 0;
47739   pCur->validNKey = 0;
47740   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
47741     return SQLITE_CORRUPT_BKPT;
47742   }
47743   return SQLITE_OK;
47744 }
47745
47746 #ifndef NDEBUG
47747 /*
47748 ** Page pParent is an internal (non-leaf) tree page. This function 
47749 ** asserts that page number iChild is the left-child if the iIdx'th
47750 ** cell in page pParent. Or, if iIdx is equal to the total number of
47751 ** cells in pParent, that page number iChild is the right-child of
47752 ** the page.
47753 */
47754 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
47755   assert( iIdx<=pParent->nCell );
47756   if( iIdx==pParent->nCell ){
47757     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
47758   }else{
47759     assert( get4byte(findCell(pParent, iIdx))==iChild );
47760   }
47761 }
47762 #else
47763 #  define assertParentIndex(x,y,z) 
47764 #endif
47765
47766 /*
47767 ** Move the cursor up to the parent page.
47768 **
47769 ** pCur->idx is set to the cell index that contains the pointer
47770 ** to the page we are coming from.  If we are coming from the
47771 ** right-most child page then pCur->idx is set to one more than
47772 ** the largest cell index.
47773 */
47774 static void moveToParent(BtCursor *pCur){
47775   assert( cursorHoldsMutex(pCur) );
47776   assert( pCur->eState==CURSOR_VALID );
47777   assert( pCur->iPage>0 );
47778   assert( pCur->apPage[pCur->iPage] );
47779   assertParentIndex(
47780     pCur->apPage[pCur->iPage-1], 
47781     pCur->aiIdx[pCur->iPage-1], 
47782     pCur->apPage[pCur->iPage]->pgno
47783   );
47784   releasePage(pCur->apPage[pCur->iPage]);
47785   pCur->iPage--;
47786   pCur->info.nSize = 0;
47787   pCur->validNKey = 0;
47788 }
47789
47790 /*
47791 ** Move the cursor to point to the root page of its b-tree structure.
47792 **
47793 ** If the table has a virtual root page, then the cursor is moved to point
47794 ** to the virtual root page instead of the actual root page. A table has a
47795 ** virtual root page when the actual root page contains no cells and a 
47796 ** single child page. This can only happen with the table rooted at page 1.
47797 **
47798 ** If the b-tree structure is empty, the cursor state is set to 
47799 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
47800 ** cell located on the root (or virtual root) page and the cursor state
47801 ** is set to CURSOR_VALID.
47802 **
47803 ** If this function returns successfully, it may be assumed that the
47804 ** page-header flags indicate that the [virtual] root-page is the expected 
47805 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
47806 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
47807 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
47808 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
47809 ** b-tree).
47810 */
47811 static int moveToRoot(BtCursor *pCur){
47812   MemPage *pRoot;
47813   int rc = SQLITE_OK;
47814   Btree *p = pCur->pBtree;
47815   BtShared *pBt = p->pBt;
47816
47817   assert( cursorHoldsMutex(pCur) );
47818   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
47819   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
47820   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
47821   if( pCur->eState>=CURSOR_REQUIRESEEK ){
47822     if( pCur->eState==CURSOR_FAULT ){
47823       assert( pCur->skipNext!=SQLITE_OK );
47824       return pCur->skipNext;
47825     }
47826     sqlite3BtreeClearCursor(pCur);
47827   }
47828
47829   if( pCur->iPage>=0 ){
47830     int i;
47831     for(i=1; i<=pCur->iPage; i++){
47832       releasePage(pCur->apPage[i]);
47833     }
47834     pCur->iPage = 0;
47835   }else{
47836     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
47837     if( rc!=SQLITE_OK ){
47838       pCur->eState = CURSOR_INVALID;
47839       return rc;
47840     }
47841     pCur->iPage = 0;
47842
47843     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
47844     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
47845     ** NULL, the caller expects a table b-tree. If this is not the case,
47846     ** return an SQLITE_CORRUPT error.  */
47847     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
47848     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
47849       return SQLITE_CORRUPT_BKPT;
47850     }
47851   }
47852
47853   /* Assert that the root page is of the correct type. This must be the
47854   ** case as the call to this function that loaded the root-page (either
47855   ** this call or a previous invocation) would have detected corruption 
47856   ** if the assumption were not true, and it is not possible for the flags 
47857   ** byte to have been modified while this cursor is holding a reference
47858   ** to the page.  */
47859   pRoot = pCur->apPage[0];
47860   assert( pRoot->pgno==pCur->pgnoRoot );
47861   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
47862
47863   pCur->aiIdx[0] = 0;
47864   pCur->info.nSize = 0;
47865   pCur->atLast = 0;
47866   pCur->validNKey = 0;
47867
47868   if( pRoot->nCell==0 && !pRoot->leaf ){
47869     Pgno subpage;
47870     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
47871     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
47872     pCur->eState = CURSOR_VALID;
47873     rc = moveToChild(pCur, subpage);
47874   }else{
47875     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
47876   }
47877   return rc;
47878 }
47879
47880 /*
47881 ** Move the cursor down to the left-most leaf entry beneath the
47882 ** entry to which it is currently pointing.
47883 **
47884 ** The left-most leaf is the one with the smallest key - the first
47885 ** in ascending order.
47886 */
47887 static int moveToLeftmost(BtCursor *pCur){
47888   Pgno pgno;
47889   int rc = SQLITE_OK;
47890   MemPage *pPage;
47891
47892   assert( cursorHoldsMutex(pCur) );
47893   assert( pCur->eState==CURSOR_VALID );
47894   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47895     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47896     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
47897     rc = moveToChild(pCur, pgno);
47898   }
47899   return rc;
47900 }
47901
47902 /*
47903 ** Move the cursor down to the right-most leaf entry beneath the
47904 ** page to which it is currently pointing.  Notice the difference
47905 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
47906 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
47907 ** finds the right-most entry beneath the *page*.
47908 **
47909 ** The right-most entry is the one with the largest key - the last
47910 ** key in ascending order.
47911 */
47912 static int moveToRightmost(BtCursor *pCur){
47913   Pgno pgno;
47914   int rc = SQLITE_OK;
47915   MemPage *pPage = 0;
47916
47917   assert( cursorHoldsMutex(pCur) );
47918   assert( pCur->eState==CURSOR_VALID );
47919   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47920     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47921     pCur->aiIdx[pCur->iPage] = pPage->nCell;
47922     rc = moveToChild(pCur, pgno);
47923   }
47924   if( rc==SQLITE_OK ){
47925     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
47926     pCur->info.nSize = 0;
47927     pCur->validNKey = 0;
47928   }
47929   return rc;
47930 }
47931
47932 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
47933 ** on success.  Set *pRes to 0 if the cursor actually points to something
47934 ** or set *pRes to 1 if the table is empty.
47935 */
47936 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
47937   int rc;
47938
47939   assert( cursorHoldsMutex(pCur) );
47940   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47941   rc = moveToRoot(pCur);
47942   if( rc==SQLITE_OK ){
47943     if( pCur->eState==CURSOR_INVALID ){
47944       assert( pCur->apPage[pCur->iPage]->nCell==0 );
47945       *pRes = 1;
47946     }else{
47947       assert( pCur->apPage[pCur->iPage]->nCell>0 );
47948       *pRes = 0;
47949       rc = moveToLeftmost(pCur);
47950     }
47951   }
47952   return rc;
47953 }
47954
47955 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
47956 ** on success.  Set *pRes to 0 if the cursor actually points to something
47957 ** or set *pRes to 1 if the table is empty.
47958 */
47959 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
47960   int rc;
47961  
47962   assert( cursorHoldsMutex(pCur) );
47963   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47964
47965   /* If the cursor already points to the last entry, this is a no-op. */
47966   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
47967 #ifdef SQLITE_DEBUG
47968     /* This block serves to assert() that the cursor really does point 
47969     ** to the last entry in the b-tree. */
47970     int ii;
47971     for(ii=0; ii<pCur->iPage; ii++){
47972       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
47973     }
47974     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
47975     assert( pCur->apPage[pCur->iPage]->leaf );
47976 #endif
47977     return SQLITE_OK;
47978   }
47979
47980   rc = moveToRoot(pCur);
47981   if( rc==SQLITE_OK ){
47982     if( CURSOR_INVALID==pCur->eState ){
47983       assert( pCur->apPage[pCur->iPage]->nCell==0 );
47984       *pRes = 1;
47985     }else{
47986       assert( pCur->eState==CURSOR_VALID );
47987       *pRes = 0;
47988       rc = moveToRightmost(pCur);
47989       pCur->atLast = rc==SQLITE_OK ?1:0;
47990     }
47991   }
47992   return rc;
47993 }
47994
47995 /* Move the cursor so that it points to an entry near the key 
47996 ** specified by pIdxKey or intKey.   Return a success code.
47997 **
47998 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
47999 ** must be NULL.  For index tables, pIdxKey is used and intKey
48000 ** is ignored.
48001 **
48002 ** If an exact match is not found, then the cursor is always
48003 ** left pointing at a leaf page which would hold the entry if it
48004 ** were present.  The cursor might point to an entry that comes
48005 ** before or after the key.
48006 **
48007 ** An integer is written into *pRes which is the result of
48008 ** comparing the key with the entry to which the cursor is 
48009 ** pointing.  The meaning of the integer written into
48010 ** *pRes is as follows:
48011 **
48012 **     *pRes<0      The cursor is left pointing at an entry that
48013 **                  is smaller than intKey/pIdxKey or if the table is empty
48014 **                  and the cursor is therefore left point to nothing.
48015 **
48016 **     *pRes==0     The cursor is left pointing at an entry that
48017 **                  exactly matches intKey/pIdxKey.
48018 **
48019 **     *pRes>0      The cursor is left pointing at an entry that
48020 **                  is larger than intKey/pIdxKey.
48021 **
48022 */
48023 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
48024   BtCursor *pCur,          /* The cursor to be moved */
48025   UnpackedRecord *pIdxKey, /* Unpacked index key */
48026   i64 intKey,              /* The table key */
48027   int biasRight,           /* If true, bias the search to the high end */
48028   int *pRes                /* Write search results here */
48029 ){
48030   int rc;
48031
48032   assert( cursorHoldsMutex(pCur) );
48033   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48034   assert( pRes );
48035   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
48036
48037   /* If the cursor is already positioned at the point we are trying
48038   ** to move to, then just return without doing any work */
48039   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
48040    && pCur->apPage[0]->intKey 
48041   ){
48042     if( pCur->info.nKey==intKey ){
48043       *pRes = 0;
48044       return SQLITE_OK;
48045     }
48046     if( pCur->atLast && pCur->info.nKey<intKey ){
48047       *pRes = -1;
48048       return SQLITE_OK;
48049     }
48050   }
48051
48052   rc = moveToRoot(pCur);
48053   if( rc ){
48054     return rc;
48055   }
48056   assert( pCur->apPage[pCur->iPage] );
48057   assert( pCur->apPage[pCur->iPage]->isInit );
48058   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
48059   if( pCur->eState==CURSOR_INVALID ){
48060     *pRes = -1;
48061     assert( pCur->apPage[pCur->iPage]->nCell==0 );
48062     return SQLITE_OK;
48063   }
48064   assert( pCur->apPage[0]->intKey || pIdxKey );
48065   for(;;){
48066     int lwr, upr;
48067     Pgno chldPg;
48068     MemPage *pPage = pCur->apPage[pCur->iPage];
48069     int c;
48070
48071     /* pPage->nCell must be greater than zero. If this is the root-page
48072     ** the cursor would have been INVALID above and this for(;;) loop
48073     ** not run. If this is not the root-page, then the moveToChild() routine
48074     ** would have already detected db corruption. Similarly, pPage must
48075     ** be the right kind (index or table) of b-tree page. Otherwise
48076     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
48077     assert( pPage->nCell>0 );
48078     assert( pPage->intKey==(pIdxKey==0) );
48079     lwr = 0;
48080     upr = pPage->nCell-1;
48081     if( biasRight ){
48082       pCur->aiIdx[pCur->iPage] = (u16)upr;
48083     }else{
48084       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
48085     }
48086     for(;;){
48087       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
48088       u8 *pCell;                          /* Pointer to current cell in pPage */
48089
48090       pCur->info.nSize = 0;
48091       pCell = findCell(pPage, idx) + pPage->childPtrSize;
48092       if( pPage->intKey ){
48093         i64 nCellKey;
48094         if( pPage->hasData ){
48095           u32 dummy;
48096           pCell += getVarint32(pCell, dummy);
48097         }
48098         getVarint(pCell, (u64*)&nCellKey);
48099         if( nCellKey==intKey ){
48100           c = 0;
48101         }else if( nCellKey<intKey ){
48102           c = -1;
48103         }else{
48104           assert( nCellKey>intKey );
48105           c = +1;
48106         }
48107         pCur->validNKey = 1;
48108         pCur->info.nKey = nCellKey;
48109       }else{
48110         /* The maximum supported page-size is 32768 bytes. This means that
48111         ** the maximum number of record bytes stored on an index B-Tree
48112         ** page is at most 8198 bytes, which may be stored as a 2-byte
48113         ** varint. This information is used to attempt to avoid parsing 
48114         ** the entire cell by checking for the cases where the record is 
48115         ** stored entirely within the b-tree page by inspecting the first 
48116         ** 2 bytes of the cell.
48117         */
48118         int nCell = pCell[0];
48119         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
48120           /* This branch runs if the record-size field of the cell is a
48121           ** single byte varint and the record fits entirely on the main
48122           ** b-tree page.  */
48123           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
48124         }else if( !(pCell[1] & 0x80) 
48125           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
48126         ){
48127           /* The record-size field is a 2 byte varint and the record 
48128           ** fits entirely on the main b-tree page.  */
48129           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
48130         }else{
48131           /* The record flows over onto one or more overflow pages. In
48132           ** this case the whole cell needs to be parsed, a buffer allocated
48133           ** and accessPayload() used to retrieve the record into the
48134           ** buffer before VdbeRecordCompare() can be called. */
48135           void *pCellKey;
48136           u8 * const pCellBody = pCell - pPage->childPtrSize;
48137           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
48138           nCell = (int)pCur->info.nKey;
48139           pCellKey = sqlite3Malloc( nCell );
48140           if( pCellKey==0 ){
48141             rc = SQLITE_NOMEM;
48142             goto moveto_finish;
48143           }
48144           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
48145           if( rc ){
48146             sqlite3_free(pCellKey);
48147             goto moveto_finish;
48148           }
48149           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
48150           sqlite3_free(pCellKey);
48151         }
48152       }
48153       if( c==0 ){
48154         if( pPage->intKey && !pPage->leaf ){
48155           lwr = idx;
48156           upr = lwr - 1;
48157           break;
48158         }else{
48159           *pRes = 0;
48160           rc = SQLITE_OK;
48161           goto moveto_finish;
48162         }
48163       }
48164       if( c<0 ){
48165         lwr = idx+1;
48166       }else{
48167         upr = idx-1;
48168       }
48169       if( lwr>upr ){
48170         break;
48171       }
48172       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
48173     }
48174     assert( lwr==upr+1 );
48175     assert( pPage->isInit );
48176     if( pPage->leaf ){
48177       chldPg = 0;
48178     }else if( lwr>=pPage->nCell ){
48179       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
48180     }else{
48181       chldPg = get4byte(findCell(pPage, lwr));
48182     }
48183     if( chldPg==0 ){
48184       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48185       *pRes = c;
48186       rc = SQLITE_OK;
48187       goto moveto_finish;
48188     }
48189     pCur->aiIdx[pCur->iPage] = (u16)lwr;
48190     pCur->info.nSize = 0;
48191     pCur->validNKey = 0;
48192     rc = moveToChild(pCur, chldPg);
48193     if( rc ) goto moveto_finish;
48194   }
48195 moveto_finish:
48196   return rc;
48197 }
48198
48199
48200 /*
48201 ** Return TRUE if the cursor is not pointing at an entry of the table.
48202 **
48203 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
48204 ** past the last entry in the table or sqlite3BtreePrev() moves past
48205 ** the first entry.  TRUE is also returned if the table is empty.
48206 */
48207 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
48208   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
48209   ** have been deleted? This API will need to change to return an error code
48210   ** as well as the boolean result value.
48211   */
48212   return (CURSOR_VALID!=pCur->eState);
48213 }
48214
48215 /*
48216 ** Advance the cursor to the next entry in the database.  If
48217 ** successful then set *pRes=0.  If the cursor
48218 ** was already pointing to the last entry in the database before
48219 ** this routine was called, then set *pRes=1.
48220 */
48221 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
48222   int rc;
48223   int idx;
48224   MemPage *pPage;
48225
48226   assert( cursorHoldsMutex(pCur) );
48227   rc = restoreCursorPosition(pCur);
48228   if( rc!=SQLITE_OK ){
48229     return rc;
48230   }
48231   assert( pRes!=0 );
48232   if( CURSOR_INVALID==pCur->eState ){
48233     *pRes = 1;
48234     return SQLITE_OK;
48235   }
48236   if( pCur->skipNext>0 ){
48237     pCur->skipNext = 0;
48238     *pRes = 0;
48239     return SQLITE_OK;
48240   }
48241   pCur->skipNext = 0;
48242
48243   pPage = pCur->apPage[pCur->iPage];
48244   idx = ++pCur->aiIdx[pCur->iPage];
48245   assert( pPage->isInit );
48246   assert( idx<=pPage->nCell );
48247
48248   pCur->info.nSize = 0;
48249   pCur->validNKey = 0;
48250   if( idx>=pPage->nCell ){
48251     if( !pPage->leaf ){
48252       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
48253       if( rc ) return rc;
48254       rc = moveToLeftmost(pCur);
48255       *pRes = 0;
48256       return rc;
48257     }
48258     do{
48259       if( pCur->iPage==0 ){
48260         *pRes = 1;
48261         pCur->eState = CURSOR_INVALID;
48262         return SQLITE_OK;
48263       }
48264       moveToParent(pCur);
48265       pPage = pCur->apPage[pCur->iPage];
48266     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
48267     *pRes = 0;
48268     if( pPage->intKey ){
48269       rc = sqlite3BtreeNext(pCur, pRes);
48270     }else{
48271       rc = SQLITE_OK;
48272     }
48273     return rc;
48274   }
48275   *pRes = 0;
48276   if( pPage->leaf ){
48277     return SQLITE_OK;
48278   }
48279   rc = moveToLeftmost(pCur);
48280   return rc;
48281 }
48282
48283
48284 /*
48285 ** Step the cursor to the back to the previous entry in the database.  If
48286 ** successful then set *pRes=0.  If the cursor
48287 ** was already pointing to the first entry in the database before
48288 ** this routine was called, then set *pRes=1.
48289 */
48290 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
48291   int rc;
48292   MemPage *pPage;
48293
48294   assert( cursorHoldsMutex(pCur) );
48295   rc = restoreCursorPosition(pCur);
48296   if( rc!=SQLITE_OK ){
48297     return rc;
48298   }
48299   pCur->atLast = 0;
48300   if( CURSOR_INVALID==pCur->eState ){
48301     *pRes = 1;
48302     return SQLITE_OK;
48303   }
48304   if( pCur->skipNext<0 ){
48305     pCur->skipNext = 0;
48306     *pRes = 0;
48307     return SQLITE_OK;
48308   }
48309   pCur->skipNext = 0;
48310
48311   pPage = pCur->apPage[pCur->iPage];
48312   assert( pPage->isInit );
48313   if( !pPage->leaf ){
48314     int idx = pCur->aiIdx[pCur->iPage];
48315     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
48316     if( rc ){
48317       return rc;
48318     }
48319     rc = moveToRightmost(pCur);
48320   }else{
48321     while( pCur->aiIdx[pCur->iPage]==0 ){
48322       if( pCur->iPage==0 ){
48323         pCur->eState = CURSOR_INVALID;
48324         *pRes = 1;
48325         return SQLITE_OK;
48326       }
48327       moveToParent(pCur);
48328     }
48329     pCur->info.nSize = 0;
48330     pCur->validNKey = 0;
48331
48332     pCur->aiIdx[pCur->iPage]--;
48333     pPage = pCur->apPage[pCur->iPage];
48334     if( pPage->intKey && !pPage->leaf ){
48335       rc = sqlite3BtreePrevious(pCur, pRes);
48336     }else{
48337       rc = SQLITE_OK;
48338     }
48339   }
48340   *pRes = 0;
48341   return rc;
48342 }
48343
48344 /*
48345 ** Allocate a new page from the database file.
48346 **
48347 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
48348 ** has already been called on the new page.)  The new page has also
48349 ** been referenced and the calling routine is responsible for calling
48350 ** sqlite3PagerUnref() on the new page when it is done.
48351 **
48352 ** SQLITE_OK is returned on success.  Any other return value indicates
48353 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
48354 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
48355 **
48356 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
48357 ** locate a page close to the page number "nearby".  This can be used in an
48358 ** attempt to keep related pages close to each other in the database file,
48359 ** which in turn can make database access faster.
48360 **
48361 ** If the "exact" parameter is not 0, and the page-number nearby exists 
48362 ** anywhere on the free-list, then it is guarenteed to be returned. This
48363 ** is only used by auto-vacuum databases when allocating a new table.
48364 */
48365 static int allocateBtreePage(
48366   BtShared *pBt, 
48367   MemPage **ppPage, 
48368   Pgno *pPgno, 
48369   Pgno nearby,
48370   u8 exact
48371 ){
48372   MemPage *pPage1;
48373   int rc;
48374   u32 n;     /* Number of pages on the freelist */
48375   u32 k;     /* Number of leaves on the trunk of the freelist */
48376   MemPage *pTrunk = 0;
48377   MemPage *pPrevTrunk = 0;
48378   Pgno mxPage;     /* Total size of the database file */
48379
48380   assert( sqlite3_mutex_held(pBt->mutex) );
48381   pPage1 = pBt->pPage1;
48382   mxPage = btreePagecount(pBt);
48383   n = get4byte(&pPage1->aData[36]);
48384   testcase( n==mxPage-1 );
48385   if( n>=mxPage ){
48386     return SQLITE_CORRUPT_BKPT;
48387   }
48388   if( n>0 ){
48389     /* There are pages on the freelist.  Reuse one of those pages. */
48390     Pgno iTrunk;
48391     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
48392     
48393     /* If the 'exact' parameter was true and a query of the pointer-map
48394     ** shows that the page 'nearby' is somewhere on the free-list, then
48395     ** the entire-list will be searched for that page.
48396     */
48397 #ifndef SQLITE_OMIT_AUTOVACUUM
48398     if( exact && nearby<=mxPage ){
48399       u8 eType;
48400       assert( nearby>0 );
48401       assert( pBt->autoVacuum );
48402       rc = ptrmapGet(pBt, nearby, &eType, 0);
48403       if( rc ) return rc;
48404       if( eType==PTRMAP_FREEPAGE ){
48405         searchList = 1;
48406       }
48407       *pPgno = nearby;
48408     }
48409 #endif
48410
48411     /* Decrement the free-list count by 1. Set iTrunk to the index of the
48412     ** first free-list trunk page. iPrevTrunk is initially 1.
48413     */
48414     rc = sqlite3PagerWrite(pPage1->pDbPage);
48415     if( rc ) return rc;
48416     put4byte(&pPage1->aData[36], n-1);
48417
48418     /* The code within this loop is run only once if the 'searchList' variable
48419     ** is not true. Otherwise, it runs once for each trunk-page on the
48420     ** free-list until the page 'nearby' is located.
48421     */
48422     do {
48423       pPrevTrunk = pTrunk;
48424       if( pPrevTrunk ){
48425         iTrunk = get4byte(&pPrevTrunk->aData[0]);
48426       }else{
48427         iTrunk = get4byte(&pPage1->aData[32]);
48428       }
48429       testcase( iTrunk==mxPage );
48430       if( iTrunk>mxPage ){
48431         rc = SQLITE_CORRUPT_BKPT;
48432       }else{
48433         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48434       }
48435       if( rc ){
48436         pTrunk = 0;
48437         goto end_allocate_page;
48438       }
48439
48440       k = get4byte(&pTrunk->aData[4]);
48441       if( k==0 && !searchList ){
48442         /* The trunk has no leaves and the list is not being searched. 
48443         ** So extract the trunk page itself and use it as the newly 
48444         ** allocated page */
48445         assert( pPrevTrunk==0 );
48446         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48447         if( rc ){
48448           goto end_allocate_page;
48449         }
48450         *pPgno = iTrunk;
48451         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48452         *ppPage = pTrunk;
48453         pTrunk = 0;
48454         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48455       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
48456         /* Value of k is out of range.  Database corruption */
48457         rc = SQLITE_CORRUPT_BKPT;
48458         goto end_allocate_page;
48459 #ifndef SQLITE_OMIT_AUTOVACUUM
48460       }else if( searchList && nearby==iTrunk ){
48461         /* The list is being searched and this trunk page is the page
48462         ** to allocate, regardless of whether it has leaves.
48463         */
48464         assert( *pPgno==iTrunk );
48465         *ppPage = pTrunk;
48466         searchList = 0;
48467         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48468         if( rc ){
48469           goto end_allocate_page;
48470         }
48471         if( k==0 ){
48472           if( !pPrevTrunk ){
48473             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48474           }else{
48475             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
48476           }
48477         }else{
48478           /* The trunk page is required by the caller but it contains 
48479           ** pointers to free-list leaves. The first leaf becomes a trunk
48480           ** page in this case.
48481           */
48482           MemPage *pNewTrunk;
48483           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
48484           if( iNewTrunk>mxPage ){ 
48485             rc = SQLITE_CORRUPT_BKPT;
48486             goto end_allocate_page;
48487           }
48488           testcase( iNewTrunk==mxPage );
48489           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
48490           if( rc!=SQLITE_OK ){
48491             goto end_allocate_page;
48492           }
48493           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
48494           if( rc!=SQLITE_OK ){
48495             releasePage(pNewTrunk);
48496             goto end_allocate_page;
48497           }
48498           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
48499           put4byte(&pNewTrunk->aData[4], k-1);
48500           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
48501           releasePage(pNewTrunk);
48502           if( !pPrevTrunk ){
48503             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
48504             put4byte(&pPage1->aData[32], iNewTrunk);
48505           }else{
48506             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
48507             if( rc ){
48508               goto end_allocate_page;
48509             }
48510             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
48511           }
48512         }
48513         pTrunk = 0;
48514         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48515 #endif
48516       }else if( k>0 ){
48517         /* Extract a leaf from the trunk */
48518         u32 closest;
48519         Pgno iPage;
48520         unsigned char *aData = pTrunk->aData;
48521         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48522         if( rc ){
48523           goto end_allocate_page;
48524         }
48525         if( nearby>0 ){
48526           u32 i;
48527           int dist;
48528           closest = 0;
48529           dist = get4byte(&aData[8]) - nearby;
48530           if( dist<0 ) dist = -dist;
48531           for(i=1; i<k; i++){
48532             int d2 = get4byte(&aData[8+i*4]) - nearby;
48533             if( d2<0 ) d2 = -d2;
48534             if( d2<dist ){
48535               closest = i;
48536               dist = d2;
48537             }
48538           }
48539         }else{
48540           closest = 0;
48541         }
48542
48543         iPage = get4byte(&aData[8+closest*4]);
48544         testcase( iPage==mxPage );
48545         if( iPage>mxPage ){
48546           rc = SQLITE_CORRUPT_BKPT;
48547           goto end_allocate_page;
48548         }
48549         testcase( iPage==mxPage );
48550         if( !searchList || iPage==nearby ){
48551           int noContent;
48552           *pPgno = iPage;
48553           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
48554                  ": %d more free pages\n",
48555                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
48556           if( closest<k-1 ){
48557             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
48558           }
48559           put4byte(&aData[4], k-1);
48560           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
48561           noContent = !btreeGetHasContent(pBt, *pPgno);
48562           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
48563           if( rc==SQLITE_OK ){
48564             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48565             if( rc!=SQLITE_OK ){
48566               releasePage(*ppPage);
48567             }
48568           }
48569           searchList = 0;
48570         }
48571       }
48572       releasePage(pPrevTrunk);
48573       pPrevTrunk = 0;
48574     }while( searchList );
48575   }else{
48576     /* There are no pages on the freelist, so create a new page at the
48577     ** end of the file */
48578     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48579     if( rc ) return rc;
48580     pBt->nPage++;
48581     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
48582
48583 #ifndef SQLITE_OMIT_AUTOVACUUM
48584     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
48585       /* If *pPgno refers to a pointer-map page, allocate two new pages
48586       ** at the end of the file instead of one. The first allocated page
48587       ** becomes a new pointer-map page, the second is used by the caller.
48588       */
48589       MemPage *pPg = 0;
48590       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
48591       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
48592       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
48593       if( rc==SQLITE_OK ){
48594         rc = sqlite3PagerWrite(pPg->pDbPage);
48595         releasePage(pPg);
48596       }
48597       if( rc ) return rc;
48598       pBt->nPage++;
48599       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
48600     }
48601 #endif
48602     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
48603     *pPgno = pBt->nPage;
48604
48605     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48606     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
48607     if( rc ) return rc;
48608     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48609     if( rc!=SQLITE_OK ){
48610       releasePage(*ppPage);
48611     }
48612     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
48613   }
48614
48615   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48616
48617 end_allocate_page:
48618   releasePage(pTrunk);
48619   releasePage(pPrevTrunk);
48620   if( rc==SQLITE_OK ){
48621     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
48622       releasePage(*ppPage);
48623       return SQLITE_CORRUPT_BKPT;
48624     }
48625     (*ppPage)->isInit = 0;
48626   }else{
48627     *ppPage = 0;
48628   }
48629   return rc;
48630 }
48631
48632 /*
48633 ** This function is used to add page iPage to the database file free-list. 
48634 ** It is assumed that the page is not already a part of the free-list.
48635 **
48636 ** The value passed as the second argument to this function is optional.
48637 ** If the caller happens to have a pointer to the MemPage object 
48638 ** corresponding to page iPage handy, it may pass it as the second value. 
48639 ** Otherwise, it may pass NULL.
48640 **
48641 ** If a pointer to a MemPage object is passed as the second argument,
48642 ** its reference count is not altered by this function.
48643 */
48644 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
48645   MemPage *pTrunk = 0;                /* Free-list trunk page */
48646   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
48647   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
48648   MemPage *pPage;                     /* Page being freed. May be NULL. */
48649   int rc;                             /* Return Code */
48650   int nFree;                          /* Initial number of pages on free-list */
48651
48652   assert( sqlite3_mutex_held(pBt->mutex) );
48653   assert( iPage>1 );
48654   assert( !pMemPage || pMemPage->pgno==iPage );
48655
48656   if( pMemPage ){
48657     pPage = pMemPage;
48658     sqlite3PagerRef(pPage->pDbPage);
48659   }else{
48660     pPage = btreePageLookup(pBt, iPage);
48661   }
48662
48663   /* Increment the free page count on pPage1 */
48664   rc = sqlite3PagerWrite(pPage1->pDbPage);
48665   if( rc ) goto freepage_out;
48666   nFree = get4byte(&pPage1->aData[36]);
48667   put4byte(&pPage1->aData[36], nFree+1);
48668
48669   if( pBt->secureDelete ){
48670     /* If the secure_delete option is enabled, then
48671     ** always fully overwrite deleted information with zeros.
48672     */
48673     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
48674      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
48675     ){
48676       goto freepage_out;
48677     }
48678     memset(pPage->aData, 0, pPage->pBt->pageSize);
48679   }
48680
48681   /* If the database supports auto-vacuum, write an entry in the pointer-map
48682   ** to indicate that the page is free.
48683   */
48684   if( ISAUTOVACUUM ){
48685     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
48686     if( rc ) goto freepage_out;
48687   }
48688
48689   /* Now manipulate the actual database free-list structure. There are two
48690   ** possibilities. If the free-list is currently empty, or if the first
48691   ** trunk page in the free-list is full, then this page will become a
48692   ** new free-list trunk page. Otherwise, it will become a leaf of the
48693   ** first trunk page in the current free-list. This block tests if it
48694   ** is possible to add the page as a new free-list leaf.
48695   */
48696   if( nFree!=0 ){
48697     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
48698
48699     iTrunk = get4byte(&pPage1->aData[32]);
48700     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48701     if( rc!=SQLITE_OK ){
48702       goto freepage_out;
48703     }
48704
48705     nLeaf = get4byte(&pTrunk->aData[4]);
48706     assert( pBt->usableSize>32 );
48707     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
48708       rc = SQLITE_CORRUPT_BKPT;
48709       goto freepage_out;
48710     }
48711     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
48712       /* In this case there is room on the trunk page to insert the page
48713       ** being freed as a new leaf.
48714       **
48715       ** Note that the trunk page is not really full until it contains
48716       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
48717       ** coded.  But due to a coding error in versions of SQLite prior to
48718       ** 3.6.0, databases with freelist trunk pages holding more than
48719       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
48720       ** to maintain backwards compatibility with older versions of SQLite,
48721       ** we will continue to restrict the number of entries to usableSize/4 - 8
48722       ** for now.  At some point in the future (once everyone has upgraded
48723       ** to 3.6.0 or later) we should consider fixing the conditional above
48724       ** to read "usableSize/4-2" instead of "usableSize/4-8".
48725       */
48726       rc = sqlite3PagerWrite(pTrunk->pDbPage);
48727       if( rc==SQLITE_OK ){
48728         put4byte(&pTrunk->aData[4], nLeaf+1);
48729         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
48730         if( pPage && !pBt->secureDelete ){
48731           sqlite3PagerDontWrite(pPage->pDbPage);
48732         }
48733         rc = btreeSetHasContent(pBt, iPage);
48734       }
48735       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
48736       goto freepage_out;
48737     }
48738   }
48739
48740   /* If control flows to this point, then it was not possible to add the
48741   ** the page being freed as a leaf page of the first trunk in the free-list.
48742   ** Possibly because the free-list is empty, or possibly because the 
48743   ** first trunk in the free-list is full. Either way, the page being freed
48744   ** will become the new first trunk page in the free-list.
48745   */
48746   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
48747     goto freepage_out;
48748   }
48749   rc = sqlite3PagerWrite(pPage->pDbPage);
48750   if( rc!=SQLITE_OK ){
48751     goto freepage_out;
48752   }
48753   put4byte(pPage->aData, iTrunk);
48754   put4byte(&pPage->aData[4], 0);
48755   put4byte(&pPage1->aData[32], iPage);
48756   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
48757
48758 freepage_out:
48759   if( pPage ){
48760     pPage->isInit = 0;
48761   }
48762   releasePage(pPage);
48763   releasePage(pTrunk);
48764   return rc;
48765 }
48766 static void freePage(MemPage *pPage, int *pRC){
48767   if( (*pRC)==SQLITE_OK ){
48768     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
48769   }
48770 }
48771
48772 /*
48773 ** Free any overflow pages associated with the given Cell.
48774 */
48775 static int clearCell(MemPage *pPage, unsigned char *pCell){
48776   BtShared *pBt = pPage->pBt;
48777   CellInfo info;
48778   Pgno ovflPgno;
48779   int rc;
48780   int nOvfl;
48781   u16 ovflPageSize;
48782
48783   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48784   btreeParseCellPtr(pPage, pCell, &info);
48785   if( info.iOverflow==0 ){
48786     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
48787   }
48788   ovflPgno = get4byte(&pCell[info.iOverflow]);
48789   assert( pBt->usableSize > 4 );
48790   ovflPageSize = pBt->usableSize - 4;
48791   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
48792   assert( ovflPgno==0 || nOvfl>0 );
48793   while( nOvfl-- ){
48794     Pgno iNext = 0;
48795     MemPage *pOvfl = 0;
48796     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
48797       /* 0 is not a legal page number and page 1 cannot be an 
48798       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
48799       ** file the database must be corrupt. */
48800       return SQLITE_CORRUPT_BKPT;
48801     }
48802     if( nOvfl ){
48803       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
48804       if( rc ) return rc;
48805     }
48806
48807     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
48808      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
48809     ){
48810       /* There is no reason any cursor should have an outstanding reference 
48811       ** to an overflow page belonging to a cell that is being deleted/updated.
48812       ** So if there exists more than one reference to this page, then it 
48813       ** must not really be an overflow page and the database must be corrupt. 
48814       ** It is helpful to detect this before calling freePage2(), as 
48815       ** freePage2() may zero the page contents if secure-delete mode is
48816       ** enabled. If this 'overflow' page happens to be a page that the
48817       ** caller is iterating through or using in some other way, this
48818       ** can be problematic.
48819       */
48820       rc = SQLITE_CORRUPT_BKPT;
48821     }else{
48822       rc = freePage2(pBt, pOvfl, ovflPgno);
48823     }
48824
48825     if( pOvfl ){
48826       sqlite3PagerUnref(pOvfl->pDbPage);
48827     }
48828     if( rc ) return rc;
48829     ovflPgno = iNext;
48830   }
48831   return SQLITE_OK;
48832 }
48833
48834 /*
48835 ** Create the byte sequence used to represent a cell on page pPage
48836 ** and write that byte sequence into pCell[].  Overflow pages are
48837 ** allocated and filled in as necessary.  The calling procedure
48838 ** is responsible for making sure sufficient space has been allocated
48839 ** for pCell[].
48840 **
48841 ** Note that pCell does not necessary need to point to the pPage->aData
48842 ** area.  pCell might point to some temporary storage.  The cell will
48843 ** be constructed in this temporary area then copied into pPage->aData
48844 ** later.
48845 */
48846 static int fillInCell(
48847   MemPage *pPage,                /* The page that contains the cell */
48848   unsigned char *pCell,          /* Complete text of the cell */
48849   const void *pKey, i64 nKey,    /* The key */
48850   const void *pData,int nData,   /* The data */
48851   int nZero,                     /* Extra zero bytes to append to pData */
48852   int *pnSize                    /* Write cell size here */
48853 ){
48854   int nPayload;
48855   const u8 *pSrc;
48856   int nSrc, n, rc;
48857   int spaceLeft;
48858   MemPage *pOvfl = 0;
48859   MemPage *pToRelease = 0;
48860   unsigned char *pPrior;
48861   unsigned char *pPayload;
48862   BtShared *pBt = pPage->pBt;
48863   Pgno pgnoOvfl = 0;
48864   int nHeader;
48865   CellInfo info;
48866
48867   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48868
48869   /* pPage is not necessarily writeable since pCell might be auxiliary
48870   ** buffer space that is separate from the pPage buffer area */
48871   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
48872             || sqlite3PagerIswriteable(pPage->pDbPage) );
48873
48874   /* Fill in the header. */
48875   nHeader = 0;
48876   if( !pPage->leaf ){
48877     nHeader += 4;
48878   }
48879   if( pPage->hasData ){
48880     nHeader += putVarint(&pCell[nHeader], nData+nZero);
48881   }else{
48882     nData = nZero = 0;
48883   }
48884   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
48885   btreeParseCellPtr(pPage, pCell, &info);
48886   assert( info.nHeader==nHeader );
48887   assert( info.nKey==nKey );
48888   assert( info.nData==(u32)(nData+nZero) );
48889   
48890   /* Fill in the payload */
48891   nPayload = nData + nZero;
48892   if( pPage->intKey ){
48893     pSrc = pData;
48894     nSrc = nData;
48895     nData = 0;
48896   }else{ 
48897     if( NEVER(nKey>0x7fffffff || pKey==0) ){
48898       return SQLITE_CORRUPT_BKPT;
48899     }
48900     nPayload += (int)nKey;
48901     pSrc = pKey;
48902     nSrc = (int)nKey;
48903   }
48904   *pnSize = info.nSize;
48905   spaceLeft = info.nLocal;
48906   pPayload = &pCell[nHeader];
48907   pPrior = &pCell[info.iOverflow];
48908
48909   while( nPayload>0 ){
48910     if( spaceLeft==0 ){
48911 #ifndef SQLITE_OMIT_AUTOVACUUM
48912       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
48913       if( pBt->autoVacuum ){
48914         do{
48915           pgnoOvfl++;
48916         } while( 
48917           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
48918         );
48919       }
48920 #endif
48921       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
48922 #ifndef SQLITE_OMIT_AUTOVACUUM
48923       /* If the database supports auto-vacuum, and the second or subsequent
48924       ** overflow page is being allocated, add an entry to the pointer-map
48925       ** for that page now. 
48926       **
48927       ** If this is the first overflow page, then write a partial entry 
48928       ** to the pointer-map. If we write nothing to this pointer-map slot,
48929       ** then the optimistic overflow chain processing in clearCell()
48930       ** may misinterpret the uninitialised values and delete the
48931       ** wrong pages from the database.
48932       */
48933       if( pBt->autoVacuum && rc==SQLITE_OK ){
48934         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
48935         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
48936         if( rc ){
48937           releasePage(pOvfl);
48938         }
48939       }
48940 #endif
48941       if( rc ){
48942         releasePage(pToRelease);
48943         return rc;
48944       }
48945
48946       /* If pToRelease is not zero than pPrior points into the data area
48947       ** of pToRelease.  Make sure pToRelease is still writeable. */
48948       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48949
48950       /* If pPrior is part of the data area of pPage, then make sure pPage
48951       ** is still writeable */
48952       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
48953             || sqlite3PagerIswriteable(pPage->pDbPage) );
48954
48955       put4byte(pPrior, pgnoOvfl);
48956       releasePage(pToRelease);
48957       pToRelease = pOvfl;
48958       pPrior = pOvfl->aData;
48959       put4byte(pPrior, 0);
48960       pPayload = &pOvfl->aData[4];
48961       spaceLeft = pBt->usableSize - 4;
48962     }
48963     n = nPayload;
48964     if( n>spaceLeft ) n = spaceLeft;
48965
48966     /* If pToRelease is not zero than pPayload points into the data area
48967     ** of pToRelease.  Make sure pToRelease is still writeable. */
48968     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48969
48970     /* If pPayload is part of the data area of pPage, then make sure pPage
48971     ** is still writeable */
48972     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
48973             || sqlite3PagerIswriteable(pPage->pDbPage) );
48974
48975     if( nSrc>0 ){
48976       if( n>nSrc ) n = nSrc;
48977       assert( pSrc );
48978       memcpy(pPayload, pSrc, n);
48979     }else{
48980       memset(pPayload, 0, n);
48981     }
48982     nPayload -= n;
48983     pPayload += n;
48984     pSrc += n;
48985     nSrc -= n;
48986     spaceLeft -= n;
48987     if( nSrc==0 ){
48988       nSrc = nData;
48989       pSrc = pData;
48990     }
48991   }
48992   releasePage(pToRelease);
48993   return SQLITE_OK;
48994 }
48995
48996 /*
48997 ** Remove the i-th cell from pPage.  This routine effects pPage only.
48998 ** The cell content is not freed or deallocated.  It is assumed that
48999 ** the cell content has been copied someplace else.  This routine just
49000 ** removes the reference to the cell from pPage.
49001 **
49002 ** "sz" must be the number of bytes in the cell.
49003 */
49004 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
49005   int i;          /* Loop counter */
49006   int pc;         /* Offset to cell content of cell being deleted */
49007   u8 *data;       /* pPage->aData */
49008   u8 *ptr;        /* Used to move bytes around within data[] */
49009   int rc;         /* The return code */
49010   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
49011
49012   if( *pRC ) return;
49013
49014   assert( idx>=0 && idx<pPage->nCell );
49015   assert( sz==cellSize(pPage, idx) );
49016   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49017   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49018   data = pPage->aData;
49019   ptr = &data[pPage->cellOffset + 2*idx];
49020   pc = get2byte(ptr);
49021   hdr = pPage->hdrOffset;
49022   testcase( pc==get2byte(&data[hdr+5]) );
49023   testcase( pc+sz==pPage->pBt->usableSize );
49024   if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
49025     *pRC = SQLITE_CORRUPT_BKPT;
49026     return;
49027   }
49028   rc = freeSpace(pPage, pc, sz);
49029   if( rc ){
49030     *pRC = rc;
49031     return;
49032   }
49033   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
49034     ptr[0] = ptr[2];
49035     ptr[1] = ptr[3];
49036   }
49037   pPage->nCell--;
49038   put2byte(&data[hdr+3], pPage->nCell);
49039   pPage->nFree += 2;
49040 }
49041
49042 /*
49043 ** Insert a new cell on pPage at cell index "i".  pCell points to the
49044 ** content of the cell.
49045 **
49046 ** If the cell content will fit on the page, then put it there.  If it
49047 ** will not fit, then make a copy of the cell content into pTemp if
49048 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
49049 ** in pPage->aOvfl[] and make it point to the cell content (either
49050 ** in pTemp or the original pCell) and also record its index. 
49051 ** Allocating a new entry in pPage->aCell[] implies that 
49052 ** pPage->nOverflow is incremented.
49053 **
49054 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
49055 ** cell. The caller will overwrite them after this function returns. If
49056 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
49057 ** (but pCell+nSkip is always valid).
49058 */
49059 static void insertCell(
49060   MemPage *pPage,   /* Page into which we are copying */
49061   int i,            /* New cell becomes the i-th cell of the page */
49062   u8 *pCell,        /* Content of the new cell */
49063   int sz,           /* Bytes of content in pCell */
49064   u8 *pTemp,        /* Temp storage space for pCell, if needed */
49065   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
49066   int *pRC          /* Read and write return code from here */
49067 ){
49068   int idx = 0;      /* Where to write new cell content in data[] */
49069   int j;            /* Loop counter */
49070   int end;          /* First byte past the last cell pointer in data[] */
49071   int ins;          /* Index in data[] where new cell pointer is inserted */
49072   int cellOffset;   /* Address of first cell pointer in data[] */
49073   u8 *data;         /* The content of the whole page */
49074   u8 *ptr;          /* Used for moving information around in data[] */
49075
49076   int nSkip = (iChild ? 4 : 0);
49077
49078   if( *pRC ) return;
49079
49080   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
49081   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
49082   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
49083   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49084   /* The cell should normally be sized correctly.  However, when moving a
49085   ** malformed cell from a leaf page to an interior page, if the cell size
49086   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
49087   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
49088   ** the term after the || in the following assert(). */
49089   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
49090   if( pPage->nOverflow || sz+2>pPage->nFree ){
49091     if( pTemp ){
49092       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
49093       pCell = pTemp;
49094     }
49095     if( iChild ){
49096       put4byte(pCell, iChild);
49097     }
49098     j = pPage->nOverflow++;
49099     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
49100     pPage->aOvfl[j].pCell = pCell;
49101     pPage->aOvfl[j].idx = (u16)i;
49102   }else{
49103     int rc = sqlite3PagerWrite(pPage->pDbPage);
49104     if( rc!=SQLITE_OK ){
49105       *pRC = rc;
49106       return;
49107     }
49108     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49109     data = pPage->aData;
49110     cellOffset = pPage->cellOffset;
49111     end = cellOffset + 2*pPage->nCell;
49112     ins = cellOffset + 2*i;
49113     rc = allocateSpace(pPage, sz, &idx);
49114     if( rc ){ *pRC = rc; return; }
49115     /* The allocateSpace() routine guarantees the following two properties
49116     ** if it returns success */
49117     assert( idx >= end+2 );
49118     assert( idx+sz <= pPage->pBt->usableSize );
49119     pPage->nCell++;
49120     pPage->nFree -= (u16)(2 + sz);
49121     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
49122     if( iChild ){
49123       put4byte(&data[idx], iChild);
49124     }
49125     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
49126       ptr[0] = ptr[-2];
49127       ptr[1] = ptr[-1];
49128     }
49129     put2byte(&data[ins], idx);
49130     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
49131 #ifndef SQLITE_OMIT_AUTOVACUUM
49132     if( pPage->pBt->autoVacuum ){
49133       /* The cell may contain a pointer to an overflow page. If so, write
49134       ** the entry for the overflow page into the pointer map.
49135       */
49136       ptrmapPutOvflPtr(pPage, pCell, pRC);
49137     }
49138 #endif
49139   }
49140 }
49141
49142 /*
49143 ** Add a list of cells to a page.  The page should be initially empty.
49144 ** The cells are guaranteed to fit on the page.
49145 */
49146 static void assemblePage(
49147   MemPage *pPage,   /* The page to be assemblied */
49148   int nCell,        /* The number of cells to add to this page */
49149   u8 **apCell,      /* Pointers to cell bodies */
49150   u16 *aSize        /* Sizes of the cells */
49151 ){
49152   int i;            /* Loop counter */
49153   u8 *pCellptr;     /* Address of next cell pointer */
49154   int cellbody;     /* Address of next cell body */
49155   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
49156   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
49157   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
49158
49159   assert( pPage->nOverflow==0 );
49160   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49161   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
49162   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49163
49164   /* Check that the page has just been zeroed by zeroPage() */
49165   assert( pPage->nCell==0 );
49166   assert( get2byte(&data[hdr+5])==nUsable );
49167
49168   pCellptr = &data[pPage->cellOffset + nCell*2];
49169   cellbody = nUsable;
49170   for(i=nCell-1; i>=0; i--){
49171     pCellptr -= 2;
49172     cellbody -= aSize[i];
49173     put2byte(pCellptr, cellbody);
49174     memcpy(&data[cellbody], apCell[i], aSize[i]);
49175   }
49176   put2byte(&data[hdr+3], nCell);
49177   put2byte(&data[hdr+5], cellbody);
49178   pPage->nFree -= (nCell*2 + nUsable - cellbody);
49179   pPage->nCell = (u16)nCell;
49180 }
49181
49182 /*
49183 ** The following parameters determine how many adjacent pages get involved
49184 ** in a balancing operation.  NN is the number of neighbors on either side
49185 ** of the page that participate in the balancing operation.  NB is the
49186 ** total number of pages that participate, including the target page and
49187 ** NN neighbors on either side.
49188 **
49189 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
49190 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
49191 ** in exchange for a larger degradation in INSERT and UPDATE performance.
49192 ** The value of NN appears to give the best results overall.
49193 */
49194 #define NN 1             /* Number of neighbors on either side of pPage */
49195 #define NB (NN*2+1)      /* Total pages involved in the balance */
49196
49197
49198 #ifndef SQLITE_OMIT_QUICKBALANCE
49199 /*
49200 ** This version of balance() handles the common special case where
49201 ** a new entry is being inserted on the extreme right-end of the
49202 ** tree, in other words, when the new entry will become the largest
49203 ** entry in the tree.
49204 **
49205 ** Instead of trying to balance the 3 right-most leaf pages, just add
49206 ** a new page to the right-hand side and put the one new entry in
49207 ** that page.  This leaves the right side of the tree somewhat
49208 ** unbalanced.  But odds are that we will be inserting new entries
49209 ** at the end soon afterwards so the nearly empty page will quickly
49210 ** fill up.  On average.
49211 **
49212 ** pPage is the leaf page which is the right-most page in the tree.
49213 ** pParent is its parent.  pPage must have a single overflow entry
49214 ** which is also the right-most entry on the page.
49215 **
49216 ** The pSpace buffer is used to store a temporary copy of the divider
49217 ** cell that will be inserted into pParent. Such a cell consists of a 4
49218 ** byte page number followed by a variable length integer. In other
49219 ** words, at most 13 bytes. Hence the pSpace buffer must be at
49220 ** least 13 bytes in size.
49221 */
49222 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
49223   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
49224   MemPage *pNew;                       /* Newly allocated page */
49225   int rc;                              /* Return Code */
49226   Pgno pgnoNew;                        /* Page number of pNew */
49227
49228   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49229   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49230   assert( pPage->nOverflow==1 );
49231
49232   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
49233
49234   /* Allocate a new page. This page will become the right-sibling of 
49235   ** pPage. Make the parent page writable, so that the new divider cell
49236   ** may be inserted. If both these operations are successful, proceed.
49237   */
49238   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
49239
49240   if( rc==SQLITE_OK ){
49241
49242     u8 *pOut = &pSpace[4];
49243     u8 *pCell = pPage->aOvfl[0].pCell;
49244     u16 szCell = cellSizePtr(pPage, pCell);
49245     u8 *pStop;
49246
49247     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
49248     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
49249     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
49250     assemblePage(pNew, 1, &pCell, &szCell);
49251
49252     /* If this is an auto-vacuum database, update the pointer map
49253     ** with entries for the new page, and any pointer from the 
49254     ** cell on the page to an overflow page. If either of these
49255     ** operations fails, the return code is set, but the contents
49256     ** of the parent page are still manipulated by thh code below.
49257     ** That is Ok, at this point the parent page is guaranteed to
49258     ** be marked as dirty. Returning an error code will cause a
49259     ** rollback, undoing any changes made to the parent page.
49260     */
49261     if( ISAUTOVACUUM ){
49262       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
49263       if( szCell>pNew->minLocal ){
49264         ptrmapPutOvflPtr(pNew, pCell, &rc);
49265       }
49266     }
49267   
49268     /* Create a divider cell to insert into pParent. The divider cell
49269     ** consists of a 4-byte page number (the page number of pPage) and
49270     ** a variable length key value (which must be the same value as the
49271     ** largest key on pPage).
49272     **
49273     ** To find the largest key value on pPage, first find the right-most 
49274     ** cell on pPage. The first two fields of this cell are the 
49275     ** record-length (a variable length integer at most 32-bits in size)
49276     ** and the key value (a variable length integer, may have any value).
49277     ** The first of the while(...) loops below skips over the record-length
49278     ** field. The second while(...) loop copies the key value from the
49279     ** cell on pPage into the pSpace buffer.
49280     */
49281     pCell = findCell(pPage, pPage->nCell-1);
49282     pStop = &pCell[9];
49283     while( (*(pCell++)&0x80) && pCell<pStop );
49284     pStop = &pCell[9];
49285     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
49286
49287     /* Insert the new divider cell into pParent. */
49288     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
49289                0, pPage->pgno, &rc);
49290
49291     /* Set the right-child pointer of pParent to point to the new page. */
49292     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
49293   
49294     /* Release the reference to the new page. */
49295     releasePage(pNew);
49296   }
49297
49298   return rc;
49299 }
49300 #endif /* SQLITE_OMIT_QUICKBALANCE */
49301
49302 #if 0
49303 /*
49304 ** This function does not contribute anything to the operation of SQLite.
49305 ** it is sometimes activated temporarily while debugging code responsible 
49306 ** for setting pointer-map entries.
49307 */
49308 static int ptrmapCheckPages(MemPage **apPage, int nPage){
49309   int i, j;
49310   for(i=0; i<nPage; i++){
49311     Pgno n;
49312     u8 e;
49313     MemPage *pPage = apPage[i];
49314     BtShared *pBt = pPage->pBt;
49315     assert( pPage->isInit );
49316
49317     for(j=0; j<pPage->nCell; j++){
49318       CellInfo info;
49319       u8 *z;
49320      
49321       z = findCell(pPage, j);
49322       btreeParseCellPtr(pPage, z, &info);
49323       if( info.iOverflow ){
49324         Pgno ovfl = get4byte(&z[info.iOverflow]);
49325         ptrmapGet(pBt, ovfl, &e, &n);
49326         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
49327       }
49328       if( !pPage->leaf ){
49329         Pgno child = get4byte(z);
49330         ptrmapGet(pBt, child, &e, &n);
49331         assert( n==pPage->pgno && e==PTRMAP_BTREE );
49332       }
49333     }
49334     if( !pPage->leaf ){
49335       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49336       ptrmapGet(pBt, child, &e, &n);
49337       assert( n==pPage->pgno && e==PTRMAP_BTREE );
49338     }
49339   }
49340   return 1;
49341 }
49342 #endif
49343
49344 /*
49345 ** This function is used to copy the contents of the b-tree node stored 
49346 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
49347 ** the pointer-map entries for each child page are updated so that the
49348 ** parent page stored in the pointer map is page pTo. If pFrom contained
49349 ** any cells with overflow page pointers, then the corresponding pointer
49350 ** map entries are also updated so that the parent page is page pTo.
49351 **
49352 ** If pFrom is currently carrying any overflow cells (entries in the
49353 ** MemPage.aOvfl[] array), they are not copied to pTo. 
49354 **
49355 ** Before returning, page pTo is reinitialized using btreeInitPage().
49356 **
49357 ** The performance of this function is not critical. It is only used by 
49358 ** the balance_shallower() and balance_deeper() procedures, neither of
49359 ** which are called often under normal circumstances.
49360 */
49361 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
49362   if( (*pRC)==SQLITE_OK ){
49363     BtShared * const pBt = pFrom->pBt;
49364     u8 * const aFrom = pFrom->aData;
49365     u8 * const aTo = pTo->aData;
49366     int const iFromHdr = pFrom->hdrOffset;
49367     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
49368     int rc;
49369     int iData;
49370   
49371   
49372     assert( pFrom->isInit );
49373     assert( pFrom->nFree>=iToHdr );
49374     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
49375   
49376     /* Copy the b-tree node content from page pFrom to page pTo. */
49377     iData = get2byte(&aFrom[iFromHdr+5]);
49378     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
49379     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
49380   
49381     /* Reinitialize page pTo so that the contents of the MemPage structure
49382     ** match the new data. The initialization of pTo can actually fail under
49383     ** fairly obscure circumstances, even though it is a copy of initialized 
49384     ** page pFrom.
49385     */
49386     pTo->isInit = 0;
49387     rc = btreeInitPage(pTo);
49388     if( rc!=SQLITE_OK ){
49389       *pRC = rc;
49390       return;
49391     }
49392   
49393     /* If this is an auto-vacuum database, update the pointer-map entries
49394     ** for any b-tree or overflow pages that pTo now contains the pointers to.
49395     */
49396     if( ISAUTOVACUUM ){
49397       *pRC = setChildPtrmaps(pTo);
49398     }
49399   }
49400 }
49401
49402 /*
49403 ** This routine redistributes cells on the iParentIdx'th child of pParent
49404 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
49405 ** same amount of free space. Usually a single sibling on either side of the
49406 ** page are used in the balancing, though both siblings might come from one
49407 ** side if the page is the first or last child of its parent. If the page 
49408 ** has fewer than 2 siblings (something which can only happen if the page
49409 ** is a root page or a child of a root page) then all available siblings
49410 ** participate in the balancing.
49411 **
49412 ** The number of siblings of the page might be increased or decreased by 
49413 ** one or two in an effort to keep pages nearly full but not over full. 
49414 **
49415 ** Note that when this routine is called, some of the cells on the page
49416 ** might not actually be stored in MemPage.aData[]. This can happen
49417 ** if the page is overfull. This routine ensures that all cells allocated
49418 ** to the page and its siblings fit into MemPage.aData[] before returning.
49419 **
49420 ** In the course of balancing the page and its siblings, cells may be
49421 ** inserted into or removed from the parent page (pParent). Doing so
49422 ** may cause the parent page to become overfull or underfull. If this
49423 ** happens, it is the responsibility of the caller to invoke the correct
49424 ** balancing routine to fix this problem (see the balance() routine). 
49425 **
49426 ** If this routine fails for any reason, it might leave the database
49427 ** in a corrupted state. So if this routine fails, the database should
49428 ** be rolled back.
49429 **
49430 ** The third argument to this function, aOvflSpace, is a pointer to a
49431 ** buffer big enough to hold one page. If while inserting cells into the parent
49432 ** page (pParent) the parent page becomes overfull, this buffer is
49433 ** used to store the parent's overflow cells. Because this function inserts
49434 ** a maximum of four divider cells into the parent page, and the maximum
49435 ** size of a cell stored within an internal node is always less than 1/4
49436 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
49437 ** enough for all overflow cells.
49438 **
49439 ** If aOvflSpace is set to a null pointer, this function returns 
49440 ** SQLITE_NOMEM.
49441 */
49442 static int balance_nonroot(
49443   MemPage *pParent,               /* Parent page of siblings being balanced */
49444   int iParentIdx,                 /* Index of "the page" in pParent */
49445   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
49446   int isRoot                      /* True if pParent is a root-page */
49447 ){
49448   BtShared *pBt;               /* The whole database */
49449   int nCell = 0;               /* Number of cells in apCell[] */
49450   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
49451   int nNew = 0;                /* Number of pages in apNew[] */
49452   int nOld;                    /* Number of pages in apOld[] */
49453   int i, j, k;                 /* Loop counters */
49454   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
49455   int rc = SQLITE_OK;          /* The return code */
49456   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
49457   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
49458   int usableSpace;             /* Bytes in pPage beyond the header */
49459   int pageFlags;               /* Value of pPage->aData[0] */
49460   int subtotal;                /* Subtotal of bytes in cells on one page */
49461   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
49462   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
49463   int szScratch;               /* Size of scratch memory requested */
49464   MemPage *apOld[NB];          /* pPage and up to two siblings */
49465   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
49466   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
49467   u8 *pRight;                  /* Location in parent of right-sibling pointer */
49468   u8 *apDiv[NB-1];             /* Divider cells in pParent */
49469   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
49470   int szNew[NB+2];             /* Combined size of cells place on i-th page */
49471   u8 **apCell = 0;             /* All cells begin balanced */
49472   u16 *szCell;                 /* Local size of all cells in apCell[] */
49473   u8 *aSpace1;                 /* Space for copies of dividers cells */
49474   Pgno pgno;                   /* Temp var to store a page number in */
49475
49476   pBt = pParent->pBt;
49477   assert( sqlite3_mutex_held(pBt->mutex) );
49478   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49479
49480 #if 0
49481   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
49482 #endif
49483
49484   /* At this point pParent may have at most one overflow cell. And if
49485   ** this overflow cell is present, it must be the cell with 
49486   ** index iParentIdx. This scenario comes about when this function
49487   ** is called (indirectly) from sqlite3BtreeDelete().
49488   */
49489   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
49490   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
49491
49492   if( !aOvflSpace ){
49493     return SQLITE_NOMEM;
49494   }
49495
49496   /* Find the sibling pages to balance. Also locate the cells in pParent 
49497   ** that divide the siblings. An attempt is made to find NN siblings on 
49498   ** either side of pPage. More siblings are taken from one side, however, 
49499   ** if there are fewer than NN siblings on the other side. If pParent
49500   ** has NB or fewer children then all children of pParent are taken.  
49501   **
49502   ** This loop also drops the divider cells from the parent page. This
49503   ** way, the remainder of the function does not have to deal with any
49504   ** overflow cells in the parent page, since if any existed they will
49505   ** have already been removed.
49506   */
49507   i = pParent->nOverflow + pParent->nCell;
49508   if( i<2 ){
49509     nxDiv = 0;
49510     nOld = i+1;
49511   }else{
49512     nOld = 3;
49513     if( iParentIdx==0 ){                 
49514       nxDiv = 0;
49515     }else if( iParentIdx==i ){
49516       nxDiv = i-2;
49517     }else{
49518       nxDiv = iParentIdx-1;
49519     }
49520     i = 2;
49521   }
49522   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
49523     pRight = &pParent->aData[pParent->hdrOffset+8];
49524   }else{
49525     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
49526   }
49527   pgno = get4byte(pRight);
49528   while( 1 ){
49529     rc = getAndInitPage(pBt, pgno, &apOld[i]);
49530     if( rc ){
49531       memset(apOld, 0, (i+1)*sizeof(MemPage*));
49532       goto balance_cleanup;
49533     }
49534     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
49535     if( (i--)==0 ) break;
49536
49537     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
49538       apDiv[i] = pParent->aOvfl[0].pCell;
49539       pgno = get4byte(apDiv[i]);
49540       szNew[i] = cellSizePtr(pParent, apDiv[i]);
49541       pParent->nOverflow = 0;
49542     }else{
49543       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
49544       pgno = get4byte(apDiv[i]);
49545       szNew[i] = cellSizePtr(pParent, apDiv[i]);
49546
49547       /* Drop the cell from the parent page. apDiv[i] still points to
49548       ** the cell within the parent, even though it has been dropped.
49549       ** This is safe because dropping a cell only overwrites the first
49550       ** four bytes of it, and this function does not need the first
49551       ** four bytes of the divider cell. So the pointer is safe to use
49552       ** later on.  
49553       **
49554       ** Unless SQLite is compiled in secure-delete mode. In this case,
49555       ** the dropCell() routine will overwrite the entire cell with zeroes.
49556       ** In this case, temporarily copy the cell into the aOvflSpace[]
49557       ** buffer. It will be copied out again as soon as the aSpace[] buffer
49558       ** is allocated.  */
49559       if( pBt->secureDelete ){
49560         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
49561         if( (iOff+szNew[i])>pBt->usableSize ){
49562           rc = SQLITE_CORRUPT_BKPT;
49563           memset(apOld, 0, (i+1)*sizeof(MemPage*));
49564           goto balance_cleanup;
49565         }else{
49566           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
49567           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
49568         }
49569       }
49570       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
49571     }
49572   }
49573
49574   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
49575   ** alignment */
49576   nMaxCells = (nMaxCells + 3)&~3;
49577
49578   /*
49579   ** Allocate space for memory structures
49580   */
49581   k = pBt->pageSize + ROUND8(sizeof(MemPage));
49582   szScratch =
49583        nMaxCells*sizeof(u8*)                       /* apCell */
49584      + nMaxCells*sizeof(u16)                       /* szCell */
49585      + pBt->pageSize                               /* aSpace1 */
49586      + k*nOld;                                     /* Page copies (apCopy) */
49587   apCell = sqlite3ScratchMalloc( szScratch ); 
49588   if( apCell==0 ){
49589     rc = SQLITE_NOMEM;
49590     goto balance_cleanup;
49591   }
49592   szCell = (u16*)&apCell[nMaxCells];
49593   aSpace1 = (u8*)&szCell[nMaxCells];
49594   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
49595
49596   /*
49597   ** Load pointers to all cells on sibling pages and the divider cells
49598   ** into the local apCell[] array.  Make copies of the divider cells
49599   ** into space obtained from aSpace1[] and remove the the divider Cells
49600   ** from pParent.
49601   **
49602   ** If the siblings are on leaf pages, then the child pointers of the
49603   ** divider cells are stripped from the cells before they are copied
49604   ** into aSpace1[].  In this way, all cells in apCell[] are without
49605   ** child pointers.  If siblings are not leaves, then all cell in
49606   ** apCell[] include child pointers.  Either way, all cells in apCell[]
49607   ** are alike.
49608   **
49609   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
49610   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
49611   */
49612   leafCorrection = apOld[0]->leaf*4;
49613   leafData = apOld[0]->hasData;
49614   for(i=0; i<nOld; i++){
49615     int limit;
49616     
49617     /* Before doing anything else, take a copy of the i'th original sibling
49618     ** The rest of this function will use data from the copies rather
49619     ** that the original pages since the original pages will be in the
49620     ** process of being overwritten.  */
49621     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
49622     memcpy(pOld, apOld[i], sizeof(MemPage));
49623     pOld->aData = (void*)&pOld[1];
49624     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
49625
49626     limit = pOld->nCell+pOld->nOverflow;
49627     for(j=0; j<limit; j++){
49628       assert( nCell<nMaxCells );
49629       apCell[nCell] = findOverflowCell(pOld, j);
49630       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
49631       nCell++;
49632     }
49633     if( i<nOld-1 && !leafData){
49634       u16 sz = (u16)szNew[i];
49635       u8 *pTemp;
49636       assert( nCell<nMaxCells );
49637       szCell[nCell] = sz;
49638       pTemp = &aSpace1[iSpace1];
49639       iSpace1 += sz;
49640       assert( sz<=pBt->pageSize/4 );
49641       assert( iSpace1<=pBt->pageSize );
49642       memcpy(pTemp, apDiv[i], sz);
49643       apCell[nCell] = pTemp+leafCorrection;
49644       assert( leafCorrection==0 || leafCorrection==4 );
49645       szCell[nCell] = szCell[nCell] - leafCorrection;
49646       if( !pOld->leaf ){
49647         assert( leafCorrection==0 );
49648         assert( pOld->hdrOffset==0 );
49649         /* The right pointer of the child page pOld becomes the left
49650         ** pointer of the divider cell */
49651         memcpy(apCell[nCell], &pOld->aData[8], 4);
49652       }else{
49653         assert( leafCorrection==4 );
49654         if( szCell[nCell]<4 ){
49655           /* Do not allow any cells smaller than 4 bytes. */
49656           szCell[nCell] = 4;
49657         }
49658       }
49659       nCell++;
49660     }
49661   }
49662
49663   /*
49664   ** Figure out the number of pages needed to hold all nCell cells.
49665   ** Store this number in "k".  Also compute szNew[] which is the total
49666   ** size of all cells on the i-th page and cntNew[] which is the index
49667   ** in apCell[] of the cell that divides page i from page i+1.  
49668   ** cntNew[k] should equal nCell.
49669   **
49670   ** Values computed by this block:
49671   **
49672   **           k: The total number of sibling pages
49673   **    szNew[i]: Spaced used on the i-th sibling page.
49674   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
49675   **              the right of the i-th sibling page.
49676   ** usableSpace: Number of bytes of space available on each sibling.
49677   ** 
49678   */
49679   usableSpace = pBt->usableSize - 12 + leafCorrection;
49680   for(subtotal=k=i=0; i<nCell; i++){
49681     assert( i<nMaxCells );
49682     subtotal += szCell[i] + 2;
49683     if( subtotal > usableSpace ){
49684       szNew[k] = subtotal - szCell[i];
49685       cntNew[k] = i;
49686       if( leafData ){ i--; }
49687       subtotal = 0;
49688       k++;
49689       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
49690     }
49691   }
49692   szNew[k] = subtotal;
49693   cntNew[k] = nCell;
49694   k++;
49695
49696   /*
49697   ** The packing computed by the previous block is biased toward the siblings
49698   ** on the left side.  The left siblings are always nearly full, while the
49699   ** right-most sibling might be nearly empty.  This block of code attempts
49700   ** to adjust the packing of siblings to get a better balance.
49701   **
49702   ** This adjustment is more than an optimization.  The packing above might
49703   ** be so out of balance as to be illegal.  For example, the right-most
49704   ** sibling might be completely empty.  This adjustment is not optional.
49705   */
49706   for(i=k-1; i>0; i--){
49707     int szRight = szNew[i];  /* Size of sibling on the right */
49708     int szLeft = szNew[i-1]; /* Size of sibling on the left */
49709     int r;              /* Index of right-most cell in left sibling */
49710     int d;              /* Index of first cell to the left of right sibling */
49711
49712     r = cntNew[i-1] - 1;
49713     d = r + 1 - leafData;
49714     assert( d<nMaxCells );
49715     assert( r<nMaxCells );
49716     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
49717       szRight += szCell[d] + 2;
49718       szLeft -= szCell[r] + 2;
49719       cntNew[i-1]--;
49720       r = cntNew[i-1] - 1;
49721       d = r + 1 - leafData;
49722     }
49723     szNew[i] = szRight;
49724     szNew[i-1] = szLeft;
49725   }
49726
49727   /* Either we found one or more cells (cntnew[0])>0) or pPage is
49728   ** a virtual root page.  A virtual root page is when the real root
49729   ** page is page 1 and we are the only child of that page.
49730   */
49731   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
49732
49733   TRACE(("BALANCE: old: %d %d %d  ",
49734     apOld[0]->pgno, 
49735     nOld>=2 ? apOld[1]->pgno : 0,
49736     nOld>=3 ? apOld[2]->pgno : 0
49737   ));
49738
49739   /*
49740   ** Allocate k new pages.  Reuse old pages where possible.
49741   */
49742   if( apOld[0]->pgno<=1 ){
49743     rc = SQLITE_CORRUPT_BKPT;
49744     goto balance_cleanup;
49745   }
49746   pageFlags = apOld[0]->aData[0];
49747   for(i=0; i<k; i++){
49748     MemPage *pNew;
49749     if( i<nOld ){
49750       pNew = apNew[i] = apOld[i];
49751       apOld[i] = 0;
49752       rc = sqlite3PagerWrite(pNew->pDbPage);
49753       nNew++;
49754       if( rc ) goto balance_cleanup;
49755     }else{
49756       assert( i>0 );
49757       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
49758       if( rc ) goto balance_cleanup;
49759       apNew[i] = pNew;
49760       nNew++;
49761
49762       /* Set the pointer-map entry for the new sibling page. */
49763       if( ISAUTOVACUUM ){
49764         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
49765         if( rc!=SQLITE_OK ){
49766           goto balance_cleanup;
49767         }
49768       }
49769     }
49770   }
49771
49772   /* Free any old pages that were not reused as new pages.
49773   */
49774   while( i<nOld ){
49775     freePage(apOld[i], &rc);
49776     if( rc ) goto balance_cleanup;
49777     releasePage(apOld[i]);
49778     apOld[i] = 0;
49779     i++;
49780   }
49781
49782   /*
49783   ** Put the new pages in accending order.  This helps to
49784   ** keep entries in the disk file in order so that a scan
49785   ** of the table is a linear scan through the file.  That
49786   ** in turn helps the operating system to deliver pages
49787   ** from the disk more rapidly.
49788   **
49789   ** An O(n^2) insertion sort algorithm is used, but since
49790   ** n is never more than NB (a small constant), that should
49791   ** not be a problem.
49792   **
49793   ** When NB==3, this one optimization makes the database
49794   ** about 25% faster for large insertions and deletions.
49795   */
49796   for(i=0; i<k-1; i++){
49797     int minV = apNew[i]->pgno;
49798     int minI = i;
49799     for(j=i+1; j<k; j++){
49800       if( apNew[j]->pgno<(unsigned)minV ){
49801         minI = j;
49802         minV = apNew[j]->pgno;
49803       }
49804     }
49805     if( minI>i ){
49806       int t;
49807       MemPage *pT;
49808       t = apNew[i]->pgno;
49809       pT = apNew[i];
49810       apNew[i] = apNew[minI];
49811       apNew[minI] = pT;
49812     }
49813   }
49814   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
49815     apNew[0]->pgno, szNew[0],
49816     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
49817     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
49818     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
49819     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
49820
49821   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49822   put4byte(pRight, apNew[nNew-1]->pgno);
49823
49824   /*
49825   ** Evenly distribute the data in apCell[] across the new pages.
49826   ** Insert divider cells into pParent as necessary.
49827   */
49828   j = 0;
49829   for(i=0; i<nNew; i++){
49830     /* Assemble the new sibling page. */
49831     MemPage *pNew = apNew[i];
49832     assert( j<nMaxCells );
49833     zeroPage(pNew, pageFlags);
49834     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
49835     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
49836     assert( pNew->nOverflow==0 );
49837
49838     j = cntNew[i];
49839
49840     /* If the sibling page assembled above was not the right-most sibling,
49841     ** insert a divider cell into the parent page.
49842     */
49843     assert( i<nNew-1 || j==nCell );
49844     if( j<nCell ){
49845       u8 *pCell;
49846       u8 *pTemp;
49847       int sz;
49848
49849       assert( j<nMaxCells );
49850       pCell = apCell[j];
49851       sz = szCell[j] + leafCorrection;
49852       pTemp = &aOvflSpace[iOvflSpace];
49853       if( !pNew->leaf ){
49854         memcpy(&pNew->aData[8], pCell, 4);
49855       }else if( leafData ){
49856         /* If the tree is a leaf-data tree, and the siblings are leaves, 
49857         ** then there is no divider cell in apCell[]. Instead, the divider 
49858         ** cell consists of the integer key for the right-most cell of 
49859         ** the sibling-page assembled above only.
49860         */
49861         CellInfo info;
49862         j--;
49863         btreeParseCellPtr(pNew, apCell[j], &info);
49864         pCell = pTemp;
49865         sz = 4 + putVarint(&pCell[4], info.nKey);
49866         pTemp = 0;
49867       }else{
49868         pCell -= 4;
49869         /* Obscure case for non-leaf-data trees: If the cell at pCell was
49870         ** previously stored on a leaf node, and its reported size was 4
49871         ** bytes, then it may actually be smaller than this 
49872         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
49873         ** any cell). But it is important to pass the correct size to 
49874         ** insertCell(), so reparse the cell now.
49875         **
49876         ** Note that this can never happen in an SQLite data file, as all
49877         ** cells are at least 4 bytes. It only happens in b-trees used
49878         ** to evaluate "IN (SELECT ...)" and similar clauses.
49879         */
49880         if( szCell[j]==4 ){
49881           assert(leafCorrection==4);
49882           sz = cellSizePtr(pParent, pCell);
49883         }
49884       }
49885       iOvflSpace += sz;
49886       assert( sz<=pBt->pageSize/4 );
49887       assert( iOvflSpace<=pBt->pageSize );
49888       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
49889       if( rc!=SQLITE_OK ) goto balance_cleanup;
49890       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49891
49892       j++;
49893       nxDiv++;
49894     }
49895   }
49896   assert( j==nCell );
49897   assert( nOld>0 );
49898   assert( nNew>0 );
49899   if( (pageFlags & PTF_LEAF)==0 ){
49900     u8 *zChild = &apCopy[nOld-1]->aData[8];
49901     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
49902   }
49903
49904   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
49905     /* The root page of the b-tree now contains no cells. The only sibling
49906     ** page is the right-child of the parent. Copy the contents of the
49907     ** child page into the parent, decreasing the overall height of the
49908     ** b-tree structure by one. This is described as the "balance-shallower"
49909     ** sub-algorithm in some documentation.
49910     **
49911     ** If this is an auto-vacuum database, the call to copyNodeContent() 
49912     ** sets all pointer-map entries corresponding to database image pages 
49913     ** for which the pointer is stored within the content being copied.
49914     **
49915     ** The second assert below verifies that the child page is defragmented
49916     ** (it must be, as it was just reconstructed using assemblePage()). This
49917     ** is important if the parent page happens to be page 1 of the database
49918     ** image.  */
49919     assert( nNew==1 );
49920     assert( apNew[0]->nFree == 
49921         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
49922     );
49923     copyNodeContent(apNew[0], pParent, &rc);
49924     freePage(apNew[0], &rc);
49925   }else if( ISAUTOVACUUM ){
49926     /* Fix the pointer-map entries for all the cells that were shifted around. 
49927     ** There are several different types of pointer-map entries that need to
49928     ** be dealt with by this routine. Some of these have been set already, but
49929     ** many have not. The following is a summary:
49930     **
49931     **   1) The entries associated with new sibling pages that were not
49932     **      siblings when this function was called. These have already
49933     **      been set. We don't need to worry about old siblings that were
49934     **      moved to the free-list - the freePage() code has taken care
49935     **      of those.
49936     **
49937     **   2) The pointer-map entries associated with the first overflow
49938     **      page in any overflow chains used by new divider cells. These 
49939     **      have also already been taken care of by the insertCell() code.
49940     **
49941     **   3) If the sibling pages are not leaves, then the child pages of
49942     **      cells stored on the sibling pages may need to be updated.
49943     **
49944     **   4) If the sibling pages are not internal intkey nodes, then any
49945     **      overflow pages used by these cells may need to be updated
49946     **      (internal intkey nodes never contain pointers to overflow pages).
49947     **
49948     **   5) If the sibling pages are not leaves, then the pointer-map
49949     **      entries for the right-child pages of each sibling may need
49950     **      to be updated.
49951     **
49952     ** Cases 1 and 2 are dealt with above by other code. The next
49953     ** block deals with cases 3 and 4 and the one after that, case 5. Since
49954     ** setting a pointer map entry is a relatively expensive operation, this
49955     ** code only sets pointer map entries for child or overflow pages that have
49956     ** actually moved between pages.  */
49957     MemPage *pNew = apNew[0];
49958     MemPage *pOld = apCopy[0];
49959     int nOverflow = pOld->nOverflow;
49960     int iNextOld = pOld->nCell + nOverflow;
49961     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
49962     j = 0;                             /* Current 'old' sibling page */
49963     k = 0;                             /* Current 'new' sibling page */
49964     for(i=0; i<nCell; i++){
49965       int isDivider = 0;
49966       while( i==iNextOld ){
49967         /* Cell i is the cell immediately following the last cell on old
49968         ** sibling page j. If the siblings are not leaf pages of an
49969         ** intkey b-tree, then cell i was a divider cell. */
49970         pOld = apCopy[++j];
49971         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
49972         if( pOld->nOverflow ){
49973           nOverflow = pOld->nOverflow;
49974           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
49975         }
49976         isDivider = !leafData;  
49977       }
49978
49979       assert(nOverflow>0 || iOverflow<i );
49980       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
49981       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
49982       if( i==iOverflow ){
49983         isDivider = 1;
49984         if( (--nOverflow)>0 ){
49985           iOverflow++;
49986         }
49987       }
49988
49989       if( i==cntNew[k] ){
49990         /* Cell i is the cell immediately following the last cell on new
49991         ** sibling page k. If the siblings are not leaf pages of an
49992         ** intkey b-tree, then cell i is a divider cell.  */
49993         pNew = apNew[++k];
49994         if( !leafData ) continue;
49995       }
49996       assert( j<nOld );
49997       assert( k<nNew );
49998
49999       /* If the cell was originally divider cell (and is not now) or
50000       ** an overflow cell, or if the cell was located on a different sibling
50001       ** page before the balancing, then the pointer map entries associated
50002       ** with any child or overflow pages need to be updated.  */
50003       if( isDivider || pOld->pgno!=pNew->pgno ){
50004         if( !leafCorrection ){
50005           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
50006         }
50007         if( szCell[i]>pNew->minLocal ){
50008           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
50009         }
50010       }
50011     }
50012
50013     if( !leafCorrection ){
50014       for(i=0; i<nNew; i++){
50015         u32 key = get4byte(&apNew[i]->aData[8]);
50016         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
50017       }
50018     }
50019
50020 #if 0
50021     /* The ptrmapCheckPages() contains assert() statements that verify that
50022     ** all pointer map pages are set correctly. This is helpful while 
50023     ** debugging. This is usually disabled because a corrupt database may
50024     ** cause an assert() statement to fail.  */
50025     ptrmapCheckPages(apNew, nNew);
50026     ptrmapCheckPages(&pParent, 1);
50027 #endif
50028   }
50029
50030   assert( pParent->isInit );
50031   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
50032           nOld, nNew, nCell));
50033
50034   /*
50035   ** Cleanup before returning.
50036   */
50037 balance_cleanup:
50038   sqlite3ScratchFree(apCell);
50039   for(i=0; i<nOld; i++){
50040     releasePage(apOld[i]);
50041   }
50042   for(i=0; i<nNew; i++){
50043     releasePage(apNew[i]);
50044   }
50045
50046   return rc;
50047 }
50048
50049
50050 /*
50051 ** This function is called when the root page of a b-tree structure is
50052 ** overfull (has one or more overflow pages).
50053 **
50054 ** A new child page is allocated and the contents of the current root
50055 ** page, including overflow cells, are copied into the child. The root
50056 ** page is then overwritten to make it an empty page with the right-child 
50057 ** pointer pointing to the new page.
50058 **
50059 ** Before returning, all pointer-map entries corresponding to pages 
50060 ** that the new child-page now contains pointers to are updated. The
50061 ** entry corresponding to the new right-child pointer of the root
50062 ** page is also updated.
50063 **
50064 ** If successful, *ppChild is set to contain a reference to the child 
50065 ** page and SQLITE_OK is returned. In this case the caller is required
50066 ** to call releasePage() on *ppChild exactly once. If an error occurs,
50067 ** an error code is returned and *ppChild is set to 0.
50068 */
50069 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
50070   int rc;                        /* Return value from subprocedures */
50071   MemPage *pChild = 0;           /* Pointer to a new child page */
50072   Pgno pgnoChild = 0;            /* Page number of the new child page */
50073   BtShared *pBt = pRoot->pBt;    /* The BTree */
50074
50075   assert( pRoot->nOverflow>0 );
50076   assert( sqlite3_mutex_held(pBt->mutex) );
50077
50078   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
50079   ** page that will become the new right-child of pPage. Copy the contents
50080   ** of the node stored on pRoot into the new child page.
50081   */
50082   rc = sqlite3PagerWrite(pRoot->pDbPage);
50083   if( rc==SQLITE_OK ){
50084     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
50085     copyNodeContent(pRoot, pChild, &rc);
50086     if( ISAUTOVACUUM ){
50087       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
50088     }
50089   }
50090   if( rc ){
50091     *ppChild = 0;
50092     releasePage(pChild);
50093     return rc;
50094   }
50095   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
50096   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50097   assert( pChild->nCell==pRoot->nCell );
50098
50099   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
50100
50101   /* Copy the overflow cells from pRoot to pChild */
50102   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
50103   pChild->nOverflow = pRoot->nOverflow;
50104
50105   /* Zero the contents of pRoot. Then install pChild as the right-child. */
50106   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
50107   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
50108
50109   *ppChild = pChild;
50110   return SQLITE_OK;
50111 }
50112
50113 /*
50114 ** The page that pCur currently points to has just been modified in
50115 ** some way. This function figures out if this modification means the
50116 ** tree needs to be balanced, and if so calls the appropriate balancing 
50117 ** routine. Balancing routines are:
50118 **
50119 **   balance_quick()
50120 **   balance_deeper()
50121 **   balance_nonroot()
50122 */
50123 static int balance(BtCursor *pCur){
50124   int rc = SQLITE_OK;
50125   const int nMin = pCur->pBt->usableSize * 2 / 3;
50126   u8 aBalanceQuickSpace[13];
50127   u8 *pFree = 0;
50128
50129   TESTONLY( int balance_quick_called = 0 );
50130   TESTONLY( int balance_deeper_called = 0 );
50131
50132   do {
50133     int iPage = pCur->iPage;
50134     MemPage *pPage = pCur->apPage[iPage];
50135
50136     if( iPage==0 ){
50137       if( pPage->nOverflow ){
50138         /* The root page of the b-tree is overfull. In this case call the
50139         ** balance_deeper() function to create a new child for the root-page
50140         ** and copy the current contents of the root-page to it. The
50141         ** next iteration of the do-loop will balance the child page.
50142         */ 
50143         assert( (balance_deeper_called++)==0 );
50144         rc = balance_deeper(pPage, &pCur->apPage[1]);
50145         if( rc==SQLITE_OK ){
50146           pCur->iPage = 1;
50147           pCur->aiIdx[0] = 0;
50148           pCur->aiIdx[1] = 0;
50149           assert( pCur->apPage[1]->nOverflow );
50150         }
50151       }else{
50152         break;
50153       }
50154     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
50155       break;
50156     }else{
50157       MemPage * const pParent = pCur->apPage[iPage-1];
50158       int const iIdx = pCur->aiIdx[iPage-1];
50159
50160       rc = sqlite3PagerWrite(pParent->pDbPage);
50161       if( rc==SQLITE_OK ){
50162 #ifndef SQLITE_OMIT_QUICKBALANCE
50163         if( pPage->hasData
50164          && pPage->nOverflow==1
50165          && pPage->aOvfl[0].idx==pPage->nCell
50166          && pParent->pgno!=1
50167          && pParent->nCell==iIdx
50168         ){
50169           /* Call balance_quick() to create a new sibling of pPage on which
50170           ** to store the overflow cell. balance_quick() inserts a new cell
50171           ** into pParent, which may cause pParent overflow. If this
50172           ** happens, the next interation of the do-loop will balance pParent 
50173           ** use either balance_nonroot() or balance_deeper(). Until this
50174           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
50175           ** buffer. 
50176           **
50177           ** The purpose of the following assert() is to check that only a
50178           ** single call to balance_quick() is made for each call to this
50179           ** function. If this were not verified, a subtle bug involving reuse
50180           ** of the aBalanceQuickSpace[] might sneak in.
50181           */
50182           assert( (balance_quick_called++)==0 );
50183           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
50184         }else
50185 #endif
50186         {
50187           /* In this case, call balance_nonroot() to redistribute cells
50188           ** between pPage and up to 2 of its sibling pages. This involves
50189           ** modifying the contents of pParent, which may cause pParent to
50190           ** become overfull or underfull. The next iteration of the do-loop
50191           ** will balance the parent page to correct this.
50192           ** 
50193           ** If the parent page becomes overfull, the overflow cell or cells
50194           ** are stored in the pSpace buffer allocated immediately below. 
50195           ** A subsequent iteration of the do-loop will deal with this by
50196           ** calling balance_nonroot() (balance_deeper() may be called first,
50197           ** but it doesn't deal with overflow cells - just moves them to a
50198           ** different page). Once this subsequent call to balance_nonroot() 
50199           ** has completed, it is safe to release the pSpace buffer used by
50200           ** the previous call, as the overflow cell data will have been 
50201           ** copied either into the body of a database page or into the new
50202           ** pSpace buffer passed to the latter call to balance_nonroot().
50203           */
50204           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
50205           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
50206           if( pFree ){
50207             /* If pFree is not NULL, it points to the pSpace buffer used 
50208             ** by a previous call to balance_nonroot(). Its contents are
50209             ** now stored either on real database pages or within the 
50210             ** new pSpace buffer, so it may be safely freed here. */
50211             sqlite3PageFree(pFree);
50212           }
50213
50214           /* The pSpace buffer will be freed after the next call to
50215           ** balance_nonroot(), or just before this function returns, whichever
50216           ** comes first. */
50217           pFree = pSpace;
50218         }
50219       }
50220
50221       pPage->nOverflow = 0;
50222
50223       /* The next iteration of the do-loop balances the parent page. */
50224       releasePage(pPage);
50225       pCur->iPage--;
50226     }
50227   }while( rc==SQLITE_OK );
50228
50229   if( pFree ){
50230     sqlite3PageFree(pFree);
50231   }
50232   return rc;
50233 }
50234
50235
50236 /*
50237 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
50238 ** and the data is given by (pData,nData).  The cursor is used only to
50239 ** define what table the record should be inserted into.  The cursor
50240 ** is left pointing at a random location.
50241 **
50242 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
50243 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
50244 **
50245 ** If the seekResult parameter is non-zero, then a successful call to
50246 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
50247 ** been performed. seekResult is the search result returned (a negative
50248 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
50249 ** a positive value if pCur points at an etry that is larger than 
50250 ** (pKey, nKey)). 
50251 **
50252 ** If the seekResult parameter is non-zero, then the caller guarantees that
50253 ** cursor pCur is pointing at the existing copy of a row that is to be
50254 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
50255 ** point to any entry or to no entry at all and so this function has to seek
50256 ** the cursor before the new key can be inserted.
50257 */
50258 SQLITE_PRIVATE int sqlite3BtreeInsert(
50259   BtCursor *pCur,                /* Insert data into the table of this cursor */
50260   const void *pKey, i64 nKey,    /* The key of the new record */
50261   const void *pData, int nData,  /* The data of the new record */
50262   int nZero,                     /* Number of extra 0 bytes to append to data */
50263   int appendBias,                /* True if this is likely an append */
50264   int seekResult                 /* Result of prior MovetoUnpacked() call */
50265 ){
50266   int rc;
50267   int loc = seekResult;          /* -1: before desired location  +1: after */
50268   int szNew = 0;
50269   int idx;
50270   MemPage *pPage;
50271   Btree *p = pCur->pBtree;
50272   BtShared *pBt = p->pBt;
50273   unsigned char *oldCell;
50274   unsigned char *newCell = 0;
50275
50276   if( pCur->eState==CURSOR_FAULT ){
50277     assert( pCur->skipNext!=SQLITE_OK );
50278     return pCur->skipNext;
50279   }
50280
50281   assert( cursorHoldsMutex(pCur) );
50282   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
50283   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
50284
50285   /* Assert that the caller has been consistent. If this cursor was opened
50286   ** expecting an index b-tree, then the caller should be inserting blob
50287   ** keys with no associated data. If the cursor was opened expecting an
50288   ** intkey table, the caller should be inserting integer keys with a
50289   ** blob of associated data.  */
50290   assert( (pKey==0)==(pCur->pKeyInfo==0) );
50291
50292   /* If this is an insert into a table b-tree, invalidate any incrblob 
50293   ** cursors open on the row being replaced (assuming this is a replace
50294   ** operation - if it is not, the following is a no-op).  */
50295   if( pCur->pKeyInfo==0 ){
50296     invalidateIncrblobCursors(p, nKey, 0);
50297   }
50298
50299   /* Save the positions of any other cursors open on this table.
50300   **
50301   ** In some cases, the call to btreeMoveto() below is a no-op. For
50302   ** example, when inserting data into a table with auto-generated integer
50303   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
50304   ** integer key to use. It then calls this function to actually insert the 
50305   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
50306   ** that the cursor is already where it needs to be and returns without
50307   ** doing any work. To avoid thwarting these optimizations, it is important
50308   ** not to clear the cursor here.
50309   */
50310   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
50311   if( rc ) return rc;
50312   if( !loc ){
50313     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
50314     if( rc ) return rc;
50315   }
50316   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
50317
50318   pPage = pCur->apPage[pCur->iPage];
50319   assert( pPage->intKey || nKey>=0 );
50320   assert( pPage->leaf || !pPage->intKey );
50321
50322   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
50323           pCur->pgnoRoot, nKey, nData, pPage->pgno,
50324           loc==0 ? "overwrite" : "new entry"));
50325   assert( pPage->isInit );
50326   allocateTempSpace(pBt);
50327   newCell = pBt->pTmpSpace;
50328   if( newCell==0 ) return SQLITE_NOMEM;
50329   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
50330   if( rc ) goto end_insert;
50331   assert( szNew==cellSizePtr(pPage, newCell) );
50332   assert( szNew<=MX_CELL_SIZE(pBt) );
50333   idx = pCur->aiIdx[pCur->iPage];
50334   if( loc==0 ){
50335     u16 szOld;
50336     assert( idx<pPage->nCell );
50337     rc = sqlite3PagerWrite(pPage->pDbPage);
50338     if( rc ){
50339       goto end_insert;
50340     }
50341     oldCell = findCell(pPage, idx);
50342     if( !pPage->leaf ){
50343       memcpy(newCell, oldCell, 4);
50344     }
50345     szOld = cellSizePtr(pPage, oldCell);
50346     rc = clearCell(pPage, oldCell);
50347     dropCell(pPage, idx, szOld, &rc);
50348     if( rc ) goto end_insert;
50349   }else if( loc<0 && pPage->nCell>0 ){
50350     assert( pPage->leaf );
50351     idx = ++pCur->aiIdx[pCur->iPage];
50352   }else{
50353     assert( pPage->leaf );
50354   }
50355   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
50356   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
50357
50358   /* If no error has occured and pPage has an overflow cell, call balance() 
50359   ** to redistribute the cells within the tree. Since balance() may move
50360   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
50361   ** variables.
50362   **
50363   ** Previous versions of SQLite called moveToRoot() to move the cursor
50364   ** back to the root page as balance() used to invalidate the contents
50365   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
50366   ** set the cursor state to "invalid". This makes common insert operations
50367   ** slightly faster.
50368   **
50369   ** There is a subtle but important optimization here too. When inserting
50370   ** multiple records into an intkey b-tree using a single cursor (as can
50371   ** happen while processing an "INSERT INTO ... SELECT" statement), it
50372   ** is advantageous to leave the cursor pointing to the last entry in
50373   ** the b-tree if possible. If the cursor is left pointing to the last
50374   ** entry in the table, and the next row inserted has an integer key
50375   ** larger than the largest existing key, it is possible to insert the
50376   ** row without seeking the cursor. This can be a big performance boost.
50377   */
50378   pCur->info.nSize = 0;
50379   pCur->validNKey = 0;
50380   if( rc==SQLITE_OK && pPage->nOverflow ){
50381     rc = balance(pCur);
50382
50383     /* Must make sure nOverflow is reset to zero even if the balance()
50384     ** fails. Internal data structure corruption will result otherwise. 
50385     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
50386     ** from trying to save the current position of the cursor.  */
50387     pCur->apPage[pCur->iPage]->nOverflow = 0;
50388     pCur->eState = CURSOR_INVALID;
50389   }
50390   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
50391
50392 end_insert:
50393   return rc;
50394 }
50395
50396 /*
50397 ** Delete the entry that the cursor is pointing to.  The cursor
50398 ** is left pointing at a arbitrary location.
50399 */
50400 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
50401   Btree *p = pCur->pBtree;
50402   BtShared *pBt = p->pBt;              
50403   int rc;                              /* Return code */
50404   MemPage *pPage;                      /* Page to delete cell from */
50405   unsigned char *pCell;                /* Pointer to cell to delete */
50406   int iCellIdx;                        /* Index of cell to delete */
50407   int iCellDepth;                      /* Depth of node containing pCell */ 
50408
50409   assert( cursorHoldsMutex(pCur) );
50410   assert( pBt->inTransaction==TRANS_WRITE );
50411   assert( !pBt->readOnly );
50412   assert( pCur->wrFlag );
50413   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
50414   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
50415
50416   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
50417    || NEVER(pCur->eState!=CURSOR_VALID)
50418   ){
50419     return SQLITE_ERROR;  /* Something has gone awry. */
50420   }
50421
50422   /* If this is a delete operation to remove a row from a table b-tree,
50423   ** invalidate any incrblob cursors open on the row being deleted.  */
50424   if( pCur->pKeyInfo==0 ){
50425     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
50426   }
50427
50428   iCellDepth = pCur->iPage;
50429   iCellIdx = pCur->aiIdx[iCellDepth];
50430   pPage = pCur->apPage[iCellDepth];
50431   pCell = findCell(pPage, iCellIdx);
50432
50433   /* If the page containing the entry to delete is not a leaf page, move
50434   ** the cursor to the largest entry in the tree that is smaller than
50435   ** the entry being deleted. This cell will replace the cell being deleted
50436   ** from the internal node. The 'previous' entry is used for this instead
50437   ** of the 'next' entry, as the previous entry is always a part of the
50438   ** sub-tree headed by the child page of the cell being deleted. This makes
50439   ** balancing the tree following the delete operation easier.  */
50440   if( !pPage->leaf ){
50441     int notUsed;
50442     rc = sqlite3BtreePrevious(pCur, &notUsed);
50443     if( rc ) return rc;
50444   }
50445
50446   /* Save the positions of any other cursors open on this table before
50447   ** making any modifications. Make the page containing the entry to be 
50448   ** deleted writable. Then free any overflow pages associated with the 
50449   ** entry and finally remove the cell itself from within the page.  
50450   */
50451   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
50452   if( rc ) return rc;
50453   rc = sqlite3PagerWrite(pPage->pDbPage);
50454   if( rc ) return rc;
50455   rc = clearCell(pPage, pCell);
50456   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
50457   if( rc ) return rc;
50458
50459   /* If the cell deleted was not located on a leaf page, then the cursor
50460   ** is currently pointing to the largest entry in the sub-tree headed
50461   ** by the child-page of the cell that was just deleted from an internal
50462   ** node. The cell from the leaf node needs to be moved to the internal
50463   ** node to replace the deleted cell.  */
50464   if( !pPage->leaf ){
50465     MemPage *pLeaf = pCur->apPage[pCur->iPage];
50466     int nCell;
50467     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
50468     unsigned char *pTmp;
50469
50470     pCell = findCell(pLeaf, pLeaf->nCell-1);
50471     nCell = cellSizePtr(pLeaf, pCell);
50472     assert( MX_CELL_SIZE(pBt)>=nCell );
50473
50474     allocateTempSpace(pBt);
50475     pTmp = pBt->pTmpSpace;
50476
50477     rc = sqlite3PagerWrite(pLeaf->pDbPage);
50478     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
50479     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
50480     if( rc ) return rc;
50481   }
50482
50483   /* Balance the tree. If the entry deleted was located on a leaf page,
50484   ** then the cursor still points to that page. In this case the first
50485   ** call to balance() repairs the tree, and the if(...) condition is
50486   ** never true.
50487   **
50488   ** Otherwise, if the entry deleted was on an internal node page, then
50489   ** pCur is pointing to the leaf page from which a cell was removed to
50490   ** replace the cell deleted from the internal node. This is slightly
50491   ** tricky as the leaf node may be underfull, and the internal node may
50492   ** be either under or overfull. In this case run the balancing algorithm
50493   ** on the leaf node first. If the balance proceeds far enough up the
50494   ** tree that we can be sure that any problem in the internal node has
50495   ** been corrected, so be it. Otherwise, after balancing the leaf node,
50496   ** walk the cursor up the tree to the internal node and balance it as 
50497   ** well.  */
50498   rc = balance(pCur);
50499   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
50500     while( pCur->iPage>iCellDepth ){
50501       releasePage(pCur->apPage[pCur->iPage--]);
50502     }
50503     rc = balance(pCur);
50504   }
50505
50506   if( rc==SQLITE_OK ){
50507     moveToRoot(pCur);
50508   }
50509   return rc;
50510 }
50511
50512 /*
50513 ** Create a new BTree table.  Write into *piTable the page
50514 ** number for the root page of the new table.
50515 **
50516 ** The type of type is determined by the flags parameter.  Only the
50517 ** following values of flags are currently in use.  Other values for
50518 ** flags might not work:
50519 **
50520 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
50521 **     BTREE_ZERODATA                  Used for SQL indices
50522 */
50523 static int btreeCreateTable(Btree *p, int *piTable, int flags){
50524   BtShared *pBt = p->pBt;
50525   MemPage *pRoot;
50526   Pgno pgnoRoot;
50527   int rc;
50528
50529   assert( sqlite3BtreeHoldsMutex(p) );
50530   assert( pBt->inTransaction==TRANS_WRITE );
50531   assert( !pBt->readOnly );
50532
50533 #ifdef SQLITE_OMIT_AUTOVACUUM
50534   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50535   if( rc ){
50536     return rc;
50537   }
50538 #else
50539   if( pBt->autoVacuum ){
50540     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
50541     MemPage *pPageMove; /* The page to move to. */
50542
50543     /* Creating a new table may probably require moving an existing database
50544     ** to make room for the new tables root page. In case this page turns
50545     ** out to be an overflow page, delete all overflow page-map caches
50546     ** held by open cursors.
50547     */
50548     invalidateAllOverflowCache(pBt);
50549
50550     /* Read the value of meta[3] from the database to determine where the
50551     ** root page of the new table should go. meta[3] is the largest root-page
50552     ** created so far, so the new root-page is (meta[3]+1).
50553     */
50554     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
50555     pgnoRoot++;
50556
50557     /* The new root-page may not be allocated on a pointer-map page, or the
50558     ** PENDING_BYTE page.
50559     */
50560     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
50561         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
50562       pgnoRoot++;
50563     }
50564     assert( pgnoRoot>=3 );
50565
50566     /* Allocate a page. The page that currently resides at pgnoRoot will
50567     ** be moved to the allocated page (unless the allocated page happens
50568     ** to reside at pgnoRoot).
50569     */
50570     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
50571     if( rc!=SQLITE_OK ){
50572       return rc;
50573     }
50574
50575     if( pgnoMove!=pgnoRoot ){
50576       /* pgnoRoot is the page that will be used for the root-page of
50577       ** the new table (assuming an error did not occur). But we were
50578       ** allocated pgnoMove. If required (i.e. if it was not allocated
50579       ** by extending the file), the current page at position pgnoMove
50580       ** is already journaled.
50581       */
50582       u8 eType = 0;
50583       Pgno iPtrPage = 0;
50584
50585       releasePage(pPageMove);
50586
50587       /* Move the page currently at pgnoRoot to pgnoMove. */
50588       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50589       if( rc!=SQLITE_OK ){
50590         return rc;
50591       }
50592       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
50593       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
50594         rc = SQLITE_CORRUPT_BKPT;
50595       }
50596       if( rc!=SQLITE_OK ){
50597         releasePage(pRoot);
50598         return rc;
50599       }
50600       assert( eType!=PTRMAP_ROOTPAGE );
50601       assert( eType!=PTRMAP_FREEPAGE );
50602       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
50603       releasePage(pRoot);
50604
50605       /* Obtain the page at pgnoRoot */
50606       if( rc!=SQLITE_OK ){
50607         return rc;
50608       }
50609       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50610       if( rc!=SQLITE_OK ){
50611         return rc;
50612       }
50613       rc = sqlite3PagerWrite(pRoot->pDbPage);
50614       if( rc!=SQLITE_OK ){
50615         releasePage(pRoot);
50616         return rc;
50617       }
50618     }else{
50619       pRoot = pPageMove;
50620     } 
50621
50622     /* Update the pointer-map and meta-data with the new root-page number. */
50623     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
50624     if( rc ){
50625       releasePage(pRoot);
50626       return rc;
50627     }
50628
50629     /* When the new root page was allocated, page 1 was made writable in
50630     ** order either to increase the database filesize, or to decrement the
50631     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
50632     */
50633     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
50634     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
50635     if( NEVER(rc) ){
50636       releasePage(pRoot);
50637       return rc;
50638     }
50639
50640   }else{
50641     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50642     if( rc ) return rc;
50643   }
50644 #endif
50645   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50646   zeroPage(pRoot, flags | PTF_LEAF);
50647   sqlite3PagerUnref(pRoot->pDbPage);
50648   *piTable = (int)pgnoRoot;
50649   return SQLITE_OK;
50650 }
50651 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
50652   int rc;
50653   sqlite3BtreeEnter(p);
50654   rc = btreeCreateTable(p, piTable, flags);
50655   sqlite3BtreeLeave(p);
50656   return rc;
50657 }
50658
50659 /*
50660 ** Erase the given database page and all its children.  Return
50661 ** the page to the freelist.
50662 */
50663 static int clearDatabasePage(
50664   BtShared *pBt,           /* The BTree that contains the table */
50665   Pgno pgno,               /* Page number to clear */
50666   int freePageFlag,        /* Deallocate page if true */
50667   int *pnChange            /* Add number of Cells freed to this counter */
50668 ){
50669   MemPage *pPage;
50670   int rc;
50671   unsigned char *pCell;
50672   int i;
50673
50674   assert( sqlite3_mutex_held(pBt->mutex) );
50675   if( pgno>btreePagecount(pBt) ){
50676     return SQLITE_CORRUPT_BKPT;
50677   }
50678
50679   rc = getAndInitPage(pBt, pgno, &pPage);
50680   if( rc ) return rc;
50681   for(i=0; i<pPage->nCell; i++){
50682     pCell = findCell(pPage, i);
50683     if( !pPage->leaf ){
50684       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
50685       if( rc ) goto cleardatabasepage_out;
50686     }
50687     rc = clearCell(pPage, pCell);
50688     if( rc ) goto cleardatabasepage_out;
50689   }
50690   if( !pPage->leaf ){
50691     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
50692     if( rc ) goto cleardatabasepage_out;
50693   }else if( pnChange ){
50694     assert( pPage->intKey );
50695     *pnChange += pPage->nCell;
50696   }
50697   if( freePageFlag ){
50698     freePage(pPage, &rc);
50699   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
50700     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
50701   }
50702
50703 cleardatabasepage_out:
50704   releasePage(pPage);
50705   return rc;
50706 }
50707
50708 /*
50709 ** Delete all information from a single table in the database.  iTable is
50710 ** the page number of the root of the table.  After this routine returns,
50711 ** the root page is empty, but still exists.
50712 **
50713 ** This routine will fail with SQLITE_LOCKED if there are any open
50714 ** read cursors on the table.  Open write cursors are moved to the
50715 ** root of the table.
50716 **
50717 ** If pnChange is not NULL, then table iTable must be an intkey table. The
50718 ** integer value pointed to by pnChange is incremented by the number of
50719 ** entries in the table.
50720 */
50721 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
50722   int rc;
50723   BtShared *pBt = p->pBt;
50724   sqlite3BtreeEnter(p);
50725   assert( p->inTrans==TRANS_WRITE );
50726
50727   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
50728   ** is the root of a table b-tree - if it is not, the following call is
50729   ** a no-op).  */
50730   invalidateIncrblobCursors(p, 0, 1);
50731
50732   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
50733   if( SQLITE_OK==rc ){
50734     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
50735   }
50736   sqlite3BtreeLeave(p);
50737   return rc;
50738 }
50739
50740 /*
50741 ** Erase all information in a table and add the root of the table to
50742 ** the freelist.  Except, the root of the principle table (the one on
50743 ** page 1) is never added to the freelist.
50744 **
50745 ** This routine will fail with SQLITE_LOCKED if there are any open
50746 ** cursors on the table.
50747 **
50748 ** If AUTOVACUUM is enabled and the page at iTable is not the last
50749 ** root page in the database file, then the last root page 
50750 ** in the database file is moved into the slot formerly occupied by
50751 ** iTable and that last slot formerly occupied by the last root page
50752 ** is added to the freelist instead of iTable.  In this say, all
50753 ** root pages are kept at the beginning of the database file, which
50754 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
50755 ** page number that used to be the last root page in the file before
50756 ** the move.  If no page gets moved, *piMoved is set to 0.
50757 ** The last root page is recorded in meta[3] and the value of
50758 ** meta[3] is updated by this procedure.
50759 */
50760 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
50761   int rc;
50762   MemPage *pPage = 0;
50763   BtShared *pBt = p->pBt;
50764
50765   assert( sqlite3BtreeHoldsMutex(p) );
50766   assert( p->inTrans==TRANS_WRITE );
50767
50768   /* It is illegal to drop a table if any cursors are open on the
50769   ** database. This is because in auto-vacuum mode the backend may
50770   ** need to move another root-page to fill a gap left by the deleted
50771   ** root page. If an open cursor was using this page a problem would 
50772   ** occur.
50773   **
50774   ** This error is caught long before control reaches this point.
50775   */
50776   if( NEVER(pBt->pCursor) ){
50777     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
50778     return SQLITE_LOCKED_SHAREDCACHE;
50779   }
50780
50781   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
50782   if( rc ) return rc;
50783   rc = sqlite3BtreeClearTable(p, iTable, 0);
50784   if( rc ){
50785     releasePage(pPage);
50786     return rc;
50787   }
50788
50789   *piMoved = 0;
50790
50791   if( iTable>1 ){
50792 #ifdef SQLITE_OMIT_AUTOVACUUM
50793     freePage(pPage, &rc);
50794     releasePage(pPage);
50795 #else
50796     if( pBt->autoVacuum ){
50797       Pgno maxRootPgno;
50798       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
50799
50800       if( iTable==maxRootPgno ){
50801         /* If the table being dropped is the table with the largest root-page
50802         ** number in the database, put the root page on the free list. 
50803         */
50804         freePage(pPage, &rc);
50805         releasePage(pPage);
50806         if( rc!=SQLITE_OK ){
50807           return rc;
50808         }
50809       }else{
50810         /* The table being dropped does not have the largest root-page
50811         ** number in the database. So move the page that does into the 
50812         ** gap left by the deleted root-page.
50813         */
50814         MemPage *pMove;
50815         releasePage(pPage);
50816         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50817         if( rc!=SQLITE_OK ){
50818           return rc;
50819         }
50820         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
50821         releasePage(pMove);
50822         if( rc!=SQLITE_OK ){
50823           return rc;
50824         }
50825         pMove = 0;
50826         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50827         freePage(pMove, &rc);
50828         releasePage(pMove);
50829         if( rc!=SQLITE_OK ){
50830           return rc;
50831         }
50832         *piMoved = maxRootPgno;
50833       }
50834
50835       /* Set the new 'max-root-page' value in the database header. This
50836       ** is the old value less one, less one more if that happens to
50837       ** be a root-page number, less one again if that is the
50838       ** PENDING_BYTE_PAGE.
50839       */
50840       maxRootPgno--;
50841       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
50842              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
50843         maxRootPgno--;
50844       }
50845       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
50846
50847       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
50848     }else{
50849       freePage(pPage, &rc);
50850       releasePage(pPage);
50851     }
50852 #endif
50853   }else{
50854     /* If sqlite3BtreeDropTable was called on page 1.
50855     ** This really never should happen except in a corrupt
50856     ** database. 
50857     */
50858     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
50859     releasePage(pPage);
50860   }
50861   return rc;  
50862 }
50863 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
50864   int rc;
50865   sqlite3BtreeEnter(p);
50866   rc = btreeDropTable(p, iTable, piMoved);
50867   sqlite3BtreeLeave(p);
50868   return rc;
50869 }
50870
50871
50872 /*
50873 ** This function may only be called if the b-tree connection already
50874 ** has a read or write transaction open on the database.
50875 **
50876 ** Read the meta-information out of a database file.  Meta[0]
50877 ** is the number of free pages currently in the database.  Meta[1]
50878 ** through meta[15] are available for use by higher layers.  Meta[0]
50879 ** is read-only, the others are read/write.
50880 ** 
50881 ** The schema layer numbers meta values differently.  At the schema
50882 ** layer (and the SetCookie and ReadCookie opcodes) the number of
50883 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
50884 */
50885 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
50886   BtShared *pBt = p->pBt;
50887
50888   sqlite3BtreeEnter(p);
50889   assert( p->inTrans>TRANS_NONE );
50890   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
50891   assert( pBt->pPage1 );
50892   assert( idx>=0 && idx<=15 );
50893
50894   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
50895
50896   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
50897   ** database, mark the database as read-only.  */
50898 #ifdef SQLITE_OMIT_AUTOVACUUM
50899   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
50900 #endif
50901
50902   sqlite3BtreeLeave(p);
50903 }
50904
50905 /*
50906 ** Write meta-information back into the database.  Meta[0] is
50907 ** read-only and may not be written.
50908 */
50909 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
50910   BtShared *pBt = p->pBt;
50911   unsigned char *pP1;
50912   int rc;
50913   assert( idx>=1 && idx<=15 );
50914   sqlite3BtreeEnter(p);
50915   assert( p->inTrans==TRANS_WRITE );
50916   assert( pBt->pPage1!=0 );
50917   pP1 = pBt->pPage1->aData;
50918   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50919   if( rc==SQLITE_OK ){
50920     put4byte(&pP1[36 + idx*4], iMeta);
50921 #ifndef SQLITE_OMIT_AUTOVACUUM
50922     if( idx==BTREE_INCR_VACUUM ){
50923       assert( pBt->autoVacuum || iMeta==0 );
50924       assert( iMeta==0 || iMeta==1 );
50925       pBt->incrVacuum = (u8)iMeta;
50926     }
50927 #endif
50928   }
50929   sqlite3BtreeLeave(p);
50930   return rc;
50931 }
50932
50933 #ifndef SQLITE_OMIT_BTREECOUNT
50934 /*
50935 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
50936 ** number of entries in the b-tree and write the result to *pnEntry.
50937 **
50938 ** SQLITE_OK is returned if the operation is successfully executed. 
50939 ** Otherwise, if an error is encountered (i.e. an IO error or database
50940 ** corruption) an SQLite error code is returned.
50941 */
50942 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
50943   i64 nEntry = 0;                      /* Value to return in *pnEntry */
50944   int rc;                              /* Return code */
50945   rc = moveToRoot(pCur);
50946
50947   /* Unless an error occurs, the following loop runs one iteration for each
50948   ** page in the B-Tree structure (not including overflow pages). 
50949   */
50950   while( rc==SQLITE_OK ){
50951     int iIdx;                          /* Index of child node in parent */
50952     MemPage *pPage;                    /* Current page of the b-tree */
50953
50954     /* If this is a leaf page or the tree is not an int-key tree, then 
50955     ** this page contains countable entries. Increment the entry counter
50956     ** accordingly.
50957     */
50958     pPage = pCur->apPage[pCur->iPage];
50959     if( pPage->leaf || !pPage->intKey ){
50960       nEntry += pPage->nCell;
50961     }
50962
50963     /* pPage is a leaf node. This loop navigates the cursor so that it 
50964     ** points to the first interior cell that it points to the parent of
50965     ** the next page in the tree that has not yet been visited. The
50966     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
50967     ** of the page, or to the number of cells in the page if the next page
50968     ** to visit is the right-child of its parent.
50969     **
50970     ** If all pages in the tree have been visited, return SQLITE_OK to the
50971     ** caller.
50972     */
50973     if( pPage->leaf ){
50974       do {
50975         if( pCur->iPage==0 ){
50976           /* All pages of the b-tree have been visited. Return successfully. */
50977           *pnEntry = nEntry;
50978           return SQLITE_OK;
50979         }
50980         moveToParent(pCur);
50981       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
50982
50983       pCur->aiIdx[pCur->iPage]++;
50984       pPage = pCur->apPage[pCur->iPage];
50985     }
50986
50987     /* Descend to the child node of the cell that the cursor currently 
50988     ** points at. This is the right-child if (iIdx==pPage->nCell).
50989     */
50990     iIdx = pCur->aiIdx[pCur->iPage];
50991     if( iIdx==pPage->nCell ){
50992       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
50993     }else{
50994       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
50995     }
50996   }
50997
50998   /* An error has occurred. Return an error code. */
50999   return rc;
51000 }
51001 #endif
51002
51003 /*
51004 ** Return the pager associated with a BTree.  This routine is used for
51005 ** testing and debugging only.
51006 */
51007 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
51008   return p->pBt->pPager;
51009 }
51010
51011 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51012 /*
51013 ** Append a message to the error message string.
51014 */
51015 static void checkAppendMsg(
51016   IntegrityCk *pCheck,
51017   char *zMsg1,
51018   const char *zFormat,
51019   ...
51020 ){
51021   va_list ap;
51022   if( !pCheck->mxErr ) return;
51023   pCheck->mxErr--;
51024   pCheck->nErr++;
51025   va_start(ap, zFormat);
51026   if( pCheck->errMsg.nChar ){
51027     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
51028   }
51029   if( zMsg1 ){
51030     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
51031   }
51032   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
51033   va_end(ap);
51034   if( pCheck->errMsg.mallocFailed ){
51035     pCheck->mallocFailed = 1;
51036   }
51037 }
51038 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51039
51040 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51041 /*
51042 ** Add 1 to the reference count for page iPage.  If this is the second
51043 ** reference to the page, add an error message to pCheck->zErrMsg.
51044 ** Return 1 if there are 2 ore more references to the page and 0 if
51045 ** if this is the first reference to the page.
51046 **
51047 ** Also check that the page number is in bounds.
51048 */
51049 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
51050   if( iPage==0 ) return 1;
51051   if( iPage>pCheck->nPage ){
51052     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
51053     return 1;
51054   }
51055   if( pCheck->anRef[iPage]==1 ){
51056     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
51057     return 1;
51058   }
51059   return  (pCheck->anRef[iPage]++)>1;
51060 }
51061
51062 #ifndef SQLITE_OMIT_AUTOVACUUM
51063 /*
51064 ** Check that the entry in the pointer-map for page iChild maps to 
51065 ** page iParent, pointer type ptrType. If not, append an error message
51066 ** to pCheck.
51067 */
51068 static void checkPtrmap(
51069   IntegrityCk *pCheck,   /* Integrity check context */
51070   Pgno iChild,           /* Child page number */
51071   u8 eType,              /* Expected pointer map type */
51072   Pgno iParent,          /* Expected pointer map parent page number */
51073   char *zContext         /* Context description (used for error msg) */
51074 ){
51075   int rc;
51076   u8 ePtrmapType;
51077   Pgno iPtrmapParent;
51078
51079   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
51080   if( rc!=SQLITE_OK ){
51081     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
51082     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
51083     return;
51084   }
51085
51086   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
51087     checkAppendMsg(pCheck, zContext, 
51088       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
51089       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
51090   }
51091 }
51092 #endif
51093
51094 /*
51095 ** Check the integrity of the freelist or of an overflow page list.
51096 ** Verify that the number of pages on the list is N.
51097 */
51098 static void checkList(
51099   IntegrityCk *pCheck,  /* Integrity checking context */
51100   int isFreeList,       /* True for a freelist.  False for overflow page list */
51101   int iPage,            /* Page number for first page in the list */
51102   int N,                /* Expected number of pages in the list */
51103   char *zContext        /* Context for error messages */
51104 ){
51105   int i;
51106   int expected = N;
51107   int iFirst = iPage;
51108   while( N-- > 0 && pCheck->mxErr ){
51109     DbPage *pOvflPage;
51110     unsigned char *pOvflData;
51111     if( iPage<1 ){
51112       checkAppendMsg(pCheck, zContext,
51113          "%d of %d pages missing from overflow list starting at %d",
51114           N+1, expected, iFirst);
51115       break;
51116     }
51117     if( checkRef(pCheck, iPage, zContext) ) break;
51118     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
51119       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
51120       break;
51121     }
51122     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
51123     if( isFreeList ){
51124       int n = get4byte(&pOvflData[4]);
51125 #ifndef SQLITE_OMIT_AUTOVACUUM
51126       if( pCheck->pBt->autoVacuum ){
51127         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
51128       }
51129 #endif
51130       if( n>pCheck->pBt->usableSize/4-2 ){
51131         checkAppendMsg(pCheck, zContext,
51132            "freelist leaf count too big on page %d", iPage);
51133         N--;
51134       }else{
51135         for(i=0; i<n; i++){
51136           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
51137 #ifndef SQLITE_OMIT_AUTOVACUUM
51138           if( pCheck->pBt->autoVacuum ){
51139             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
51140           }
51141 #endif
51142           checkRef(pCheck, iFreePage, zContext);
51143         }
51144         N -= n;
51145       }
51146     }
51147 #ifndef SQLITE_OMIT_AUTOVACUUM
51148     else{
51149       /* If this database supports auto-vacuum and iPage is not the last
51150       ** page in this overflow list, check that the pointer-map entry for
51151       ** the following page matches iPage.
51152       */
51153       if( pCheck->pBt->autoVacuum && N>0 ){
51154         i = get4byte(pOvflData);
51155         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
51156       }
51157     }
51158 #endif
51159     iPage = get4byte(pOvflData);
51160     sqlite3PagerUnref(pOvflPage);
51161   }
51162 }
51163 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51164
51165 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51166 /*
51167 ** Do various sanity checks on a single page of a tree.  Return
51168 ** the tree depth.  Root pages return 0.  Parents of root pages
51169 ** return 1, and so forth.
51170 ** 
51171 ** These checks are done:
51172 **
51173 **      1.  Make sure that cells and freeblocks do not overlap
51174 **          but combine to completely cover the page.
51175 **  NO  2.  Make sure cell keys are in order.
51176 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
51177 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
51178 **      5.  Check the integrity of overflow pages.
51179 **      6.  Recursively call checkTreePage on all children.
51180 **      7.  Verify that the depth of all children is the same.
51181 **      8.  Make sure this page is at least 33% full or else it is
51182 **          the root of the tree.
51183 */
51184 static int checkTreePage(
51185   IntegrityCk *pCheck,  /* Context for the sanity check */
51186   int iPage,            /* Page number of the page to check */
51187   char *zParentContext, /* Parent context */
51188   i64 *pnParentMinKey, 
51189   i64 *pnParentMaxKey
51190 ){
51191   MemPage *pPage;
51192   int i, rc, depth, d2, pgno, cnt;
51193   int hdr, cellStart;
51194   int nCell;
51195   u8 *data;
51196   BtShared *pBt;
51197   int usableSize;
51198   char zContext[100];
51199   char *hit = 0;
51200   i64 nMinKey = 0;
51201   i64 nMaxKey = 0;
51202
51203   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
51204
51205   /* Check that the page exists
51206   */
51207   pBt = pCheck->pBt;
51208   usableSize = pBt->usableSize;
51209   if( iPage==0 ) return 0;
51210   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
51211   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
51212     checkAppendMsg(pCheck, zContext,
51213        "unable to get the page. error code=%d", rc);
51214     return 0;
51215   }
51216
51217   /* Clear MemPage.isInit to make sure the corruption detection code in
51218   ** btreeInitPage() is executed.  */
51219   pPage->isInit = 0;
51220   if( (rc = btreeInitPage(pPage))!=0 ){
51221     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
51222     checkAppendMsg(pCheck, zContext, 
51223                    "btreeInitPage() returns error code %d", rc);
51224     releasePage(pPage);
51225     return 0;
51226   }
51227
51228   /* Check out all the cells.
51229   */
51230   depth = 0;
51231   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
51232     u8 *pCell;
51233     u32 sz;
51234     CellInfo info;
51235
51236     /* Check payload overflow pages
51237     */
51238     sqlite3_snprintf(sizeof(zContext), zContext,
51239              "On tree page %d cell %d: ", iPage, i);
51240     pCell = findCell(pPage,i);
51241     btreeParseCellPtr(pPage, pCell, &info);
51242     sz = info.nData;
51243     if( !pPage->intKey ) sz += (int)info.nKey;
51244     /* For intKey pages, check that the keys are in order.
51245     */
51246     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
51247     else{
51248       if( info.nKey <= nMaxKey ){
51249         checkAppendMsg(pCheck, zContext, 
51250             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
51251       }
51252       nMaxKey = info.nKey;
51253     }
51254     assert( sz==info.nPayload );
51255     if( (sz>info.nLocal) 
51256      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
51257     ){
51258       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
51259       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
51260 #ifndef SQLITE_OMIT_AUTOVACUUM
51261       if( pBt->autoVacuum ){
51262         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
51263       }
51264 #endif
51265       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
51266     }
51267
51268     /* Check sanity of left child page.
51269     */
51270     if( !pPage->leaf ){
51271       pgno = get4byte(pCell);
51272 #ifndef SQLITE_OMIT_AUTOVACUUM
51273       if( pBt->autoVacuum ){
51274         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
51275       }
51276 #endif
51277       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
51278       if( i>0 && d2!=depth ){
51279         checkAppendMsg(pCheck, zContext, "Child page depth differs");
51280       }
51281       depth = d2;
51282     }
51283   }
51284
51285   if( !pPage->leaf ){
51286     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51287     sqlite3_snprintf(sizeof(zContext), zContext, 
51288                      "On page %d at right child: ", iPage);
51289 #ifndef SQLITE_OMIT_AUTOVACUUM
51290     if( pBt->autoVacuum ){
51291       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
51292     }
51293 #endif
51294     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
51295   }
51296  
51297   /* For intKey leaf pages, check that the min/max keys are in order
51298   ** with any left/parent/right pages.
51299   */
51300   if( pPage->leaf && pPage->intKey ){
51301     /* if we are a left child page */
51302     if( pnParentMinKey ){
51303       /* if we are the left most child page */
51304       if( !pnParentMaxKey ){
51305         if( nMaxKey > *pnParentMinKey ){
51306           checkAppendMsg(pCheck, zContext, 
51307               "Rowid %lld out of order (max larger than parent min of %lld)",
51308               nMaxKey, *pnParentMinKey);
51309         }
51310       }else{
51311         if( nMinKey <= *pnParentMinKey ){
51312           checkAppendMsg(pCheck, zContext, 
51313               "Rowid %lld out of order (min less than parent min of %lld)",
51314               nMinKey, *pnParentMinKey);
51315         }
51316         if( nMaxKey > *pnParentMaxKey ){
51317           checkAppendMsg(pCheck, zContext, 
51318               "Rowid %lld out of order (max larger than parent max of %lld)",
51319               nMaxKey, *pnParentMaxKey);
51320         }
51321         *pnParentMinKey = nMaxKey;
51322       }
51323     /* else if we're a right child page */
51324     } else if( pnParentMaxKey ){
51325       if( nMinKey <= *pnParentMaxKey ){
51326         checkAppendMsg(pCheck, zContext, 
51327             "Rowid %lld out of order (min less than parent max of %lld)",
51328             nMinKey, *pnParentMaxKey);
51329       }
51330     }
51331   }
51332
51333   /* Check for complete coverage of the page
51334   */
51335   data = pPage->aData;
51336   hdr = pPage->hdrOffset;
51337   hit = sqlite3PageMalloc( pBt->pageSize );
51338   if( hit==0 ){
51339     pCheck->mallocFailed = 1;
51340   }else{
51341     u16 contentOffset = get2byte(&data[hdr+5]);
51342     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
51343     memset(hit+contentOffset, 0, usableSize-contentOffset);
51344     memset(hit, 1, contentOffset);
51345     nCell = get2byte(&data[hdr+3]);
51346     cellStart = hdr + 12 - 4*pPage->leaf;
51347     for(i=0; i<nCell; i++){
51348       int pc = get2byte(&data[cellStart+i*2]);
51349       u16 size = 1024;
51350       int j;
51351       if( pc<=usableSize-4 ){
51352         size = cellSizePtr(pPage, &data[pc]);
51353       }
51354       if( (pc+size-1)>=usableSize ){
51355         checkAppendMsg(pCheck, 0, 
51356             "Corruption detected in cell %d on page %d",i,iPage);
51357       }else{
51358         for(j=pc+size-1; j>=pc; j--) hit[j]++;
51359       }
51360     }
51361     i = get2byte(&data[hdr+1]);
51362     while( i>0 ){
51363       int size, j;
51364       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
51365       size = get2byte(&data[i+2]);
51366       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
51367       for(j=i+size-1; j>=i; j--) hit[j]++;
51368       j = get2byte(&data[i]);
51369       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
51370       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
51371       i = j;
51372     }
51373     for(i=cnt=0; i<usableSize; i++){
51374       if( hit[i]==0 ){
51375         cnt++;
51376       }else if( hit[i]>1 ){
51377         checkAppendMsg(pCheck, 0,
51378           "Multiple uses for byte %d of page %d", i, iPage);
51379         break;
51380       }
51381     }
51382     if( cnt!=data[hdr+7] ){
51383       checkAppendMsg(pCheck, 0, 
51384           "Fragmentation of %d bytes reported as %d on page %d",
51385           cnt, data[hdr+7], iPage);
51386     }
51387   }
51388   sqlite3PageFree(hit);
51389   releasePage(pPage);
51390   return depth+1;
51391 }
51392 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51393
51394 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51395 /*
51396 ** This routine does a complete check of the given BTree file.  aRoot[] is
51397 ** an array of pages numbers were each page number is the root page of
51398 ** a table.  nRoot is the number of entries in aRoot.
51399 **
51400 ** A read-only or read-write transaction must be opened before calling
51401 ** this function.
51402 **
51403 ** Write the number of error seen in *pnErr.  Except for some memory
51404 ** allocation errors,  an error message held in memory obtained from
51405 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
51406 ** returned.  If a memory allocation error occurs, NULL is returned.
51407 */
51408 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
51409   Btree *p,     /* The btree to be checked */
51410   int *aRoot,   /* An array of root pages numbers for individual trees */
51411   int nRoot,    /* Number of entries in aRoot[] */
51412   int mxErr,    /* Stop reporting errors after this many */
51413   int *pnErr    /* Write number of errors seen to this variable */
51414 ){
51415   Pgno i;
51416   int nRef;
51417   IntegrityCk sCheck;
51418   BtShared *pBt = p->pBt;
51419   char zErr[100];
51420
51421   sqlite3BtreeEnter(p);
51422   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
51423   nRef = sqlite3PagerRefcount(pBt->pPager);
51424   sCheck.pBt = pBt;
51425   sCheck.pPager = pBt->pPager;
51426   sCheck.nPage = btreePagecount(sCheck.pBt);
51427   sCheck.mxErr = mxErr;
51428   sCheck.nErr = 0;
51429   sCheck.mallocFailed = 0;
51430   *pnErr = 0;
51431   if( sCheck.nPage==0 ){
51432     sqlite3BtreeLeave(p);
51433     return 0;
51434   }
51435   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
51436   if( !sCheck.anRef ){
51437     *pnErr = 1;
51438     sqlite3BtreeLeave(p);
51439     return 0;
51440   }
51441   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
51442   i = PENDING_BYTE_PAGE(pBt);
51443   if( i<=sCheck.nPage ){
51444     sCheck.anRef[i] = 1;
51445   }
51446   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
51447
51448   /* Check the integrity of the freelist
51449   */
51450   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
51451             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
51452
51453   /* Check all the tables.
51454   */
51455   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
51456     if( aRoot[i]==0 ) continue;
51457 #ifndef SQLITE_OMIT_AUTOVACUUM
51458     if( pBt->autoVacuum && aRoot[i]>1 ){
51459       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
51460     }
51461 #endif
51462     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
51463   }
51464
51465   /* Make sure every page in the file is referenced
51466   */
51467   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
51468 #ifdef SQLITE_OMIT_AUTOVACUUM
51469     if( sCheck.anRef[i]==0 ){
51470       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51471     }
51472 #else
51473     /* If the database supports auto-vacuum, make sure no tables contain
51474     ** references to pointer-map pages.
51475     */
51476     if( sCheck.anRef[i]==0 && 
51477        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
51478       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51479     }
51480     if( sCheck.anRef[i]!=0 && 
51481        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
51482       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
51483     }
51484 #endif
51485   }
51486
51487   /* Make sure this analysis did not leave any unref() pages.
51488   ** This is an internal consistency check; an integrity check
51489   ** of the integrity check.
51490   */
51491   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
51492     checkAppendMsg(&sCheck, 0, 
51493       "Outstanding page count goes from %d to %d during this analysis",
51494       nRef, sqlite3PagerRefcount(pBt->pPager)
51495     );
51496   }
51497
51498   /* Clean  up and report errors.
51499   */
51500   sqlite3BtreeLeave(p);
51501   sqlite3_free(sCheck.anRef);
51502   if( sCheck.mallocFailed ){
51503     sqlite3StrAccumReset(&sCheck.errMsg);
51504     *pnErr = sCheck.nErr+1;
51505     return 0;
51506   }
51507   *pnErr = sCheck.nErr;
51508   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
51509   return sqlite3StrAccumFinish(&sCheck.errMsg);
51510 }
51511 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51512
51513 /*
51514 ** Return the full pathname of the underlying database file.
51515 **
51516 ** The pager filename is invariant as long as the pager is
51517 ** open so it is safe to access without the BtShared mutex.
51518 */
51519 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
51520   assert( p->pBt->pPager!=0 );
51521   return sqlite3PagerFilename(p->pBt->pPager);
51522 }
51523
51524 /*
51525 ** Return the pathname of the journal file for this database. The return
51526 ** value of this routine is the same regardless of whether the journal file
51527 ** has been created or not.
51528 **
51529 ** The pager journal filename is invariant as long as the pager is
51530 ** open so it is safe to access without the BtShared mutex.
51531 */
51532 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
51533   assert( p->pBt->pPager!=0 );
51534   return sqlite3PagerJournalname(p->pBt->pPager);
51535 }
51536
51537 /*
51538 ** Return non-zero if a transaction is active.
51539 */
51540 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
51541   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
51542   return (p && (p->inTrans==TRANS_WRITE));
51543 }
51544
51545 /*
51546 ** Return non-zero if a read (or write) transaction is active.
51547 */
51548 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
51549   assert( p );
51550   assert( sqlite3_mutex_held(p->db->mutex) );
51551   return p->inTrans!=TRANS_NONE;
51552 }
51553
51554 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
51555   assert( p );
51556   assert( sqlite3_mutex_held(p->db->mutex) );
51557   return p->nBackup!=0;
51558 }
51559
51560 /*
51561 ** This function returns a pointer to a blob of memory associated with
51562 ** a single shared-btree. The memory is used by client code for its own
51563 ** purposes (for example, to store a high-level schema associated with 
51564 ** the shared-btree). The btree layer manages reference counting issues.
51565 **
51566 ** The first time this is called on a shared-btree, nBytes bytes of memory
51567 ** are allocated, zeroed, and returned to the caller. For each subsequent 
51568 ** call the nBytes parameter is ignored and a pointer to the same blob
51569 ** of memory returned. 
51570 **
51571 ** If the nBytes parameter is 0 and the blob of memory has not yet been
51572 ** allocated, a null pointer is returned. If the blob has already been
51573 ** allocated, it is returned as normal.
51574 **
51575 ** Just before the shared-btree is closed, the function passed as the 
51576 ** xFree argument when the memory allocation was made is invoked on the 
51577 ** blob of allocated memory. This function should not call sqlite3_free()
51578 ** on the memory, the btree layer does that.
51579 */
51580 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
51581   BtShared *pBt = p->pBt;
51582   sqlite3BtreeEnter(p);
51583   if( !pBt->pSchema && nBytes ){
51584     pBt->pSchema = sqlite3MallocZero(nBytes);
51585     pBt->xFreeSchema = xFree;
51586   }
51587   sqlite3BtreeLeave(p);
51588   return pBt->pSchema;
51589 }
51590
51591 /*
51592 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
51593 ** btree as the argument handle holds an exclusive lock on the 
51594 ** sqlite_master table. Otherwise SQLITE_OK.
51595 */
51596 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
51597   int rc;
51598   assert( sqlite3_mutex_held(p->db->mutex) );
51599   sqlite3BtreeEnter(p);
51600   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51601   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
51602   sqlite3BtreeLeave(p);
51603   return rc;
51604 }
51605
51606
51607 #ifndef SQLITE_OMIT_SHARED_CACHE
51608 /*
51609 ** Obtain a lock on the table whose root page is iTab.  The
51610 ** lock is a write lock if isWritelock is true or a read lock
51611 ** if it is false.
51612 */
51613 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
51614   int rc = SQLITE_OK;
51615   assert( p->inTrans!=TRANS_NONE );
51616   if( p->sharable ){
51617     u8 lockType = READ_LOCK + isWriteLock;
51618     assert( READ_LOCK+1==WRITE_LOCK );
51619     assert( isWriteLock==0 || isWriteLock==1 );
51620
51621     sqlite3BtreeEnter(p);
51622     rc = querySharedCacheTableLock(p, iTab, lockType);
51623     if( rc==SQLITE_OK ){
51624       rc = setSharedCacheTableLock(p, iTab, lockType);
51625     }
51626     sqlite3BtreeLeave(p);
51627   }
51628   return rc;
51629 }
51630 #endif
51631
51632 #ifndef SQLITE_OMIT_INCRBLOB
51633 /*
51634 ** Argument pCsr must be a cursor opened for writing on an 
51635 ** INTKEY table currently pointing at a valid table entry. 
51636 ** This function modifies the data stored as part of that entry.
51637 **
51638 ** Only the data content may only be modified, it is not possible to 
51639 ** change the length of the data stored. If this function is called with
51640 ** parameters that attempt to write past the end of the existing data,
51641 ** no modifications are made and SQLITE_CORRUPT is returned.
51642 */
51643 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
51644   int rc;
51645   assert( cursorHoldsMutex(pCsr) );
51646   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
51647   assert( pCsr->isIncrblobHandle );
51648
51649   rc = restoreCursorPosition(pCsr);
51650   if( rc!=SQLITE_OK ){
51651     return rc;
51652   }
51653   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
51654   if( pCsr->eState!=CURSOR_VALID ){
51655     return SQLITE_ABORT;
51656   }
51657
51658   /* Check some assumptions: 
51659   **   (a) the cursor is open for writing,
51660   **   (b) there is a read/write transaction open,
51661   **   (c) the connection holds a write-lock on the table (if required),
51662   **   (d) there are no conflicting read-locks, and
51663   **   (e) the cursor points at a valid row of an intKey table.
51664   */
51665   if( !pCsr->wrFlag ){
51666     return SQLITE_READONLY;
51667   }
51668   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
51669   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
51670   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
51671   assert( pCsr->apPage[pCsr->iPage]->intKey );
51672
51673   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
51674 }
51675
51676 /* 
51677 ** Set a flag on this cursor to cache the locations of pages from the 
51678 ** overflow list for the current row. This is used by cursors opened
51679 ** for incremental blob IO only.
51680 **
51681 ** This function sets a flag only. The actual page location cache
51682 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
51683 ** accessPayload() (the worker function for sqlite3BtreeData() and
51684 ** sqlite3BtreePutData()).
51685 */
51686 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
51687   assert( cursorHoldsMutex(pCur) );
51688   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51689   assert(!pCur->isIncrblobHandle);
51690   assert(!pCur->aOverflow);
51691   pCur->isIncrblobHandle = 1;
51692 }
51693 #endif
51694
51695 /*
51696 ** Set both the "read version" (single byte at byte offset 18) and 
51697 ** "write version" (single byte at byte offset 19) fields in the database
51698 ** header to iVersion.
51699 */
51700 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
51701   BtShared *pBt = pBtree->pBt;
51702   int rc;                         /* Return code */
51703  
51704   assert( pBtree->inTrans==TRANS_NONE );
51705   assert( iVersion==1 || iVersion==2 );
51706
51707   /* If setting the version fields to 1, do not automatically open the
51708   ** WAL connection, even if the version fields are currently set to 2.
51709   */
51710   pBt->doNotUseWAL = (u8)(iVersion==1);
51711
51712   rc = sqlite3BtreeBeginTrans(pBtree, 0);
51713   if( rc==SQLITE_OK ){
51714     u8 *aData = pBt->pPage1->aData;
51715     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
51716       rc = sqlite3BtreeBeginTrans(pBtree, 2);
51717       if( rc==SQLITE_OK ){
51718         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51719         if( rc==SQLITE_OK ){
51720           aData[18] = (u8)iVersion;
51721           aData[19] = (u8)iVersion;
51722         }
51723       }
51724     }
51725   }
51726
51727   pBt->doNotUseWAL = 0;
51728   return rc;
51729 }
51730
51731 /************** End of btree.c ***********************************************/
51732 /************** Begin file backup.c ******************************************/
51733 /*
51734 ** 2009 January 28
51735 **
51736 ** The author disclaims copyright to this source code.  In place of
51737 ** a legal notice, here is a blessing:
51738 **
51739 **    May you do good and not evil.
51740 **    May you find forgiveness for yourself and forgive others.
51741 **    May you share freely, never taking more than you give.
51742 **
51743 *************************************************************************
51744 ** This file contains the implementation of the sqlite3_backup_XXX() 
51745 ** API functions and the related features.
51746 */
51747
51748 /* Macro to find the minimum of two numeric values.
51749 */
51750 #ifndef MIN
51751 # define MIN(x,y) ((x)<(y)?(x):(y))
51752 #endif
51753
51754 /*
51755 ** Structure allocated for each backup operation.
51756 */
51757 struct sqlite3_backup {
51758   sqlite3* pDestDb;        /* Destination database handle */
51759   Btree *pDest;            /* Destination b-tree file */
51760   u32 iDestSchema;         /* Original schema cookie in destination */
51761   int bDestLocked;         /* True once a write-transaction is open on pDest */
51762
51763   Pgno iNext;              /* Page number of the next source page to copy */
51764   sqlite3* pSrcDb;         /* Source database handle */
51765   Btree *pSrc;             /* Source b-tree file */
51766
51767   int rc;                  /* Backup process error code */
51768
51769   /* These two variables are set by every call to backup_step(). They are
51770   ** read by calls to backup_remaining() and backup_pagecount().
51771   */
51772   Pgno nRemaining;         /* Number of pages left to copy */
51773   Pgno nPagecount;         /* Total number of pages to copy */
51774
51775   int isAttached;          /* True once backup has been registered with pager */
51776   sqlite3_backup *pNext;   /* Next backup associated with source pager */
51777 };
51778
51779 /*
51780 ** THREAD SAFETY NOTES:
51781 **
51782 **   Once it has been created using backup_init(), a single sqlite3_backup
51783 **   structure may be accessed via two groups of thread-safe entry points:
51784 **
51785 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
51786 **       backup_finish(). Both these functions obtain the source database
51787 **       handle mutex and the mutex associated with the source BtShared 
51788 **       structure, in that order.
51789 **
51790 **     * Via the BackupUpdate() and BackupRestart() functions, which are
51791 **       invoked by the pager layer to report various state changes in
51792 **       the page cache associated with the source database. The mutex
51793 **       associated with the source database BtShared structure will always 
51794 **       be held when either of these functions are invoked.
51795 **
51796 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
51797 **   backup_pagecount() are not thread-safe functions. If they are called
51798 **   while some other thread is calling backup_step() or backup_finish(),
51799 **   the values returned may be invalid. There is no way for a call to
51800 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
51801 **   or backup_pagecount().
51802 **
51803 **   Depending on the SQLite configuration, the database handles and/or
51804 **   the Btree objects may have their own mutexes that require locking.
51805 **   Non-sharable Btrees (in-memory databases for example), do not have
51806 **   associated mutexes.
51807 */
51808
51809 /*
51810 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
51811 ** in connection handle pDb. If such a database cannot be found, return
51812 ** a NULL pointer and write an error message to pErrorDb.
51813 **
51814 ** If the "temp" database is requested, it may need to be opened by this 
51815 ** function. If an error occurs while doing so, return 0 and write an 
51816 ** error message to pErrorDb.
51817 */
51818 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
51819   int i = sqlite3FindDbName(pDb, zDb);
51820
51821   if( i==1 ){
51822     Parse *pParse;
51823     int rc = 0;
51824     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
51825     if( pParse==0 ){
51826       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
51827       rc = SQLITE_NOMEM;
51828     }else{
51829       pParse->db = pDb;
51830       if( sqlite3OpenTempDatabase(pParse) ){
51831         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
51832         rc = SQLITE_ERROR;
51833       }
51834       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
51835       sqlite3StackFree(pErrorDb, pParse);
51836     }
51837     if( rc ){
51838       return 0;
51839     }
51840   }
51841
51842   if( i<0 ){
51843     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
51844     return 0;
51845   }
51846
51847   return pDb->aDb[i].pBt;
51848 }
51849
51850 /*
51851 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
51852 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
51853 ** a pointer to the new sqlite3_backup object.
51854 **
51855 ** If an error occurs, NULL is returned and an error code and error message
51856 ** stored in database handle pDestDb.
51857 */
51858 SQLITE_API sqlite3_backup *sqlite3_backup_init(
51859   sqlite3* pDestDb,                     /* Database to write to */
51860   const char *zDestDb,                  /* Name of database within pDestDb */
51861   sqlite3* pSrcDb,                      /* Database connection to read from */
51862   const char *zSrcDb                    /* Name of database within pSrcDb */
51863 ){
51864   sqlite3_backup *p;                    /* Value to return */
51865
51866   /* Lock the source database handle. The destination database
51867   ** handle is not locked in this routine, but it is locked in
51868   ** sqlite3_backup_step(). The user is required to ensure that no
51869   ** other thread accesses the destination handle for the duration
51870   ** of the backup operation.  Any attempt to use the destination
51871   ** database connection while a backup is in progress may cause
51872   ** a malfunction or a deadlock.
51873   */
51874   sqlite3_mutex_enter(pSrcDb->mutex);
51875   sqlite3_mutex_enter(pDestDb->mutex);
51876
51877   if( pSrcDb==pDestDb ){
51878     sqlite3Error(
51879         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
51880     );
51881     p = 0;
51882   }else {
51883     /* Allocate space for a new sqlite3_backup object */
51884     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
51885     if( !p ){
51886       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
51887     }
51888   }
51889
51890   /* If the allocation succeeded, populate the new object. */
51891   if( p ){
51892     memset(p, 0, sizeof(sqlite3_backup));
51893     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
51894     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
51895     p->pDestDb = pDestDb;
51896     p->pSrcDb = pSrcDb;
51897     p->iNext = 1;
51898     p->isAttached = 0;
51899
51900     if( 0==p->pSrc || 0==p->pDest ){
51901       /* One (or both) of the named databases did not exist. An error has
51902       ** already been written into the pDestDb handle. All that is left
51903       ** to do here is free the sqlite3_backup structure.
51904       */
51905       sqlite3_free(p);
51906       p = 0;
51907     }
51908   }
51909   if( p ){
51910     p->pSrc->nBackup++;
51911   }
51912
51913   sqlite3_mutex_leave(pDestDb->mutex);
51914   sqlite3_mutex_leave(pSrcDb->mutex);
51915   return p;
51916 }
51917
51918 /*
51919 ** Argument rc is an SQLite error code. Return true if this error is 
51920 ** considered fatal if encountered during a backup operation. All errors
51921 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
51922 */
51923 static int isFatalError(int rc){
51924   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
51925 }
51926
51927 /*
51928 ** Parameter zSrcData points to a buffer containing the data for 
51929 ** page iSrcPg from the source database. Copy this data into the 
51930 ** destination database.
51931 */
51932 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
51933   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
51934   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
51935   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
51936   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
51937   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
51938
51939   int rc = SQLITE_OK;
51940   i64 iOff;
51941
51942   assert( p->bDestLocked );
51943   assert( !isFatalError(p->rc) );
51944   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
51945   assert( zSrcData );
51946
51947   /* Catch the case where the destination is an in-memory database and the
51948   ** page sizes of the source and destination differ. 
51949   */
51950   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
51951     rc = SQLITE_READONLY;
51952   }
51953
51954   /* This loop runs once for each destination page spanned by the source 
51955   ** page. For each iteration, variable iOff is set to the byte offset
51956   ** of the destination page.
51957   */
51958   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
51959     DbPage *pDestPg = 0;
51960     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
51961     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
51962     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
51963      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
51964     ){
51965       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
51966       u8 *zDestData = sqlite3PagerGetData(pDestPg);
51967       u8 *zOut = &zDestData[iOff%nDestPgsz];
51968
51969       /* Copy the data from the source page into the destination page.
51970       ** Then clear the Btree layer MemPage.isInit flag. Both this module
51971       ** and the pager code use this trick (clearing the first byte
51972       ** of the page 'extra' space to invalidate the Btree layers
51973       ** cached parse of the page). MemPage.isInit is marked 
51974       ** "MUST BE FIRST" for this purpose.
51975       */
51976       memcpy(zOut, zIn, nCopy);
51977       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
51978     }
51979     sqlite3PagerUnref(pDestPg);
51980   }
51981
51982   return rc;
51983 }
51984
51985 /*
51986 ** If pFile is currently larger than iSize bytes, then truncate it to
51987 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
51988 ** this function is a no-op.
51989 **
51990 ** Return SQLITE_OK if everything is successful, or an SQLite error 
51991 ** code if an error occurs.
51992 */
51993 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
51994   i64 iCurrent;
51995   int rc = sqlite3OsFileSize(pFile, &iCurrent);
51996   if( rc==SQLITE_OK && iCurrent>iSize ){
51997     rc = sqlite3OsTruncate(pFile, iSize);
51998   }
51999   return rc;
52000 }
52001
52002 /*
52003 ** Register this backup object with the associated source pager for
52004 ** callbacks when pages are changed or the cache invalidated.
52005 */
52006 static void attachBackupObject(sqlite3_backup *p){
52007   sqlite3_backup **pp;
52008   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
52009   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
52010   p->pNext = *pp;
52011   *pp = p;
52012   p->isAttached = 1;
52013 }
52014
52015 /*
52016 ** Copy nPage pages from the source b-tree to the destination.
52017 */
52018 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
52019   int rc;
52020   int destMode;       /* Destination journal mode */
52021   int pgszSrc = 0;    /* Source page size */
52022   int pgszDest = 0;   /* Destination page size */
52023
52024   sqlite3_mutex_enter(p->pSrcDb->mutex);
52025   sqlite3BtreeEnter(p->pSrc);
52026   if( p->pDestDb ){
52027     sqlite3_mutex_enter(p->pDestDb->mutex);
52028   }
52029
52030   rc = p->rc;
52031   if( !isFatalError(rc) ){
52032     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
52033     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
52034     int ii;                            /* Iterator variable */
52035     int nSrcPage = -1;                 /* Size of source db in pages */
52036     int bCloseTrans = 0;               /* True if src db requires unlocking */
52037
52038     /* If the source pager is currently in a write-transaction, return
52039     ** SQLITE_BUSY immediately.
52040     */
52041     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
52042       rc = SQLITE_BUSY;
52043     }else{
52044       rc = SQLITE_OK;
52045     }
52046
52047     /* Lock the destination database, if it is not locked already. */
52048     if( SQLITE_OK==rc && p->bDestLocked==0
52049      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
52050     ){
52051       p->bDestLocked = 1;
52052       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
52053     }
52054
52055     /* If there is no open read-transaction on the source database, open
52056     ** one now. If a transaction is opened here, then it will be closed
52057     ** before this function exits.
52058     */
52059     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
52060       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
52061       bCloseTrans = 1;
52062     }
52063
52064     /* Do not allow backup if the destination database is in WAL mode
52065     ** and the page sizes are different between source and destination */
52066     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
52067     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
52068     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
52069     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
52070       rc = SQLITE_READONLY;
52071     }
52072   
52073     /* Now that there is a read-lock on the source database, query the
52074     ** source pager for the number of pages in the database.
52075     */
52076     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
52077     assert( nSrcPage>=0 );
52078     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
52079       const Pgno iSrcPg = p->iNext;                 /* Source page number */
52080       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
52081         DbPage *pSrcPg;                             /* Source page object */
52082         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
52083         if( rc==SQLITE_OK ){
52084           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
52085           sqlite3PagerUnref(pSrcPg);
52086         }
52087       }
52088       p->iNext++;
52089     }
52090     if( rc==SQLITE_OK ){
52091       p->nPagecount = nSrcPage;
52092       p->nRemaining = nSrcPage+1-p->iNext;
52093       if( p->iNext>(Pgno)nSrcPage ){
52094         rc = SQLITE_DONE;
52095       }else if( !p->isAttached ){
52096         attachBackupObject(p);
52097       }
52098     }
52099   
52100     /* Update the schema version field in the destination database. This
52101     ** is to make sure that the schema-version really does change in
52102     ** the case where the source and destination databases have the
52103     ** same schema version.
52104     */
52105     if( rc==SQLITE_DONE 
52106      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
52107     ){
52108       int nDestTruncate;
52109   
52110       if( p->pDestDb ){
52111         sqlite3ResetInternalSchema(p->pDestDb, 0);
52112       }
52113
52114       /* Set nDestTruncate to the final number of pages in the destination
52115       ** database. The complication here is that the destination page
52116       ** size may be different to the source page size. 
52117       **
52118       ** If the source page size is smaller than the destination page size, 
52119       ** round up. In this case the call to sqlite3OsTruncate() below will
52120       ** fix the size of the file. However it is important to call
52121       ** sqlite3PagerTruncateImage() here so that any pages in the 
52122       ** destination file that lie beyond the nDestTruncate page mark are
52123       ** journalled by PagerCommitPhaseOne() before they are destroyed
52124       ** by the file truncation.
52125       */
52126       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
52127       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
52128       if( pgszSrc<pgszDest ){
52129         int ratio = pgszDest/pgszSrc;
52130         nDestTruncate = (nSrcPage+ratio-1)/ratio;
52131         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
52132           nDestTruncate--;
52133         }
52134       }else{
52135         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
52136       }
52137       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
52138
52139       if( pgszSrc<pgszDest ){
52140         /* If the source page-size is smaller than the destination page-size,
52141         ** two extra things may need to happen:
52142         **
52143         **   * The destination may need to be truncated, and
52144         **
52145         **   * Data stored on the pages immediately following the 
52146         **     pending-byte page in the source database may need to be
52147         **     copied into the destination database.
52148         */
52149         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
52150         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
52151
52152         assert( pFile );
52153         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
52154               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
52155            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
52156         ));
52157         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
52158          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
52159          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
52160         ){
52161           i64 iOff;
52162           i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
52163           for(
52164             iOff=PENDING_BYTE+pgszSrc; 
52165             rc==SQLITE_OK && iOff<iEnd; 
52166             iOff+=pgszSrc
52167           ){
52168             PgHdr *pSrcPg = 0;
52169             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
52170             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
52171             if( rc==SQLITE_OK ){
52172               u8 *zData = sqlite3PagerGetData(pSrcPg);
52173               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
52174             }
52175             sqlite3PagerUnref(pSrcPg);
52176           }
52177         }
52178       }else{
52179         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
52180       }
52181   
52182       /* Finish committing the transaction to the destination database. */
52183       if( SQLITE_OK==rc
52184        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
52185       ){
52186         rc = SQLITE_DONE;
52187       }
52188     }
52189   
52190     /* If bCloseTrans is true, then this function opened a read transaction
52191     ** on the source database. Close the read transaction here. There is
52192     ** no need to check the return values of the btree methods here, as
52193     ** "committing" a read-only transaction cannot fail.
52194     */
52195     if( bCloseTrans ){
52196       TESTONLY( int rc2 );
52197       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
52198       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
52199       assert( rc2==SQLITE_OK );
52200     }
52201   
52202     if( rc==SQLITE_IOERR_NOMEM ){
52203       rc = SQLITE_NOMEM;
52204     }
52205     p->rc = rc;
52206   }
52207   if( p->pDestDb ){
52208     sqlite3_mutex_leave(p->pDestDb->mutex);
52209   }
52210   sqlite3BtreeLeave(p->pSrc);
52211   sqlite3_mutex_leave(p->pSrcDb->mutex);
52212   return rc;
52213 }
52214
52215 /*
52216 ** Release all resources associated with an sqlite3_backup* handle.
52217 */
52218 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
52219   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
52220   sqlite3_mutex *mutex;                /* Mutex to protect source database */
52221   int rc;                              /* Value to return */
52222
52223   /* Enter the mutexes */
52224   if( p==0 ) return SQLITE_OK;
52225   sqlite3_mutex_enter(p->pSrcDb->mutex);
52226   sqlite3BtreeEnter(p->pSrc);
52227   mutex = p->pSrcDb->mutex;
52228   if( p->pDestDb ){
52229     sqlite3_mutex_enter(p->pDestDb->mutex);
52230   }
52231
52232   /* Detach this backup from the source pager. */
52233   if( p->pDestDb ){
52234     p->pSrc->nBackup--;
52235   }
52236   if( p->isAttached ){
52237     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
52238     while( *pp!=p ){
52239       pp = &(*pp)->pNext;
52240     }
52241     *pp = p->pNext;
52242   }
52243
52244   /* If a transaction is still open on the Btree, roll it back. */
52245   sqlite3BtreeRollback(p->pDest);
52246
52247   /* Set the error code of the destination database handle. */
52248   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
52249   sqlite3Error(p->pDestDb, rc, 0);
52250
52251   /* Exit the mutexes and free the backup context structure. */
52252   if( p->pDestDb ){
52253     sqlite3_mutex_leave(p->pDestDb->mutex);
52254   }
52255   sqlite3BtreeLeave(p->pSrc);
52256   if( p->pDestDb ){
52257     sqlite3_free(p);
52258   }
52259   sqlite3_mutex_leave(mutex);
52260   return rc;
52261 }
52262
52263 /*
52264 ** Return the number of pages still to be backed up as of the most recent
52265 ** call to sqlite3_backup_step().
52266 */
52267 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
52268   return p->nRemaining;
52269 }
52270
52271 /*
52272 ** Return the total number of pages in the source database as of the most 
52273 ** recent call to sqlite3_backup_step().
52274 */
52275 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
52276   return p->nPagecount;
52277 }
52278
52279 /*
52280 ** This function is called after the contents of page iPage of the
52281 ** source database have been modified. If page iPage has already been 
52282 ** copied into the destination database, then the data written to the
52283 ** destination is now invalidated. The destination copy of iPage needs
52284 ** to be updated with the new data before the backup operation is
52285 ** complete.
52286 **
52287 ** It is assumed that the mutex associated with the BtShared object
52288 ** corresponding to the source database is held when this function is
52289 ** called.
52290 */
52291 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
52292   sqlite3_backup *p;                   /* Iterator variable */
52293   for(p=pBackup; p; p=p->pNext){
52294     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
52295     if( !isFatalError(p->rc) && iPage<p->iNext ){
52296       /* The backup process p has already copied page iPage. But now it
52297       ** has been modified by a transaction on the source pager. Copy
52298       ** the new data into the backup.
52299       */
52300       int rc = backupOnePage(p, iPage, aData);
52301       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
52302       if( rc!=SQLITE_OK ){
52303         p->rc = rc;
52304       }
52305     }
52306   }
52307 }
52308
52309 /*
52310 ** Restart the backup process. This is called when the pager layer
52311 ** detects that the database has been modified by an external database
52312 ** connection. In this case there is no way of knowing which of the
52313 ** pages that have been copied into the destination database are still 
52314 ** valid and which are not, so the entire process needs to be restarted.
52315 **
52316 ** It is assumed that the mutex associated with the BtShared object
52317 ** corresponding to the source database is held when this function is
52318 ** called.
52319 */
52320 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
52321   sqlite3_backup *p;                   /* Iterator variable */
52322   for(p=pBackup; p; p=p->pNext){
52323     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
52324     p->iNext = 1;
52325   }
52326 }
52327
52328 #ifndef SQLITE_OMIT_VACUUM
52329 /*
52330 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
52331 ** must be active for both files.
52332 **
52333 ** The size of file pTo may be reduced by this operation. If anything 
52334 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
52335 ** transaction is committed before returning.
52336 */
52337 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
52338   int rc;
52339   sqlite3_backup b;
52340   sqlite3BtreeEnter(pTo);
52341   sqlite3BtreeEnter(pFrom);
52342
52343   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
52344   ** to 0. This is used by the implementations of sqlite3_backup_step()
52345   ** and sqlite3_backup_finish() to detect that they are being called
52346   ** from this function, not directly by the user.
52347   */
52348   memset(&b, 0, sizeof(b));
52349   b.pSrcDb = pFrom->db;
52350   b.pSrc = pFrom;
52351   b.pDest = pTo;
52352   b.iNext = 1;
52353
52354   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
52355   ** file. By passing this as the number of pages to copy to
52356   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
52357   ** within a single call (unless an error occurs). The assert() statement
52358   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
52359   ** or an error code.
52360   */
52361   sqlite3_backup_step(&b, 0x7FFFFFFF);
52362   assert( b.rc!=SQLITE_OK );
52363   rc = sqlite3_backup_finish(&b);
52364   if( rc==SQLITE_OK ){
52365     pTo->pBt->pageSizeFixed = 0;
52366   }
52367
52368   sqlite3BtreeLeave(pFrom);
52369   sqlite3BtreeLeave(pTo);
52370   return rc;
52371 }
52372 #endif /* SQLITE_OMIT_VACUUM */
52373
52374 /************** End of backup.c **********************************************/
52375 /************** Begin file vdbemem.c *****************************************/
52376 /*
52377 ** 2004 May 26
52378 **
52379 ** The author disclaims copyright to this source code.  In place of
52380 ** a legal notice, here is a blessing:
52381 **
52382 **    May you do good and not evil.
52383 **    May you find forgiveness for yourself and forgive others.
52384 **    May you share freely, never taking more than you give.
52385 **
52386 *************************************************************************
52387 **
52388 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
52389 ** stores a single value in the VDBE.  Mem is an opaque structure visible
52390 ** only within the VDBE.  Interface routines refer to a Mem using the
52391 ** name sqlite_value
52392 */
52393
52394 /*
52395 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52396 ** P if required.
52397 */
52398 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52399
52400 /*
52401 ** If pMem is an object with a valid string representation, this routine
52402 ** ensures the internal encoding for the string representation is
52403 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
52404 **
52405 ** If pMem is not a string object, or the encoding of the string
52406 ** representation is already stored using the requested encoding, then this
52407 ** routine is a no-op.
52408 **
52409 ** SQLITE_OK is returned if the conversion is successful (or not required).
52410 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
52411 ** between formats.
52412 */
52413 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
52414   int rc;
52415   assert( (pMem->flags&MEM_RowSet)==0 );
52416   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
52417            || desiredEnc==SQLITE_UTF16BE );
52418   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
52419     return SQLITE_OK;
52420   }
52421   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52422 #ifdef SQLITE_OMIT_UTF16
52423   return SQLITE_ERROR;
52424 #else
52425
52426   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
52427   ** then the encoding of the value may not have changed.
52428   */
52429   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
52430   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
52431   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
52432   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
52433   return rc;
52434 #endif
52435 }
52436
52437 /*
52438 ** Make sure pMem->z points to a writable allocation of at least 
52439 ** n bytes.
52440 **
52441 ** If the memory cell currently contains string or blob data
52442 ** and the third argument passed to this function is true, the 
52443 ** current content of the cell is preserved. Otherwise, it may
52444 ** be discarded.  
52445 **
52446 ** This function sets the MEM_Dyn flag and clears any xDel callback.
52447 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
52448 ** not set, Mem.n is zeroed.
52449 */
52450 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
52451   assert( 1 >=
52452     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
52453     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
52454     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
52455     ((pMem->flags&MEM_Static) ? 1 : 0)
52456   );
52457   assert( (pMem->flags&MEM_RowSet)==0 );
52458
52459   if( n<32 ) n = 32;
52460   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
52461     if( preserve && pMem->z==pMem->zMalloc ){
52462       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
52463       preserve = 0;
52464     }else{
52465       sqlite3DbFree(pMem->db, pMem->zMalloc);
52466       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
52467     }
52468   }
52469
52470   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
52471     memcpy(pMem->zMalloc, pMem->z, pMem->n);
52472   }
52473   if( pMem->flags&MEM_Dyn && pMem->xDel ){
52474     pMem->xDel((void *)(pMem->z));
52475   }
52476
52477   pMem->z = pMem->zMalloc;
52478   if( pMem->z==0 ){
52479     pMem->flags = MEM_Null;
52480   }else{
52481     pMem->flags &= ~(MEM_Ephem|MEM_Static);
52482   }
52483   pMem->xDel = 0;
52484   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
52485 }
52486
52487 /*
52488 ** Make the given Mem object MEM_Dyn.  In other words, make it so
52489 ** that any TEXT or BLOB content is stored in memory obtained from
52490 ** malloc().  In this way, we know that the memory is safe to be
52491 ** overwritten or altered.
52492 **
52493 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
52494 */
52495 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
52496   int f;
52497   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52498   assert( (pMem->flags&MEM_RowSet)==0 );
52499   expandBlob(pMem);
52500   f = pMem->flags;
52501   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
52502     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
52503       return SQLITE_NOMEM;
52504     }
52505     pMem->z[pMem->n] = 0;
52506     pMem->z[pMem->n+1] = 0;
52507     pMem->flags |= MEM_Term;
52508   }
52509
52510   return SQLITE_OK;
52511 }
52512
52513 /*
52514 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
52515 ** blob stored in dynamically allocated space.
52516 */
52517 #ifndef SQLITE_OMIT_INCRBLOB
52518 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
52519   if( pMem->flags & MEM_Zero ){
52520     int nByte;
52521     assert( pMem->flags&MEM_Blob );
52522     assert( (pMem->flags&MEM_RowSet)==0 );
52523     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52524
52525     /* Set nByte to the number of bytes required to store the expanded blob. */
52526     nByte = pMem->n + pMem->u.nZero;
52527     if( nByte<=0 ){
52528       nByte = 1;
52529     }
52530     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
52531       return SQLITE_NOMEM;
52532     }
52533
52534     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
52535     pMem->n += pMem->u.nZero;
52536     pMem->flags &= ~(MEM_Zero|MEM_Term);
52537   }
52538   return SQLITE_OK;
52539 }
52540 #endif
52541
52542
52543 /*
52544 ** Make sure the given Mem is \u0000 terminated.
52545 */
52546 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
52547   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52548   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
52549     return SQLITE_OK;   /* Nothing to do */
52550   }
52551   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
52552     return SQLITE_NOMEM;
52553   }
52554   pMem->z[pMem->n] = 0;
52555   pMem->z[pMem->n+1] = 0;
52556   pMem->flags |= MEM_Term;
52557   return SQLITE_OK;
52558 }
52559
52560 /*
52561 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
52562 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
52563 ** is a no-op.
52564 **
52565 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
52566 **
52567 ** A MEM_Null value will never be passed to this function. This function is
52568 ** used for converting values to text for returning to the user (i.e. via
52569 ** sqlite3_value_text()), or for ensuring that values to be used as btree
52570 ** keys are strings. In the former case a NULL pointer is returned the
52571 ** user and the later is an internal programming error.
52572 */
52573 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
52574   int rc = SQLITE_OK;
52575   int fg = pMem->flags;
52576   const int nByte = 32;
52577
52578   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52579   assert( !(fg&MEM_Zero) );
52580   assert( !(fg&(MEM_Str|MEM_Blob)) );
52581   assert( fg&(MEM_Int|MEM_Real) );
52582   assert( (pMem->flags&MEM_RowSet)==0 );
52583   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52584
52585
52586   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52587     return SQLITE_NOMEM;
52588   }
52589
52590   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
52591   ** string representation of the value. Then, if the required encoding
52592   ** is UTF-16le or UTF-16be do a translation.
52593   ** 
52594   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
52595   */
52596   if( fg & MEM_Int ){
52597     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
52598   }else{
52599     assert( fg & MEM_Real );
52600     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
52601   }
52602   pMem->n = sqlite3Strlen30(pMem->z);
52603   pMem->enc = SQLITE_UTF8;
52604   pMem->flags |= MEM_Str|MEM_Term;
52605   sqlite3VdbeChangeEncoding(pMem, enc);
52606   return rc;
52607 }
52608
52609 /*
52610 ** Memory cell pMem contains the context of an aggregate function.
52611 ** This routine calls the finalize method for that function.  The
52612 ** result of the aggregate is stored back into pMem.
52613 **
52614 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
52615 ** otherwise.
52616 */
52617 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
52618   int rc = SQLITE_OK;
52619   if( ALWAYS(pFunc && pFunc->xFinalize) ){
52620     sqlite3_context ctx;
52621     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
52622     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52623     memset(&ctx, 0, sizeof(ctx));
52624     ctx.s.flags = MEM_Null;
52625     ctx.s.db = pMem->db;
52626     ctx.pMem = pMem;
52627     ctx.pFunc = pFunc;
52628     pFunc->xFinalize(&ctx);
52629     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
52630     sqlite3DbFree(pMem->db, pMem->zMalloc);
52631     memcpy(pMem, &ctx.s, sizeof(ctx.s));
52632     rc = ctx.isError;
52633   }
52634   return rc;
52635 }
52636
52637 /*
52638 ** If the memory cell contains a string value that must be freed by
52639 ** invoking an external callback, free it now. Calling this function
52640 ** does not free any Mem.zMalloc buffer.
52641 */
52642 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
52643   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
52644   testcase( p->flags & MEM_Agg );
52645   testcase( p->flags & MEM_Dyn );
52646   testcase( p->flags & MEM_RowSet );
52647   testcase( p->flags & MEM_Frame );
52648   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
52649     if( p->flags&MEM_Agg ){
52650       sqlite3VdbeMemFinalize(p, p->u.pDef);
52651       assert( (p->flags & MEM_Agg)==0 );
52652       sqlite3VdbeMemRelease(p);
52653     }else if( p->flags&MEM_Dyn && p->xDel ){
52654       assert( (p->flags&MEM_RowSet)==0 );
52655       p->xDel((void *)p->z);
52656       p->xDel = 0;
52657     }else if( p->flags&MEM_RowSet ){
52658       sqlite3RowSetClear(p->u.pRowSet);
52659     }else if( p->flags&MEM_Frame ){
52660       sqlite3VdbeMemSetNull(p);
52661     }
52662   }
52663 }
52664
52665 /*
52666 ** Release any memory held by the Mem. This may leave the Mem in an
52667 ** inconsistent state, for example with (Mem.z==0) and
52668 ** (Mem.type==SQLITE_TEXT).
52669 */
52670 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
52671   sqlite3VdbeMemReleaseExternal(p);
52672   sqlite3DbFree(p->db, p->zMalloc);
52673   p->z = 0;
52674   p->zMalloc = 0;
52675   p->xDel = 0;
52676 }
52677
52678 /*
52679 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
52680 ** If the double is too large, return 0x8000000000000000.
52681 **
52682 ** Most systems appear to do this simply by assigning
52683 ** variables and without the extra range tests.  But
52684 ** there are reports that windows throws an expection
52685 ** if the floating point value is out of range. (See ticket #2880.)
52686 ** Because we do not completely understand the problem, we will
52687 ** take the conservative approach and always do range tests
52688 ** before attempting the conversion.
52689 */
52690 static i64 doubleToInt64(double r){
52691 #ifdef SQLITE_OMIT_FLOATING_POINT
52692   /* When floating-point is omitted, double and int64 are the same thing */
52693   return r;
52694 #else
52695   /*
52696   ** Many compilers we encounter do not define constants for the
52697   ** minimum and maximum 64-bit integers, or they define them
52698   ** inconsistently.  And many do not understand the "LL" notation.
52699   ** So we define our own static constants here using nothing
52700   ** larger than a 32-bit integer constant.
52701   */
52702   static const i64 maxInt = LARGEST_INT64;
52703   static const i64 minInt = SMALLEST_INT64;
52704
52705   if( r<(double)minInt ){
52706     return minInt;
52707   }else if( r>(double)maxInt ){
52708     /* minInt is correct here - not maxInt.  It turns out that assigning
52709     ** a very large positive number to an integer results in a very large
52710     ** negative integer.  This makes no sense, but it is what x86 hardware
52711     ** does so for compatibility we will do the same in software. */
52712     return minInt;
52713   }else{
52714     return (i64)r;
52715   }
52716 #endif
52717 }
52718
52719 /*
52720 ** Return some kind of integer value which is the best we can do
52721 ** at representing the value that *pMem describes as an integer.
52722 ** If pMem is an integer, then the value is exact.  If pMem is
52723 ** a floating-point then the value returned is the integer part.
52724 ** If pMem is a string or blob, then we make an attempt to convert
52725 ** it into a integer and return that.  If pMem represents an
52726 ** an SQL-NULL value, return 0.
52727 **
52728 ** If pMem represents a string value, its encoding might be changed.
52729 */
52730 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
52731   int flags;
52732   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52733   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52734   flags = pMem->flags;
52735   if( flags & MEM_Int ){
52736     return pMem->u.i;
52737   }else if( flags & MEM_Real ){
52738     return doubleToInt64(pMem->r);
52739   }else if( flags & (MEM_Str|MEM_Blob) ){
52740     i64 value;
52741     pMem->flags |= MEM_Str;
52742     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52743        || sqlite3VdbeMemNulTerminate(pMem) ){
52744       return 0;
52745     }
52746     assert( pMem->z );
52747     sqlite3Atoi64(pMem->z, &value);
52748     return value;
52749   }else{
52750     return 0;
52751   }
52752 }
52753
52754 /*
52755 ** Return the best representation of pMem that we can get into a
52756 ** double.  If pMem is already a double or an integer, return its
52757 ** value.  If it is a string or blob, try to convert it to a double.
52758 ** If it is a NULL, return 0.0.
52759 */
52760 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
52761   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52762   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52763   if( pMem->flags & MEM_Real ){
52764     return pMem->r;
52765   }else if( pMem->flags & MEM_Int ){
52766     return (double)pMem->u.i;
52767   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
52768     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52769     double val = (double)0;
52770     pMem->flags |= MEM_Str;
52771     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52772        || sqlite3VdbeMemNulTerminate(pMem) ){
52773       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52774       return (double)0;
52775     }
52776     assert( pMem->z );
52777     sqlite3AtoF(pMem->z, &val);
52778     return val;
52779   }else{
52780     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52781     return (double)0;
52782   }
52783 }
52784
52785 /*
52786 ** The MEM structure is already a MEM_Real.  Try to also make it a
52787 ** MEM_Int if we can.
52788 */
52789 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
52790   assert( pMem->flags & MEM_Real );
52791   assert( (pMem->flags & MEM_RowSet)==0 );
52792   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52793   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52794
52795   pMem->u.i = doubleToInt64(pMem->r);
52796
52797   /* Only mark the value as an integer if
52798   **
52799   **    (1) the round-trip conversion real->int->real is a no-op, and
52800   **    (2) The integer is neither the largest nor the smallest
52801   **        possible integer (ticket #3922)
52802   **
52803   ** The second and third terms in the following conditional enforces
52804   ** the second condition under the assumption that addition overflow causes
52805   ** values to wrap around.  On x86 hardware, the third term is always
52806   ** true and could be omitted.  But we leave it in because other
52807   ** architectures might behave differently.
52808   */
52809   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
52810       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
52811     pMem->flags |= MEM_Int;
52812   }
52813 }
52814
52815 /*
52816 ** Convert pMem to type integer.  Invalidate any prior representations.
52817 */
52818 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
52819   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52820   assert( (pMem->flags & MEM_RowSet)==0 );
52821   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52822
52823   pMem->u.i = sqlite3VdbeIntValue(pMem);
52824   MemSetTypeFlag(pMem, MEM_Int);
52825   return SQLITE_OK;
52826 }
52827
52828 /*
52829 ** Convert pMem so that it is of type MEM_Real.
52830 ** Invalidate any prior representations.
52831 */
52832 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
52833   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52834   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52835
52836   pMem->r = sqlite3VdbeRealValue(pMem);
52837   MemSetTypeFlag(pMem, MEM_Real);
52838   return SQLITE_OK;
52839 }
52840
52841 /*
52842 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
52843 ** Invalidate any prior representations.
52844 **
52845 ** Every effort is made to force the conversion, even if the input
52846 ** is a string that does not look completely like a number.  Convert
52847 ** as much of the string as we can and ignore the rest.
52848 */
52849 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
52850   int rc;
52851   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
52852   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
52853   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52854   rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8);
52855   if( rc ) return rc;
52856   rc = sqlite3VdbeMemNulTerminate(pMem);
52857   if( rc ) return rc;
52858   if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){
52859     MemSetTypeFlag(pMem, MEM_Int);
52860   }else{
52861     pMem->r = sqlite3VdbeRealValue(pMem);
52862     MemSetTypeFlag(pMem, MEM_Real);
52863     sqlite3VdbeIntegerAffinity(pMem);
52864   }
52865   return SQLITE_OK;
52866 }
52867
52868 /*
52869 ** Delete any previous value and set the value stored in *pMem to NULL.
52870 */
52871 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
52872   if( pMem->flags & MEM_Frame ){
52873     sqlite3VdbeFrameDelete(pMem->u.pFrame);
52874   }
52875   if( pMem->flags & MEM_RowSet ){
52876     sqlite3RowSetClear(pMem->u.pRowSet);
52877   }
52878   MemSetTypeFlag(pMem, MEM_Null);
52879   pMem->type = SQLITE_NULL;
52880 }
52881
52882 /*
52883 ** Delete any previous value and set the value to be a BLOB of length
52884 ** n containing all zeros.
52885 */
52886 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
52887   sqlite3VdbeMemRelease(pMem);
52888   pMem->flags = MEM_Blob|MEM_Zero;
52889   pMem->type = SQLITE_BLOB;
52890   pMem->n = 0;
52891   if( n<0 ) n = 0;
52892   pMem->u.nZero = n;
52893   pMem->enc = SQLITE_UTF8;
52894
52895 #ifdef SQLITE_OMIT_INCRBLOB
52896   sqlite3VdbeMemGrow(pMem, n, 0);
52897   if( pMem->z ){
52898     pMem->n = n;
52899     memset(pMem->z, 0, n);
52900   }
52901 #endif
52902 }
52903
52904 /*
52905 ** Delete any previous value and set the value stored in *pMem to val,
52906 ** manifest type INTEGER.
52907 */
52908 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
52909   sqlite3VdbeMemRelease(pMem);
52910   pMem->u.i = val;
52911   pMem->flags = MEM_Int;
52912   pMem->type = SQLITE_INTEGER;
52913 }
52914
52915 #ifndef SQLITE_OMIT_FLOATING_POINT
52916 /*
52917 ** Delete any previous value and set the value stored in *pMem to val,
52918 ** manifest type REAL.
52919 */
52920 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
52921   if( sqlite3IsNaN(val) ){
52922     sqlite3VdbeMemSetNull(pMem);
52923   }else{
52924     sqlite3VdbeMemRelease(pMem);
52925     pMem->r = val;
52926     pMem->flags = MEM_Real;
52927     pMem->type = SQLITE_FLOAT;
52928   }
52929 }
52930 #endif
52931
52932 /*
52933 ** Delete any previous value and set the value of pMem to be an
52934 ** empty boolean index.
52935 */
52936 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
52937   sqlite3 *db = pMem->db;
52938   assert( db!=0 );
52939   assert( (pMem->flags & MEM_RowSet)==0 );
52940   sqlite3VdbeMemRelease(pMem);
52941   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
52942   if( db->mallocFailed ){
52943     pMem->flags = MEM_Null;
52944   }else{
52945     assert( pMem->zMalloc );
52946     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
52947                                        sqlite3DbMallocSize(db, pMem->zMalloc));
52948     assert( pMem->u.pRowSet!=0 );
52949     pMem->flags = MEM_RowSet;
52950   }
52951 }
52952
52953 /*
52954 ** Return true if the Mem object contains a TEXT or BLOB that is
52955 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
52956 */
52957 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
52958   assert( p->db!=0 );
52959   if( p->flags & (MEM_Str|MEM_Blob) ){
52960     int n = p->n;
52961     if( p->flags & MEM_Zero ){
52962       n += p->u.nZero;
52963     }
52964     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
52965   }
52966   return 0; 
52967 }
52968
52969 /*
52970 ** Size of struct Mem not including the Mem.zMalloc member.
52971 */
52972 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
52973
52974 /*
52975 ** Make an shallow copy of pFrom into pTo.  Prior contents of
52976 ** pTo are freed.  The pFrom->z field is not duplicated.  If
52977 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
52978 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
52979 */
52980 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
52981   assert( (pFrom->flags & MEM_RowSet)==0 );
52982   sqlite3VdbeMemReleaseExternal(pTo);
52983   memcpy(pTo, pFrom, MEMCELLSIZE);
52984   pTo->xDel = 0;
52985   if( (pFrom->flags&MEM_Static)==0 ){
52986     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
52987     assert( srcType==MEM_Ephem || srcType==MEM_Static );
52988     pTo->flags |= srcType;
52989   }
52990 }
52991
52992 /*
52993 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
52994 ** freed before the copy is made.
52995 */
52996 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
52997   int rc = SQLITE_OK;
52998
52999   assert( (pFrom->flags & MEM_RowSet)==0 );
53000   sqlite3VdbeMemReleaseExternal(pTo);
53001   memcpy(pTo, pFrom, MEMCELLSIZE);
53002   pTo->flags &= ~MEM_Dyn;
53003
53004   if( pTo->flags&(MEM_Str|MEM_Blob) ){
53005     if( 0==(pFrom->flags&MEM_Static) ){
53006       pTo->flags |= MEM_Ephem;
53007       rc = sqlite3VdbeMemMakeWriteable(pTo);
53008     }
53009   }
53010
53011   return rc;
53012 }
53013
53014 /*
53015 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
53016 ** freed. If pFrom contains ephemeral data, a copy is made.
53017 **
53018 ** pFrom contains an SQL NULL when this routine returns.
53019 */
53020 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
53021   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
53022   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
53023   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
53024
53025   sqlite3VdbeMemRelease(pTo);
53026   memcpy(pTo, pFrom, sizeof(Mem));
53027   pFrom->flags = MEM_Null;
53028   pFrom->xDel = 0;
53029   pFrom->zMalloc = 0;
53030 }
53031
53032 /*
53033 ** Change the value of a Mem to be a string or a BLOB.
53034 **
53035 ** The memory management strategy depends on the value of the xDel
53036 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
53037 ** string is copied into a (possibly existing) buffer managed by the 
53038 ** Mem structure. Otherwise, any existing buffer is freed and the
53039 ** pointer copied.
53040 **
53041 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
53042 ** size limit) then no memory allocation occurs.  If the string can be
53043 ** stored without allocating memory, then it is.  If a memory allocation
53044 ** is required to store the string, then value of pMem is unchanged.  In
53045 ** either case, SQLITE_TOOBIG is returned.
53046 */
53047 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
53048   Mem *pMem,          /* Memory cell to set to string value */
53049   const char *z,      /* String pointer */
53050   int n,              /* Bytes in string, or negative */
53051   u8 enc,             /* Encoding of z.  0 for BLOBs */
53052   void (*xDel)(void*) /* Destructor function */
53053 ){
53054   int nByte = n;      /* New value for pMem->n */
53055   int iLimit;         /* Maximum allowed string or blob size */
53056   u16 flags = 0;      /* New value for pMem->flags */
53057
53058   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53059   assert( (pMem->flags & MEM_RowSet)==0 );
53060
53061   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
53062   if( !z ){
53063     sqlite3VdbeMemSetNull(pMem);
53064     return SQLITE_OK;
53065   }
53066
53067   if( pMem->db ){
53068     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
53069   }else{
53070     iLimit = SQLITE_MAX_LENGTH;
53071   }
53072   flags = (enc==0?MEM_Blob:MEM_Str);
53073   if( nByte<0 ){
53074     assert( enc!=0 );
53075     if( enc==SQLITE_UTF8 ){
53076       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
53077     }else{
53078       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
53079     }
53080     flags |= MEM_Term;
53081   }
53082
53083   /* The following block sets the new values of Mem.z and Mem.xDel. It
53084   ** also sets a flag in local variable "flags" to indicate the memory
53085   ** management (one of MEM_Dyn or MEM_Static).
53086   */
53087   if( xDel==SQLITE_TRANSIENT ){
53088     int nAlloc = nByte;
53089     if( flags&MEM_Term ){
53090       nAlloc += (enc==SQLITE_UTF8?1:2);
53091     }
53092     if( nByte>iLimit ){
53093       return SQLITE_TOOBIG;
53094     }
53095     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
53096       return SQLITE_NOMEM;
53097     }
53098     memcpy(pMem->z, z, nAlloc);
53099   }else if( xDel==SQLITE_DYNAMIC ){
53100     sqlite3VdbeMemRelease(pMem);
53101     pMem->zMalloc = pMem->z = (char *)z;
53102     pMem->xDel = 0;
53103   }else{
53104     sqlite3VdbeMemRelease(pMem);
53105     pMem->z = (char *)z;
53106     pMem->xDel = xDel;
53107     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
53108   }
53109
53110   pMem->n = nByte;
53111   pMem->flags = flags;
53112   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
53113   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
53114
53115 #ifndef SQLITE_OMIT_UTF16
53116   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
53117     return SQLITE_NOMEM;
53118   }
53119 #endif
53120
53121   if( nByte>iLimit ){
53122     return SQLITE_TOOBIG;
53123   }
53124
53125   return SQLITE_OK;
53126 }
53127
53128 /*
53129 ** Compare the values contained by the two memory cells, returning
53130 ** negative, zero or positive if pMem1 is less than, equal to, or greater
53131 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
53132 ** and reals) sorted numerically, followed by text ordered by the collating
53133 ** sequence pColl and finally blob's ordered by memcmp().
53134 **
53135 ** Two NULL values are considered equal by this function.
53136 */
53137 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
53138   int rc;
53139   int f1, f2;
53140   int combined_flags;
53141
53142   f1 = pMem1->flags;
53143   f2 = pMem2->flags;
53144   combined_flags = f1|f2;
53145   assert( (combined_flags & MEM_RowSet)==0 );
53146  
53147   /* If one value is NULL, it is less than the other. If both values
53148   ** are NULL, return 0.
53149   */
53150   if( combined_flags&MEM_Null ){
53151     return (f2&MEM_Null) - (f1&MEM_Null);
53152   }
53153
53154   /* If one value is a number and the other is not, the number is less.
53155   ** If both are numbers, compare as reals if one is a real, or as integers
53156   ** if both values are integers.
53157   */
53158   if( combined_flags&(MEM_Int|MEM_Real) ){
53159     if( !(f1&(MEM_Int|MEM_Real)) ){
53160       return 1;
53161     }
53162     if( !(f2&(MEM_Int|MEM_Real)) ){
53163       return -1;
53164     }
53165     if( (f1 & f2 & MEM_Int)==0 ){
53166       double r1, r2;
53167       if( (f1&MEM_Real)==0 ){
53168         r1 = (double)pMem1->u.i;
53169       }else{
53170         r1 = pMem1->r;
53171       }
53172       if( (f2&MEM_Real)==0 ){
53173         r2 = (double)pMem2->u.i;
53174       }else{
53175         r2 = pMem2->r;
53176       }
53177       if( r1<r2 ) return -1;
53178       if( r1>r2 ) return 1;
53179       return 0;
53180     }else{
53181       assert( f1&MEM_Int );
53182       assert( f2&MEM_Int );
53183       if( pMem1->u.i < pMem2->u.i ) return -1;
53184       if( pMem1->u.i > pMem2->u.i ) return 1;
53185       return 0;
53186     }
53187   }
53188
53189   /* If one value is a string and the other is a blob, the string is less.
53190   ** If both are strings, compare using the collating functions.
53191   */
53192   if( combined_flags&MEM_Str ){
53193     if( (f1 & MEM_Str)==0 ){
53194       return 1;
53195     }
53196     if( (f2 & MEM_Str)==0 ){
53197       return -1;
53198     }
53199
53200     assert( pMem1->enc==pMem2->enc );
53201     assert( pMem1->enc==SQLITE_UTF8 || 
53202             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
53203
53204     /* The collation sequence must be defined at this point, even if
53205     ** the user deletes the collation sequence after the vdbe program is
53206     ** compiled (this was not always the case).
53207     */
53208     assert( !pColl || pColl->xCmp );
53209
53210     if( pColl ){
53211       if( pMem1->enc==pColl->enc ){
53212         /* The strings are already in the correct encoding.  Call the
53213         ** comparison function directly */
53214         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
53215       }else{
53216         const void *v1, *v2;
53217         int n1, n2;
53218         Mem c1;
53219         Mem c2;
53220         memset(&c1, 0, sizeof(c1));
53221         memset(&c2, 0, sizeof(c2));
53222         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
53223         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
53224         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
53225         n1 = v1==0 ? 0 : c1.n;
53226         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
53227         n2 = v2==0 ? 0 : c2.n;
53228         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
53229         sqlite3VdbeMemRelease(&c1);
53230         sqlite3VdbeMemRelease(&c2);
53231         return rc;
53232       }
53233     }
53234     /* If a NULL pointer was passed as the collate function, fall through
53235     ** to the blob case and use memcmp().  */
53236   }
53237  
53238   /* Both values must be blobs.  Compare using memcmp().  */
53239   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
53240   if( rc==0 ){
53241     rc = pMem1->n - pMem2->n;
53242   }
53243   return rc;
53244 }
53245
53246 /*
53247 ** Move data out of a btree key or data field and into a Mem structure.
53248 ** The data or key is taken from the entry that pCur is currently pointing
53249 ** to.  offset and amt determine what portion of the data or key to retrieve.
53250 ** key is true to get the key or false to get data.  The result is written
53251 ** into the pMem element.
53252 **
53253 ** The pMem structure is assumed to be uninitialized.  Any prior content
53254 ** is overwritten without being freed.
53255 **
53256 ** If this routine fails for any reason (malloc returns NULL or unable
53257 ** to read from the disk) then the pMem is left in an inconsistent state.
53258 */
53259 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
53260   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
53261   int offset,       /* Offset from the start of data to return bytes from. */
53262   int amt,          /* Number of bytes to return. */
53263   int key,          /* If true, retrieve from the btree key, not data. */
53264   Mem *pMem         /* OUT: Return data in this Mem structure. */
53265 ){
53266   char *zData;        /* Data from the btree layer */
53267   int available = 0;  /* Number of bytes available on the local btree page */
53268   int rc = SQLITE_OK; /* Return code */
53269
53270   assert( sqlite3BtreeCursorIsValid(pCur) );
53271
53272   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
53273   ** that both the BtShared and database handle mutexes are held. */
53274   assert( (pMem->flags & MEM_RowSet)==0 );
53275   if( key ){
53276     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
53277   }else{
53278     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
53279   }
53280   assert( zData!=0 );
53281
53282   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
53283     sqlite3VdbeMemRelease(pMem);
53284     pMem->z = &zData[offset];
53285     pMem->flags = MEM_Blob|MEM_Ephem;
53286   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
53287     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
53288     pMem->enc = 0;
53289     pMem->type = SQLITE_BLOB;
53290     if( key ){
53291       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
53292     }else{
53293       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
53294     }
53295     pMem->z[amt] = 0;
53296     pMem->z[amt+1] = 0;
53297     if( rc!=SQLITE_OK ){
53298       sqlite3VdbeMemRelease(pMem);
53299     }
53300   }
53301   pMem->n = amt;
53302
53303   return rc;
53304 }
53305
53306 /* This function is only available internally, it is not part of the
53307 ** external API. It works in a similar way to sqlite3_value_text(),
53308 ** except the data returned is in the encoding specified by the second
53309 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
53310 ** SQLITE_UTF8.
53311 **
53312 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
53313 ** If that is the case, then the result must be aligned on an even byte
53314 ** boundary.
53315 */
53316 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
53317   if( !pVal ) return 0;
53318
53319   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
53320   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
53321   assert( (pVal->flags & MEM_RowSet)==0 );
53322
53323   if( pVal->flags&MEM_Null ){
53324     return 0;
53325   }
53326   assert( (MEM_Blob>>3) == MEM_Str );
53327   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
53328   expandBlob(pVal);
53329   if( pVal->flags&MEM_Str ){
53330     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
53331     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
53332       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
53333       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
53334         return 0;
53335       }
53336     }
53337     sqlite3VdbeMemNulTerminate(pVal);
53338   }else{
53339     assert( (pVal->flags&MEM_Blob)==0 );
53340     sqlite3VdbeMemStringify(pVal, enc);
53341     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
53342   }
53343   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
53344               || pVal->db->mallocFailed );
53345   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
53346     return pVal->z;
53347   }else{
53348     return 0;
53349   }
53350 }
53351
53352 /*
53353 ** Create a new sqlite3_value object.
53354 */
53355 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
53356   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
53357   if( p ){
53358     p->flags = MEM_Null;
53359     p->type = SQLITE_NULL;
53360     p->db = db;
53361   }
53362   return p;
53363 }
53364
53365 /*
53366 ** Create a new sqlite3_value object, containing the value of pExpr.
53367 **
53368 ** This only works for very simple expressions that consist of one constant
53369 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
53370 ** be converted directly into a value, then the value is allocated and
53371 ** a pointer written to *ppVal. The caller is responsible for deallocating
53372 ** the value by passing it to sqlite3ValueFree() later on. If the expression
53373 ** cannot be converted to a value, then *ppVal is set to NULL.
53374 */
53375 SQLITE_PRIVATE int sqlite3ValueFromExpr(
53376   sqlite3 *db,              /* The database connection */
53377   Expr *pExpr,              /* The expression to evaluate */
53378   u8 enc,                   /* Encoding to use */
53379   u8 affinity,              /* Affinity to use */
53380   sqlite3_value **ppVal     /* Write the new value here */
53381 ){
53382   int op;
53383   char *zVal = 0;
53384   sqlite3_value *pVal = 0;
53385
53386   if( !pExpr ){
53387     *ppVal = 0;
53388     return SQLITE_OK;
53389   }
53390   op = pExpr->op;
53391
53392   /* op can only be TK_REGISTER is we have compiled with SQLITE_ENABLE_STAT2.
53393   ** The ifdef here is to enable us to achieve 100% branch test coverage even
53394   ** when SQLITE_ENABLE_STAT2 is omitted.
53395   */
53396 #ifdef SQLITE_ENABLE_STAT2
53397   if( op==TK_REGISTER ) op = pExpr->op2;
53398 #else
53399   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
53400 #endif
53401
53402   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
53403     pVal = sqlite3ValueNew(db);
53404     if( pVal==0 ) goto no_mem;
53405     if( ExprHasProperty(pExpr, EP_IntValue) ){
53406       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
53407     }else{
53408       zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
53409       if( zVal==0 ) goto no_mem;
53410       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
53411       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
53412     }
53413     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
53414       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
53415     }else{
53416       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
53417     }
53418     if( enc!=SQLITE_UTF8 ){
53419       sqlite3VdbeChangeEncoding(pVal, enc);
53420     }
53421   }else if( op==TK_UMINUS ) {
53422     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
53423       pVal->u.i = -1 * pVal->u.i;
53424       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
53425       pVal->r = (double)-1 * pVal->r;
53426     }
53427   }
53428 #ifndef SQLITE_OMIT_BLOB_LITERAL
53429   else if( op==TK_BLOB ){
53430     int nVal;
53431     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
53432     assert( pExpr->u.zToken[1]=='\'' );
53433     pVal = sqlite3ValueNew(db);
53434     if( !pVal ) goto no_mem;
53435     zVal = &pExpr->u.zToken[2];
53436     nVal = sqlite3Strlen30(zVal)-1;
53437     assert( zVal[nVal]=='\'' );
53438     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
53439                          0, SQLITE_DYNAMIC);
53440   }
53441 #endif
53442
53443   if( pVal ){
53444     sqlite3VdbeMemStoreType(pVal);
53445   }
53446   *ppVal = pVal;
53447   return SQLITE_OK;
53448
53449 no_mem:
53450   db->mallocFailed = 1;
53451   sqlite3DbFree(db, zVal);
53452   sqlite3ValueFree(pVal);
53453   *ppVal = 0;
53454   return SQLITE_NOMEM;
53455 }
53456
53457 /*
53458 ** Change the string value of an sqlite3_value object
53459 */
53460 SQLITE_PRIVATE void sqlite3ValueSetStr(
53461   sqlite3_value *v,     /* Value to be set */
53462   int n,                /* Length of string z */
53463   const void *z,        /* Text of the new string */
53464   u8 enc,               /* Encoding to use */
53465   void (*xDel)(void*)   /* Destructor for the string */
53466 ){
53467   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
53468 }
53469
53470 /*
53471 ** Free an sqlite3_value object
53472 */
53473 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
53474   if( !v ) return;
53475   sqlite3VdbeMemRelease((Mem *)v);
53476   sqlite3DbFree(((Mem*)v)->db, v);
53477 }
53478
53479 /*
53480 ** Return the number of bytes in the sqlite3_value object assuming
53481 ** that it uses the encoding "enc"
53482 */
53483 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
53484   Mem *p = (Mem*)pVal;
53485   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
53486     if( p->flags & MEM_Zero ){
53487       return p->n + p->u.nZero;
53488     }else{
53489       return p->n;
53490     }
53491   }
53492   return 0;
53493 }
53494
53495 /************** End of vdbemem.c *********************************************/
53496 /************** Begin file vdbeaux.c *****************************************/
53497 /*
53498 ** 2003 September 6
53499 **
53500 ** The author disclaims copyright to this source code.  In place of
53501 ** a legal notice, here is a blessing:
53502 **
53503 **    May you do good and not evil.
53504 **    May you find forgiveness for yourself and forgive others.
53505 **    May you share freely, never taking more than you give.
53506 **
53507 *************************************************************************
53508 ** This file contains code used for creating, destroying, and populating
53509 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
53510 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
53511 ** But that file was getting too big so this subroutines were split out.
53512 */
53513
53514
53515
53516 /*
53517 ** When debugging the code generator in a symbolic debugger, one can
53518 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
53519 ** as they are added to the instruction stream.
53520 */
53521 #ifdef SQLITE_DEBUG
53522 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
53523 #endif
53524
53525
53526 /*
53527 ** Create a new virtual database engine.
53528 */
53529 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
53530   Vdbe *p;
53531   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
53532   if( p==0 ) return 0;
53533   p->db = db;
53534   if( db->pVdbe ){
53535     db->pVdbe->pPrev = p;
53536   }
53537   p->pNext = db->pVdbe;
53538   p->pPrev = 0;
53539   db->pVdbe = p;
53540   p->magic = VDBE_MAGIC_INIT;
53541   return p;
53542 }
53543
53544 /*
53545 ** Remember the SQL string for a prepared statement.
53546 */
53547 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
53548   assert( isPrepareV2==1 || isPrepareV2==0 );
53549   if( p==0 ) return;
53550 #ifdef SQLITE_OMIT_TRACE
53551   if( !isPrepareV2 ) return;
53552 #endif
53553   assert( p->zSql==0 );
53554   p->zSql = sqlite3DbStrNDup(p->db, z, n);
53555   p->isPrepareV2 = (u8)isPrepareV2;
53556 }
53557
53558 /*
53559 ** Return the SQL associated with a prepared statement
53560 */
53561 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
53562   Vdbe *p = (Vdbe *)pStmt;
53563   return (p && p->isPrepareV2) ? p->zSql : 0;
53564 }
53565
53566 /*
53567 ** Swap all content between two VDBE structures.
53568 */
53569 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
53570   Vdbe tmp, *pTmp;
53571   char *zTmp;
53572   tmp = *pA;
53573   *pA = *pB;
53574   *pB = tmp;
53575   pTmp = pA->pNext;
53576   pA->pNext = pB->pNext;
53577   pB->pNext = pTmp;
53578   pTmp = pA->pPrev;
53579   pA->pPrev = pB->pPrev;
53580   pB->pPrev = pTmp;
53581   zTmp = pA->zSql;
53582   pA->zSql = pB->zSql;
53583   pB->zSql = zTmp;
53584   pB->isPrepareV2 = pA->isPrepareV2;
53585 }
53586
53587 #ifdef SQLITE_DEBUG
53588 /*
53589 ** Turn tracing on or off
53590 */
53591 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
53592   p->trace = trace;
53593 }
53594 #endif
53595
53596 /*
53597 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
53598 ** it was.
53599 **
53600 ** If an out-of-memory error occurs while resizing the array, return
53601 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
53602 ** unchanged (this is so that any opcodes already allocated can be 
53603 ** correctly deallocated along with the rest of the Vdbe).
53604 */
53605 static int growOpArray(Vdbe *p){
53606   VdbeOp *pNew;
53607   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
53608   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
53609   if( pNew ){
53610     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
53611     p->aOp = pNew;
53612   }
53613   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
53614 }
53615
53616 /*
53617 ** Add a new instruction to the list of instructions current in the
53618 ** VDBE.  Return the address of the new instruction.
53619 **
53620 ** Parameters:
53621 **
53622 **    p               Pointer to the VDBE
53623 **
53624 **    op              The opcode for this instruction
53625 **
53626 **    p1, p2, p3      Operands
53627 **
53628 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
53629 ** the sqlite3VdbeChangeP4() function to change the value of the P4
53630 ** operand.
53631 */
53632 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
53633   int i;
53634   VdbeOp *pOp;
53635
53636   i = p->nOp;
53637   assert( p->magic==VDBE_MAGIC_INIT );
53638   assert( op>0 && op<0xff );
53639   if( p->nOpAlloc<=i ){
53640     if( growOpArray(p) ){
53641       return 1;
53642     }
53643   }
53644   p->nOp++;
53645   pOp = &p->aOp[i];
53646   pOp->opcode = (u8)op;
53647   pOp->p5 = 0;
53648   pOp->p1 = p1;
53649   pOp->p2 = p2;
53650   pOp->p3 = p3;
53651   pOp->p4.p = 0;
53652   pOp->p4type = P4_NOTUSED;
53653   p->expired = 0;
53654 #ifdef SQLITE_DEBUG
53655   pOp->zComment = 0;
53656   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
53657 #endif
53658 #ifdef VDBE_PROFILE
53659   pOp->cycles = 0;
53660   pOp->cnt = 0;
53661 #endif
53662   return i;
53663 }
53664 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
53665   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
53666 }
53667 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
53668   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
53669 }
53670 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
53671   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
53672 }
53673
53674
53675 /*
53676 ** Add an opcode that includes the p4 value as a pointer.
53677 */
53678 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
53679   Vdbe *p,            /* Add the opcode to this VM */
53680   int op,             /* The new opcode */
53681   int p1,             /* The P1 operand */
53682   int p2,             /* The P2 operand */
53683   int p3,             /* The P3 operand */
53684   const char *zP4,    /* The P4 operand */
53685   int p4type          /* P4 operand type */
53686 ){
53687   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53688   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
53689   return addr;
53690 }
53691
53692 /*
53693 ** Add an opcode that includes the p4 value as an integer.
53694 */
53695 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
53696   Vdbe *p,            /* Add the opcode to this VM */
53697   int op,             /* The new opcode */
53698   int p1,             /* The P1 operand */
53699   int p2,             /* The P2 operand */
53700   int p3,             /* The P3 operand */
53701   int p4              /* The P4 operand as an integer */
53702 ){
53703   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53704   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
53705   return addr;
53706 }
53707
53708 /*
53709 ** Create a new symbolic label for an instruction that has yet to be
53710 ** coded.  The symbolic label is really just a negative number.  The
53711 ** label can be used as the P2 value of an operation.  Later, when
53712 ** the label is resolved to a specific address, the VDBE will scan
53713 ** through its operation list and change all values of P2 which match
53714 ** the label into the resolved address.
53715 **
53716 ** The VDBE knows that a P2 value is a label because labels are
53717 ** always negative and P2 values are suppose to be non-negative.
53718 ** Hence, a negative P2 value is a label that has yet to be resolved.
53719 **
53720 ** Zero is returned if a malloc() fails.
53721 */
53722 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
53723   int i;
53724   i = p->nLabel++;
53725   assert( p->magic==VDBE_MAGIC_INIT );
53726   if( i>=p->nLabelAlloc ){
53727     int n = p->nLabelAlloc*2 + 5;
53728     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
53729                                        n*sizeof(p->aLabel[0]));
53730     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
53731   }
53732   if( p->aLabel ){
53733     p->aLabel[i] = -1;
53734   }
53735   return -1-i;
53736 }
53737
53738 /*
53739 ** Resolve label "x" to be the address of the next instruction to
53740 ** be inserted.  The parameter "x" must have been obtained from
53741 ** a prior call to sqlite3VdbeMakeLabel().
53742 */
53743 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
53744   int j = -1-x;
53745   assert( p->magic==VDBE_MAGIC_INIT );
53746   assert( j>=0 && j<p->nLabel );
53747   if( p->aLabel ){
53748     p->aLabel[j] = p->nOp;
53749   }
53750 }
53751
53752 /*
53753 ** Mark the VDBE as one that can only be run one time.
53754 */
53755 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
53756   p->runOnlyOnce = 1;
53757 }
53758
53759 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
53760
53761 /*
53762 ** The following type and function are used to iterate through all opcodes
53763 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
53764 ** invoke directly or indirectly. It should be used as follows:
53765 **
53766 **   Op *pOp;
53767 **   VdbeOpIter sIter;
53768 **
53769 **   memset(&sIter, 0, sizeof(sIter));
53770 **   sIter.v = v;                            // v is of type Vdbe* 
53771 **   while( (pOp = opIterNext(&sIter)) ){
53772 **     // Do something with pOp
53773 **   }
53774 **   sqlite3DbFree(v->db, sIter.apSub);
53775 ** 
53776 */
53777 typedef struct VdbeOpIter VdbeOpIter;
53778 struct VdbeOpIter {
53779   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
53780   SubProgram **apSub;        /* Array of subprograms */
53781   int nSub;                  /* Number of entries in apSub */
53782   int iAddr;                 /* Address of next instruction to return */
53783   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
53784 };
53785 static Op *opIterNext(VdbeOpIter *p){
53786   Vdbe *v = p->v;
53787   Op *pRet = 0;
53788   Op *aOp;
53789   int nOp;
53790
53791   if( p->iSub<=p->nSub ){
53792
53793     if( p->iSub==0 ){
53794       aOp = v->aOp;
53795       nOp = v->nOp;
53796     }else{
53797       aOp = p->apSub[p->iSub-1]->aOp;
53798       nOp = p->apSub[p->iSub-1]->nOp;
53799     }
53800     assert( p->iAddr<nOp );
53801
53802     pRet = &aOp[p->iAddr];
53803     p->iAddr++;
53804     if( p->iAddr==nOp ){
53805       p->iSub++;
53806       p->iAddr = 0;
53807     }
53808   
53809     if( pRet->p4type==P4_SUBPROGRAM ){
53810       int nByte = (p->nSub+1)*sizeof(SubProgram*);
53811       int j;
53812       for(j=0; j<p->nSub; j++){
53813         if( p->apSub[j]==pRet->p4.pProgram ) break;
53814       }
53815       if( j==p->nSub ){
53816         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
53817         if( !p->apSub ){
53818           pRet = 0;
53819         }else{
53820           p->apSub[p->nSub++] = pRet->p4.pProgram;
53821         }
53822       }
53823     }
53824   }
53825
53826   return pRet;
53827 }
53828
53829 /*
53830 ** Check if the program stored in the VM associated with pParse may
53831 ** throw an ABORT exception (causing the statement, but not entire transaction
53832 ** to be rolled back). This condition is true if the main program or any
53833 ** sub-programs contains any of the following:
53834 **
53835 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53836 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53837 **   *  OP_Destroy
53838 **   *  OP_VUpdate
53839 **   *  OP_VRename
53840 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
53841 **
53842 ** Then check that the value of Parse.mayAbort is true if an
53843 ** ABORT may be thrown, or false otherwise. Return true if it does
53844 ** match, or false otherwise. This function is intended to be used as
53845 ** part of an assert statement in the compiler. Similar to:
53846 **
53847 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
53848 */
53849 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
53850   int hasAbort = 0;
53851   Op *pOp;
53852   VdbeOpIter sIter;
53853   memset(&sIter, 0, sizeof(sIter));
53854   sIter.v = v;
53855
53856   while( (pOp = opIterNext(&sIter))!=0 ){
53857     int opcode = pOp->opcode;
53858     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
53859 #ifndef SQLITE_OMIT_FOREIGN_KEY
53860      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
53861 #endif
53862      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
53863       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
53864     ){
53865       hasAbort = 1;
53866       break;
53867     }
53868   }
53869   sqlite3DbFree(v->db, sIter.apSub);
53870
53871   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
53872   ** If malloc failed, then the while() loop above may not have iterated
53873   ** through all opcodes and hasAbort may be set incorrectly. Return
53874   ** true for this case to prevent the assert() in the callers frame
53875   ** from failing.  */
53876   return ( v->db->mallocFailed || hasAbort==mayAbort );
53877 }
53878 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
53879
53880 /*
53881 ** Loop through the program looking for P2 values that are negative
53882 ** on jump instructions.  Each such value is a label.  Resolve the
53883 ** label by setting the P2 value to its correct non-zero value.
53884 **
53885 ** This routine is called once after all opcodes have been inserted.
53886 **
53887 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
53888 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
53889 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
53890 **
53891 ** The Op.opflags field is set on all opcodes.
53892 */
53893 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
53894   int i;
53895   int nMaxArgs = *pMaxFuncArgs;
53896   Op *pOp;
53897   int *aLabel = p->aLabel;
53898   p->readOnly = 1;
53899   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
53900     u8 opcode = pOp->opcode;
53901
53902     pOp->opflags = sqlite3OpcodeProperty[opcode];
53903     if( opcode==OP_Function || opcode==OP_AggStep ){
53904       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
53905     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
53906       p->readOnly = 0;
53907 #ifndef SQLITE_OMIT_VIRTUALTABLE
53908     }else if( opcode==OP_VUpdate ){
53909       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
53910     }else if( opcode==OP_VFilter ){
53911       int n;
53912       assert( p->nOp - i >= 3 );
53913       assert( pOp[-1].opcode==OP_Integer );
53914       n = pOp[-1].p1;
53915       if( n>nMaxArgs ) nMaxArgs = n;
53916 #endif
53917     }
53918
53919     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
53920       assert( -1-pOp->p2<p->nLabel );
53921       pOp->p2 = aLabel[-1-pOp->p2];
53922     }
53923   }
53924   sqlite3DbFree(p->db, p->aLabel);
53925   p->aLabel = 0;
53926
53927   *pMaxFuncArgs = nMaxArgs;
53928 }
53929
53930 /*
53931 ** Return the address of the next instruction to be inserted.
53932 */
53933 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
53934   assert( p->magic==VDBE_MAGIC_INIT );
53935   return p->nOp;
53936 }
53937
53938 /*
53939 ** This function returns a pointer to the array of opcodes associated with
53940 ** the Vdbe passed as the first argument. It is the callers responsibility
53941 ** to arrange for the returned array to be eventually freed using the 
53942 ** vdbeFreeOpArray() function.
53943 **
53944 ** Before returning, *pnOp is set to the number of entries in the returned
53945 ** array. Also, *pnMaxArg is set to the larger of its current value and 
53946 ** the number of entries in the Vdbe.apArg[] array required to execute the 
53947 ** returned program.
53948 */
53949 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
53950   VdbeOp *aOp = p->aOp;
53951   assert( aOp && !p->db->mallocFailed );
53952
53953   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
53954   assert( p->aMutex.nMutex==0 );
53955
53956   resolveP2Values(p, pnMaxArg);
53957   *pnOp = p->nOp;
53958   p->aOp = 0;
53959   return aOp;
53960 }
53961
53962 /*
53963 ** Add a whole list of operations to the operation stack.  Return the
53964 ** address of the first operation added.
53965 */
53966 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
53967   int addr;
53968   assert( p->magic==VDBE_MAGIC_INIT );
53969   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
53970     return 0;
53971   }
53972   addr = p->nOp;
53973   if( ALWAYS(nOp>0) ){
53974     int i;
53975     VdbeOpList const *pIn = aOp;
53976     for(i=0; i<nOp; i++, pIn++){
53977       int p2 = pIn->p2;
53978       VdbeOp *pOut = &p->aOp[i+addr];
53979       pOut->opcode = pIn->opcode;
53980       pOut->p1 = pIn->p1;
53981       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
53982         pOut->p2 = addr + ADDR(p2);
53983       }else{
53984         pOut->p2 = p2;
53985       }
53986       pOut->p3 = pIn->p3;
53987       pOut->p4type = P4_NOTUSED;
53988       pOut->p4.p = 0;
53989       pOut->p5 = 0;
53990 #ifdef SQLITE_DEBUG
53991       pOut->zComment = 0;
53992       if( sqlite3VdbeAddopTrace ){
53993         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
53994       }
53995 #endif
53996     }
53997     p->nOp += nOp;
53998   }
53999   return addr;
54000 }
54001
54002 /*
54003 ** Change the value of the P1 operand for a specific instruction.
54004 ** This routine is useful when a large program is loaded from a
54005 ** static array using sqlite3VdbeAddOpList but we want to make a
54006 ** few minor changes to the program.
54007 */
54008 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
54009   assert( p!=0 );
54010   assert( addr>=0 );
54011   if( p->nOp>addr ){
54012     p->aOp[addr].p1 = val;
54013   }
54014 }
54015
54016 /*
54017 ** Change the value of the P2 operand for a specific instruction.
54018 ** This routine is useful for setting a jump destination.
54019 */
54020 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
54021   assert( p!=0 );
54022   assert( addr>=0 );
54023   if( p->nOp>addr ){
54024     p->aOp[addr].p2 = val;
54025   }
54026 }
54027
54028 /*
54029 ** Change the value of the P3 operand for a specific instruction.
54030 */
54031 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
54032   assert( p!=0 );
54033   assert( addr>=0 );
54034   if( p->nOp>addr ){
54035     p->aOp[addr].p3 = val;
54036   }
54037 }
54038
54039 /*
54040 ** Change the value of the P5 operand for the most recently
54041 ** added operation.
54042 */
54043 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
54044   assert( p!=0 );
54045   if( p->aOp ){
54046     assert( p->nOp>0 );
54047     p->aOp[p->nOp-1].p5 = val;
54048   }
54049 }
54050
54051 /*
54052 ** Change the P2 operand of instruction addr so that it points to
54053 ** the address of the next instruction to be coded.
54054 */
54055 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
54056   sqlite3VdbeChangeP2(p, addr, p->nOp);
54057 }
54058
54059
54060 /*
54061 ** If the input FuncDef structure is ephemeral, then free it.  If
54062 ** the FuncDef is not ephermal, then do nothing.
54063 */
54064 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
54065   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
54066     sqlite3DbFree(db, pDef);
54067   }
54068 }
54069
54070 /*
54071 ** Delete a P4 value if necessary.
54072 */
54073 static void freeP4(sqlite3 *db, int p4type, void *p4){
54074   if( p4 ){
54075     switch( p4type ){
54076       case P4_REAL:
54077       case P4_INT64:
54078       case P4_MPRINTF:
54079       case P4_DYNAMIC:
54080       case P4_KEYINFO:
54081       case P4_INTARRAY:
54082       case P4_KEYINFO_HANDOFF: {
54083         sqlite3DbFree(db, p4);
54084         break;
54085       }
54086       case P4_VDBEFUNC: {
54087         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
54088         freeEphemeralFunction(db, pVdbeFunc->pFunc);
54089         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
54090         sqlite3DbFree(db, pVdbeFunc);
54091         break;
54092       }
54093       case P4_FUNCDEF: {
54094         freeEphemeralFunction(db, (FuncDef*)p4);
54095         break;
54096       }
54097       case P4_MEM: {
54098         sqlite3ValueFree((sqlite3_value*)p4);
54099         break;
54100       }
54101       case P4_VTAB : {
54102         sqlite3VtabUnlock((VTable *)p4);
54103         break;
54104       }
54105       case P4_SUBPROGRAM : {
54106         sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
54107         break;
54108       }
54109     }
54110   }
54111 }
54112
54113 /*
54114 ** Free the space allocated for aOp and any p4 values allocated for the
54115 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
54116 ** nOp entries. 
54117 */
54118 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
54119   if( aOp ){
54120     Op *pOp;
54121     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
54122       freeP4(db, pOp->p4type, pOp->p4.p);
54123 #ifdef SQLITE_DEBUG
54124       sqlite3DbFree(db, pOp->zComment);
54125 #endif     
54126     }
54127   }
54128   sqlite3DbFree(db, aOp);
54129 }
54130
54131 /*
54132 ** Decrement the ref-count on the SubProgram structure passed as the
54133 ** second argument. If the ref-count reaches zero, free the structure.
54134 **
54135 ** The array of VDBE opcodes stored as SubProgram.aOp is freed if
54136 ** either the ref-count reaches zero or parameter freeop is non-zero.
54137 **
54138 ** Since the array of opcodes pointed to by SubProgram.aOp may directly
54139 ** or indirectly contain a reference to the SubProgram structure itself.
54140 ** By passing a non-zero freeop parameter, the caller may ensure that all
54141 ** SubProgram structures and their aOp arrays are freed, even when there
54142 ** are such circular references.
54143 */
54144 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
54145   if( p ){
54146     assert( p->nRef>0 );
54147     if( freeop || p->nRef==1 ){
54148       Op *aOp = p->aOp;
54149       p->aOp = 0;
54150       vdbeFreeOpArray(db, aOp, p->nOp);
54151       p->nOp = 0;
54152     }
54153     p->nRef--;
54154     if( p->nRef==0 ){
54155       sqlite3DbFree(db, p);
54156     }
54157   }
54158 }
54159
54160
54161 /*
54162 ** Change N opcodes starting at addr to No-ops.
54163 */
54164 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
54165   if( p->aOp ){
54166     VdbeOp *pOp = &p->aOp[addr];
54167     sqlite3 *db = p->db;
54168     while( N-- ){
54169       freeP4(db, pOp->p4type, pOp->p4.p);
54170       memset(pOp, 0, sizeof(pOp[0]));
54171       pOp->opcode = OP_Noop;
54172       pOp++;
54173     }
54174   }
54175 }
54176
54177 /*
54178 ** Change the value of the P4 operand for a specific instruction.
54179 ** This routine is useful when a large program is loaded from a
54180 ** static array using sqlite3VdbeAddOpList but we want to make a
54181 ** few minor changes to the program.
54182 **
54183 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
54184 ** the string is made into memory obtained from sqlite3_malloc().
54185 ** A value of n==0 means copy bytes of zP4 up to and including the
54186 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
54187 **
54188 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
54189 ** A copy is made of the KeyInfo structure into memory obtained from
54190 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
54191 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
54192 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
54193 ** caller should not free the allocation, it will be freed when the Vdbe is
54194 ** finalized.
54195 ** 
54196 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
54197 ** to a string or structure that is guaranteed to exist for the lifetime of
54198 ** the Vdbe. In these cases we can just copy the pointer.
54199 **
54200 ** If addr<0 then change P4 on the most recently inserted instruction.
54201 */
54202 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
54203   Op *pOp;
54204   sqlite3 *db;
54205   assert( p!=0 );
54206   db = p->db;
54207   assert( p->magic==VDBE_MAGIC_INIT );
54208   if( p->aOp==0 || db->mallocFailed ){
54209     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
54210       freeP4(db, n, (void*)*(char**)&zP4);
54211     }
54212     return;
54213   }
54214   assert( p->nOp>0 );
54215   assert( addr<p->nOp );
54216   if( addr<0 ){
54217     addr = p->nOp - 1;
54218   }
54219   pOp = &p->aOp[addr];
54220   freeP4(db, pOp->p4type, pOp->p4.p);
54221   pOp->p4.p = 0;
54222   if( n==P4_INT32 ){
54223     /* Note: this cast is safe, because the origin data point was an int
54224     ** that was cast to a (const char *). */
54225     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
54226     pOp->p4type = P4_INT32;
54227   }else if( zP4==0 ){
54228     pOp->p4.p = 0;
54229     pOp->p4type = P4_NOTUSED;
54230   }else if( n==P4_KEYINFO ){
54231     KeyInfo *pKeyInfo;
54232     int nField, nByte;
54233
54234     nField = ((KeyInfo*)zP4)->nField;
54235     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
54236     pKeyInfo = sqlite3Malloc( nByte );
54237     pOp->p4.pKeyInfo = pKeyInfo;
54238     if( pKeyInfo ){
54239       u8 *aSortOrder;
54240       memcpy((char*)pKeyInfo, zP4, nByte - nField);
54241       aSortOrder = pKeyInfo->aSortOrder;
54242       if( aSortOrder ){
54243         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
54244         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
54245       }
54246       pOp->p4type = P4_KEYINFO;
54247     }else{
54248       p->db->mallocFailed = 1;
54249       pOp->p4type = P4_NOTUSED;
54250     }
54251   }else if( n==P4_KEYINFO_HANDOFF ){
54252     pOp->p4.p = (void*)zP4;
54253     pOp->p4type = P4_KEYINFO;
54254   }else if( n==P4_VTAB ){
54255     pOp->p4.p = (void*)zP4;
54256     pOp->p4type = P4_VTAB;
54257     sqlite3VtabLock((VTable *)zP4);
54258     assert( ((VTable *)zP4)->db==p->db );
54259   }else if( n<0 ){
54260     pOp->p4.p = (void*)zP4;
54261     pOp->p4type = (signed char)n;
54262   }else{
54263     if( n==0 ) n = sqlite3Strlen30(zP4);
54264     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
54265     pOp->p4type = P4_DYNAMIC;
54266   }
54267 }
54268
54269 #ifndef NDEBUG
54270 /*
54271 ** Change the comment on the the most recently coded instruction.  Or
54272 ** insert a No-op and add the comment to that new instruction.  This
54273 ** makes the code easier to read during debugging.  None of this happens
54274 ** in a production build.
54275 */
54276 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
54277   va_list ap;
54278   if( !p ) return;
54279   assert( p->nOp>0 || p->aOp==0 );
54280   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
54281   if( p->nOp ){
54282     char **pz = &p->aOp[p->nOp-1].zComment;
54283     va_start(ap, zFormat);
54284     sqlite3DbFree(p->db, *pz);
54285     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
54286     va_end(ap);
54287   }
54288 }
54289 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
54290   va_list ap;
54291   if( !p ) return;
54292   sqlite3VdbeAddOp0(p, OP_Noop);
54293   assert( p->nOp>0 || p->aOp==0 );
54294   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
54295   if( p->nOp ){
54296     char **pz = &p->aOp[p->nOp-1].zComment;
54297     va_start(ap, zFormat);
54298     sqlite3DbFree(p->db, *pz);
54299     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
54300     va_end(ap);
54301   }
54302 }
54303 #endif  /* NDEBUG */
54304
54305 /*
54306 ** Return the opcode for a given address.  If the address is -1, then
54307 ** return the most recently inserted opcode.
54308 **
54309 ** If a memory allocation error has occurred prior to the calling of this
54310 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
54311 ** is readable but not writable, though it is cast to a writable value.
54312 ** The return of a dummy opcode allows the call to continue functioning
54313 ** after a OOM fault without having to check to see if the return from 
54314 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
54315 ** dummy will never be written to.  This is verified by code inspection and
54316 ** by running with Valgrind.
54317 **
54318 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
54319 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
54320 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
54321 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
54322 ** having to double-check to make sure that the result is non-negative. But
54323 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
54324 ** check the value of p->nOp-1 before continuing.
54325 */
54326 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
54327   /* C89 specifies that the constant "dummy" will be initialized to all
54328   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
54329   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
54330   assert( p->magic==VDBE_MAGIC_INIT );
54331   if( addr<0 ){
54332 #ifdef SQLITE_OMIT_TRACE
54333     if( p->nOp==0 ) return (VdbeOp*)&dummy;
54334 #endif
54335     addr = p->nOp - 1;
54336   }
54337   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
54338   if( p->db->mallocFailed ){
54339     return (VdbeOp*)&dummy;
54340   }else{
54341     return &p->aOp[addr];
54342   }
54343 }
54344
54345 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
54346      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
54347 /*
54348 ** Compute a string that describes the P4 parameter for an opcode.
54349 ** Use zTemp for any required temporary buffer space.
54350 */
54351 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
54352   char *zP4 = zTemp;
54353   assert( nTemp>=20 );
54354   switch( pOp->p4type ){
54355     case P4_KEYINFO_STATIC:
54356     case P4_KEYINFO: {
54357       int i, j;
54358       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
54359       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
54360       i = sqlite3Strlen30(zTemp);
54361       for(j=0; j<pKeyInfo->nField; j++){
54362         CollSeq *pColl = pKeyInfo->aColl[j];
54363         if( pColl ){
54364           int n = sqlite3Strlen30(pColl->zName);
54365           if( i+n>nTemp-6 ){
54366             memcpy(&zTemp[i],",...",4);
54367             break;
54368           }
54369           zTemp[i++] = ',';
54370           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
54371             zTemp[i++] = '-';
54372           }
54373           memcpy(&zTemp[i], pColl->zName,n+1);
54374           i += n;
54375         }else if( i+4<nTemp-6 ){
54376           memcpy(&zTemp[i],",nil",4);
54377           i += 4;
54378         }
54379       }
54380       zTemp[i++] = ')';
54381       zTemp[i] = 0;
54382       assert( i<nTemp );
54383       break;
54384     }
54385     case P4_COLLSEQ: {
54386       CollSeq *pColl = pOp->p4.pColl;
54387       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
54388       break;
54389     }
54390     case P4_FUNCDEF: {
54391       FuncDef *pDef = pOp->p4.pFunc;
54392       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
54393       break;
54394     }
54395     case P4_INT64: {
54396       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
54397       break;
54398     }
54399     case P4_INT32: {
54400       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
54401       break;
54402     }
54403     case P4_REAL: {
54404       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
54405       break;
54406     }
54407     case P4_MEM: {
54408       Mem *pMem = pOp->p4.pMem;
54409       assert( (pMem->flags & MEM_Null)==0 );
54410       if( pMem->flags & MEM_Str ){
54411         zP4 = pMem->z;
54412       }else if( pMem->flags & MEM_Int ){
54413         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
54414       }else if( pMem->flags & MEM_Real ){
54415         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
54416       }else{
54417         assert( pMem->flags & MEM_Blob );
54418         zP4 = "(blob)";
54419       }
54420       break;
54421     }
54422 #ifndef SQLITE_OMIT_VIRTUALTABLE
54423     case P4_VTAB: {
54424       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
54425       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
54426       break;
54427     }
54428 #endif
54429     case P4_INTARRAY: {
54430       sqlite3_snprintf(nTemp, zTemp, "intarray");
54431       break;
54432     }
54433     case P4_SUBPROGRAM: {
54434       sqlite3_snprintf(nTemp, zTemp, "program");
54435       break;
54436     }
54437     default: {
54438       zP4 = pOp->p4.z;
54439       if( zP4==0 ){
54440         zP4 = zTemp;
54441         zTemp[0] = 0;
54442       }
54443     }
54444   }
54445   assert( zP4!=0 );
54446   return zP4;
54447 }
54448 #endif
54449
54450 /*
54451 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
54452 **
54453 ** The prepared statement has to know in advance which Btree objects
54454 ** will be used so that it can acquire mutexes on them all in sorted
54455 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
54456 ** in order (and released in reverse order) to avoid deadlocks.
54457 */
54458 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
54459   int mask;
54460   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
54461   assert( i<(int)sizeof(p->btreeMask)*8 );
54462   mask = ((u32)1)<<i;
54463   if( (p->btreeMask & mask)==0 ){
54464     p->btreeMask |= mask;
54465     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
54466   }
54467 }
54468
54469
54470 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
54471 /*
54472 ** Print a single opcode.  This routine is used for debugging only.
54473 */
54474 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
54475   char *zP4;
54476   char zPtr[50];
54477   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
54478   if( pOut==0 ) pOut = stdout;
54479   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
54480   fprintf(pOut, zFormat1, pc, 
54481       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
54482 #ifdef SQLITE_DEBUG
54483       pOp->zComment ? pOp->zComment : ""
54484 #else
54485       ""
54486 #endif
54487   );
54488   fflush(pOut);
54489 }
54490 #endif
54491
54492 /*
54493 ** Release an array of N Mem elements
54494 */
54495 static void releaseMemArray(Mem *p, int N){
54496   if( p && N ){
54497     Mem *pEnd;
54498     sqlite3 *db = p->db;
54499     u8 malloc_failed = db->mallocFailed;
54500     for(pEnd=&p[N]; p<pEnd; p++){
54501       assert( (&p[1])==pEnd || p[0].db==p[1].db );
54502
54503       /* This block is really an inlined version of sqlite3VdbeMemRelease()
54504       ** that takes advantage of the fact that the memory cell value is 
54505       ** being set to NULL after releasing any dynamic resources.
54506       **
54507       ** The justification for duplicating code is that according to 
54508       ** callgrind, this causes a certain test case to hit the CPU 4.7 
54509       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
54510       ** sqlite3MemRelease() were called from here. With -O2, this jumps
54511       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
54512       ** with no indexes using a single prepared INSERT statement, bind() 
54513       ** and reset(). Inserts are grouped into a transaction.
54514       */
54515       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
54516         sqlite3VdbeMemRelease(p);
54517       }else if( p->zMalloc ){
54518         sqlite3DbFree(db, p->zMalloc);
54519         p->zMalloc = 0;
54520       }
54521
54522       p->flags = MEM_Null;
54523     }
54524     db->mallocFailed = malloc_failed;
54525   }
54526 }
54527
54528 /*
54529 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
54530 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
54531 */
54532 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
54533   int i;
54534   Mem *aMem = VdbeFrameMem(p);
54535   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
54536   for(i=0; i<p->nChildCsr; i++){
54537     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
54538   }
54539   releaseMemArray(aMem, p->nChildMem);
54540   sqlite3DbFree(p->v->db, p);
54541 }
54542
54543 #ifndef SQLITE_OMIT_EXPLAIN
54544 /*
54545 ** Give a listing of the program in the virtual machine.
54546 **
54547 ** The interface is the same as sqlite3VdbeExec().  But instead of
54548 ** running the code, it invokes the callback once for each instruction.
54549 ** This feature is used to implement "EXPLAIN".
54550 **
54551 ** When p->explain==1, each instruction is listed.  When
54552 ** p->explain==2, only OP_Explain instructions are listed and these
54553 ** are shown in a different format.  p->explain==2 is used to implement
54554 ** EXPLAIN QUERY PLAN.
54555 **
54556 ** When p->explain==1, first the main program is listed, then each of
54557 ** the trigger subprograms are listed one by one.
54558 */
54559 SQLITE_PRIVATE int sqlite3VdbeList(
54560   Vdbe *p                   /* The VDBE */
54561 ){
54562   int nRow;                            /* Stop when row count reaches this */
54563   int nSub = 0;                        /* Number of sub-vdbes seen so far */
54564   SubProgram **apSub = 0;              /* Array of sub-vdbes */
54565   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
54566   sqlite3 *db = p->db;                 /* The database connection */
54567   int i;                               /* Loop counter */
54568   int rc = SQLITE_OK;                  /* Return code */
54569   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
54570
54571   assert( p->explain );
54572   assert( p->magic==VDBE_MAGIC_RUN );
54573   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
54574
54575   /* Even though this opcode does not use dynamic strings for
54576   ** the result, result columns may become dynamic if the user calls
54577   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
54578   */
54579   releaseMemArray(pMem, 8);
54580
54581   if( p->rc==SQLITE_NOMEM ){
54582     /* This happens if a malloc() inside a call to sqlite3_column_text() or
54583     ** sqlite3_column_text16() failed.  */
54584     db->mallocFailed = 1;
54585     return SQLITE_ERROR;
54586   }
54587
54588   /* When the number of output rows reaches nRow, that means the
54589   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
54590   ** nRow is the sum of the number of rows in the main program, plus
54591   ** the sum of the number of rows in all trigger subprograms encountered
54592   ** so far.  The nRow value will increase as new trigger subprograms are
54593   ** encountered, but p->pc will eventually catch up to nRow.
54594   */
54595   nRow = p->nOp;
54596   if( p->explain==1 ){
54597     /* The first 8 memory cells are used for the result set.  So we will
54598     ** commandeer the 9th cell to use as storage for an array of pointers
54599     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
54600     ** cells.  */
54601     assert( p->nMem>9 );
54602     pSub = &p->aMem[9];
54603     if( pSub->flags&MEM_Blob ){
54604       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
54605       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
54606       nSub = pSub->n/sizeof(Vdbe*);
54607       apSub = (SubProgram **)pSub->z;
54608     }
54609     for(i=0; i<nSub; i++){
54610       nRow += apSub[i]->nOp;
54611     }
54612   }
54613
54614   do{
54615     i = p->pc++;
54616   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
54617   if( i>=nRow ){
54618     p->rc = SQLITE_OK;
54619     rc = SQLITE_DONE;
54620   }else if( db->u1.isInterrupted ){
54621     p->rc = SQLITE_INTERRUPT;
54622     rc = SQLITE_ERROR;
54623     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
54624   }else{
54625     char *z;
54626     Op *pOp;
54627     if( i<p->nOp ){
54628       /* The output line number is small enough that we are still in the
54629       ** main program. */
54630       pOp = &p->aOp[i];
54631     }else{
54632       /* We are currently listing subprograms.  Figure out which one and
54633       ** pick up the appropriate opcode. */
54634       int j;
54635       i -= p->nOp;
54636       for(j=0; i>=apSub[j]->nOp; j++){
54637         i -= apSub[j]->nOp;
54638       }
54639       pOp = &apSub[j]->aOp[i];
54640     }
54641     if( p->explain==1 ){
54642       pMem->flags = MEM_Int;
54643       pMem->type = SQLITE_INTEGER;
54644       pMem->u.i = i;                                /* Program counter */
54645       pMem++;
54646   
54647       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
54648       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
54649       assert( pMem->z!=0 );
54650       pMem->n = sqlite3Strlen30(pMem->z);
54651       pMem->type = SQLITE_TEXT;
54652       pMem->enc = SQLITE_UTF8;
54653       pMem++;
54654
54655       /* When an OP_Program opcode is encounter (the only opcode that has
54656       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
54657       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
54658       ** has not already been seen.
54659       */
54660       if( pOp->p4type==P4_SUBPROGRAM ){
54661         int nByte = (nSub+1)*sizeof(SubProgram*);
54662         int j;
54663         for(j=0; j<nSub; j++){
54664           if( apSub[j]==pOp->p4.pProgram ) break;
54665         }
54666         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
54667           apSub = (SubProgram **)pSub->z;
54668           apSub[nSub++] = pOp->p4.pProgram;
54669           pSub->flags |= MEM_Blob;
54670           pSub->n = nSub*sizeof(SubProgram*);
54671         }
54672       }
54673     }
54674
54675     pMem->flags = MEM_Int;
54676     pMem->u.i = pOp->p1;                          /* P1 */
54677     pMem->type = SQLITE_INTEGER;
54678     pMem++;
54679
54680     pMem->flags = MEM_Int;
54681     pMem->u.i = pOp->p2;                          /* P2 */
54682     pMem->type = SQLITE_INTEGER;
54683     pMem++;
54684
54685     if( p->explain==1 ){
54686       pMem->flags = MEM_Int;
54687       pMem->u.i = pOp->p3;                          /* P3 */
54688       pMem->type = SQLITE_INTEGER;
54689       pMem++;
54690     }
54691
54692     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
54693       assert( p->db->mallocFailed );
54694       return SQLITE_ERROR;
54695     }
54696     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54697     z = displayP4(pOp, pMem->z, 32);
54698     if( z!=pMem->z ){
54699       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
54700     }else{
54701       assert( pMem->z!=0 );
54702       pMem->n = sqlite3Strlen30(pMem->z);
54703       pMem->enc = SQLITE_UTF8;
54704     }
54705     pMem->type = SQLITE_TEXT;
54706     pMem++;
54707
54708     if( p->explain==1 ){
54709       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
54710         assert( p->db->mallocFailed );
54711         return SQLITE_ERROR;
54712       }
54713       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54714       pMem->n = 2;
54715       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
54716       pMem->type = SQLITE_TEXT;
54717       pMem->enc = SQLITE_UTF8;
54718       pMem++;
54719   
54720 #ifdef SQLITE_DEBUG
54721       if( pOp->zComment ){
54722         pMem->flags = MEM_Str|MEM_Term;
54723         pMem->z = pOp->zComment;
54724         pMem->n = sqlite3Strlen30(pMem->z);
54725         pMem->enc = SQLITE_UTF8;
54726         pMem->type = SQLITE_TEXT;
54727       }else
54728 #endif
54729       {
54730         pMem->flags = MEM_Null;                       /* Comment */
54731         pMem->type = SQLITE_NULL;
54732       }
54733     }
54734
54735     p->nResColumn = 8 - 5*(p->explain-1);
54736     p->rc = SQLITE_OK;
54737     rc = SQLITE_ROW;
54738   }
54739   return rc;
54740 }
54741 #endif /* SQLITE_OMIT_EXPLAIN */
54742
54743 #ifdef SQLITE_DEBUG
54744 /*
54745 ** Print the SQL that was used to generate a VDBE program.
54746 */
54747 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
54748   int nOp = p->nOp;
54749   VdbeOp *pOp;
54750   if( nOp<1 ) return;
54751   pOp = &p->aOp[0];
54752   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54753     const char *z = pOp->p4.z;
54754     while( sqlite3Isspace(*z) ) z++;
54755     printf("SQL: [%s]\n", z);
54756   }
54757 }
54758 #endif
54759
54760 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
54761 /*
54762 ** Print an IOTRACE message showing SQL content.
54763 */
54764 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
54765   int nOp = p->nOp;
54766   VdbeOp *pOp;
54767   if( sqlite3IoTrace==0 ) return;
54768   if( nOp<1 ) return;
54769   pOp = &p->aOp[0];
54770   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54771     int i, j;
54772     char z[1000];
54773     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
54774     for(i=0; sqlite3Isspace(z[i]); i++){}
54775     for(j=0; z[i]; i++){
54776       if( sqlite3Isspace(z[i]) ){
54777         if( z[i-1]!=' ' ){
54778           z[j++] = ' ';
54779         }
54780       }else{
54781         z[j++] = z[i];
54782       }
54783     }
54784     z[j] = 0;
54785     sqlite3IoTrace("SQL %s\n", z);
54786   }
54787 }
54788 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
54789
54790 /*
54791 ** Allocate space from a fixed size buffer and return a pointer to
54792 ** that space.  If insufficient space is available, return NULL.
54793 **
54794 ** The pBuf parameter is the initial value of a pointer which will
54795 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
54796 ** NULL, it means that memory space has already been allocated and that
54797 ** this routine should not allocate any new memory.  When pBuf is not
54798 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
54799 ** is NULL.
54800 **
54801 ** nByte is the number of bytes of space needed.
54802 **
54803 ** *ppFrom points to available space and pEnd points to the end of the
54804 ** available space.  When space is allocated, *ppFrom is advanced past
54805 ** the end of the allocated space.
54806 **
54807 ** *pnByte is a counter of the number of bytes of space that have failed
54808 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
54809 ** request, then increment *pnByte by the amount of the request.
54810 */
54811 static void *allocSpace(
54812   void *pBuf,          /* Where return pointer will be stored */
54813   int nByte,           /* Number of bytes to allocate */
54814   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
54815   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
54816   int *pnByte          /* If allocation cannot be made, increment *pnByte */
54817 ){
54818   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
54819   if( pBuf ) return pBuf;
54820   nByte = ROUND8(nByte);
54821   if( &(*ppFrom)[nByte] <= pEnd ){
54822     pBuf = (void*)*ppFrom;
54823     *ppFrom += nByte;
54824   }else{
54825     *pnByte += nByte;
54826   }
54827   return pBuf;
54828 }
54829
54830 /*
54831 ** Prepare a virtual machine for execution.  This involves things such
54832 ** as allocating stack space and initializing the program counter.
54833 ** After the VDBE has be prepped, it can be executed by one or more
54834 ** calls to sqlite3VdbeExec().  
54835 **
54836 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
54837 ** VDBE_MAGIC_RUN.
54838 **
54839 ** This function may be called more than once on a single virtual machine.
54840 ** The first call is made while compiling the SQL statement. Subsequent
54841 ** calls are made as part of the process of resetting a statement to be
54842 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
54843 ** and isExplain parameters are only passed correct values the first time
54844 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
54845 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
54846 */
54847 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
54848   Vdbe *p,                       /* The VDBE */
54849   int nVar,                      /* Number of '?' see in the SQL statement */
54850   int nMem,                      /* Number of memory cells to allocate */
54851   int nCursor,                   /* Number of cursors to allocate */
54852   int nArg,                      /* Maximum number of args in SubPrograms */
54853   int isExplain,                 /* True if the EXPLAIN keywords is present */
54854   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
54855 ){
54856   int n;
54857   sqlite3 *db = p->db;
54858
54859   assert( p!=0 );
54860   assert( p->magic==VDBE_MAGIC_INIT );
54861
54862   /* There should be at least one opcode.
54863   */
54864   assert( p->nOp>0 );
54865
54866   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
54867   p->magic = VDBE_MAGIC_RUN;
54868
54869   /* For each cursor required, also allocate a memory cell. Memory
54870   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
54871   ** the vdbe program. Instead they are used to allocate space for
54872   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
54873   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
54874   ** stores the blob of memory associated with cursor 1, etc.
54875   **
54876   ** See also: allocateCursor().
54877   */
54878   nMem += nCursor;
54879
54880   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
54881   ** an array to marshal SQL function arguments in. This is only done the
54882   ** first time this function is called for a given VDBE, not when it is
54883   ** being called from sqlite3_reset() to reset the virtual machine.
54884   */
54885   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
54886     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
54887     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
54888     int nByte;                              /* How much extra memory needed */
54889
54890     resolveP2Values(p, &nArg);
54891     p->usesStmtJournal = (u8)usesStmtJournal;
54892     if( isExplain && nMem<10 ){
54893       nMem = 10;
54894     }
54895     memset(zCsr, 0, zEnd-zCsr);
54896     zCsr += (zCsr - (u8*)0)&7;
54897     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
54898
54899     /* Memory for registers, parameters, cursor, etc, is allocated in two
54900     ** passes.  On the first pass, we try to reuse unused space at the 
54901     ** end of the opcode array.  If we are unable to satisfy all memory
54902     ** requirements by reusing the opcode array tail, then the second
54903     ** pass will fill in the rest using a fresh allocation.  
54904     **
54905     ** This two-pass approach that reuses as much memory as possible from
54906     ** the leftover space at the end of the opcode array can significantly
54907     ** reduce the amount of memory held by a prepared statement.
54908     */
54909     do {
54910       nByte = 0;
54911       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
54912       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
54913       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
54914       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
54915       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
54916                             &zCsr, zEnd, &nByte);
54917       if( nByte ){
54918         p->pFree = sqlite3DbMallocZero(db, nByte);
54919       }
54920       zCsr = p->pFree;
54921       zEnd = &zCsr[nByte];
54922     }while( nByte && !db->mallocFailed );
54923
54924     p->nCursor = (u16)nCursor;
54925     if( p->aVar ){
54926       p->nVar = (ynVar)nVar;
54927       for(n=0; n<nVar; n++){
54928         p->aVar[n].flags = MEM_Null;
54929         p->aVar[n].db = db;
54930       }
54931     }
54932     if( p->aMem ){
54933       p->aMem--;                      /* aMem[] goes from 1..nMem */
54934       p->nMem = nMem;                 /*       not from 0..nMem-1 */
54935       for(n=1; n<=nMem; n++){
54936         p->aMem[n].flags = MEM_Null;
54937         p->aMem[n].db = db;
54938       }
54939     }
54940   }
54941 #ifdef SQLITE_DEBUG
54942   for(n=1; n<p->nMem; n++){
54943     assert( p->aMem[n].db==db );
54944   }
54945 #endif
54946
54947   p->pc = -1;
54948   p->rc = SQLITE_OK;
54949   p->errorAction = OE_Abort;
54950   p->explain |= isExplain;
54951   p->magic = VDBE_MAGIC_RUN;
54952   p->nChange = 0;
54953   p->cacheCtr = 1;
54954   p->minWriteFileFormat = 255;
54955   p->iStatement = 0;
54956   p->nFkConstraint = 0;
54957 #ifdef VDBE_PROFILE
54958   {
54959     int i;
54960     for(i=0; i<p->nOp; i++){
54961       p->aOp[i].cnt = 0;
54962       p->aOp[i].cycles = 0;
54963     }
54964   }
54965 #endif
54966 }
54967
54968 /*
54969 ** Close a VDBE cursor and release all the resources that cursor 
54970 ** happens to hold.
54971 */
54972 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
54973   if( pCx==0 ){
54974     return;
54975   }
54976   if( pCx->pBt ){
54977     sqlite3BtreeClose(pCx->pBt);
54978     /* The pCx->pCursor will be close automatically, if it exists, by
54979     ** the call above. */
54980   }else if( pCx->pCursor ){
54981     sqlite3BtreeCloseCursor(pCx->pCursor);
54982   }
54983 #ifndef SQLITE_OMIT_VIRTUALTABLE
54984   if( pCx->pVtabCursor ){
54985     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
54986     const sqlite3_module *pModule = pCx->pModule;
54987     p->inVtabMethod = 1;
54988     pModule->xClose(pVtabCursor);
54989     p->inVtabMethod = 0;
54990   }
54991 #endif
54992 }
54993
54994 /*
54995 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
54996 ** is used, for example, when a trigger sub-program is halted to restore
54997 ** control to the main program.
54998 */
54999 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
55000   Vdbe *v = pFrame->v;
55001   v->aOp = pFrame->aOp;
55002   v->nOp = pFrame->nOp;
55003   v->aMem = pFrame->aMem;
55004   v->nMem = pFrame->nMem;
55005   v->apCsr = pFrame->apCsr;
55006   v->nCursor = pFrame->nCursor;
55007   v->db->lastRowid = pFrame->lastRowid;
55008   v->nChange = pFrame->nChange;
55009   return pFrame->pc;
55010 }
55011
55012 /*
55013 ** Close all cursors.
55014 **
55015 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
55016 ** cell array. This is necessary as the memory cell array may contain
55017 ** pointers to VdbeFrame objects, which may in turn contain pointers to
55018 ** open cursors.
55019 */
55020 static void closeAllCursors(Vdbe *p){
55021   if( p->pFrame ){
55022     VdbeFrame *pFrame = p->pFrame;
55023     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
55024     sqlite3VdbeFrameRestore(pFrame);
55025   }
55026   p->pFrame = 0;
55027   p->nFrame = 0;
55028
55029   if( p->apCsr ){
55030     int i;
55031     for(i=0; i<p->nCursor; i++){
55032       VdbeCursor *pC = p->apCsr[i];
55033       if( pC ){
55034         sqlite3VdbeFreeCursor(p, pC);
55035         p->apCsr[i] = 0;
55036       }
55037     }
55038   }
55039   if( p->aMem ){
55040     releaseMemArray(&p->aMem[1], p->nMem);
55041   }
55042 }
55043
55044 /*
55045 ** Clean up the VM after execution.
55046 **
55047 ** This routine will automatically close any cursors, lists, and/or
55048 ** sorters that were left open.  It also deletes the values of
55049 ** variables in the aVar[] array.
55050 */
55051 static void Cleanup(Vdbe *p){
55052   sqlite3 *db = p->db;
55053
55054 #ifdef SQLITE_DEBUG
55055   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
55056   ** Vdbe.aMem[] arrays have already been cleaned up.  */
55057   int i;
55058   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
55059   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
55060 #endif
55061
55062   sqlite3DbFree(db, p->zErrMsg);
55063   p->zErrMsg = 0;
55064   p->pResultSet = 0;
55065 }
55066
55067 /*
55068 ** Set the number of result columns that will be returned by this SQL
55069 ** statement. This is now set at compile time, rather than during
55070 ** execution of the vdbe program so that sqlite3_column_count() can
55071 ** be called on an SQL statement before sqlite3_step().
55072 */
55073 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
55074   Mem *pColName;
55075   int n;
55076   sqlite3 *db = p->db;
55077
55078   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55079   sqlite3DbFree(db, p->aColName);
55080   n = nResColumn*COLNAME_N;
55081   p->nResColumn = (u16)nResColumn;
55082   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
55083   if( p->aColName==0 ) return;
55084   while( n-- > 0 ){
55085     pColName->flags = MEM_Null;
55086     pColName->db = p->db;
55087     pColName++;
55088   }
55089 }
55090
55091 /*
55092 ** Set the name of the idx'th column to be returned by the SQL statement.
55093 ** zName must be a pointer to a nul terminated string.
55094 **
55095 ** This call must be made after a call to sqlite3VdbeSetNumCols().
55096 **
55097 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
55098 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
55099 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
55100 */
55101 SQLITE_PRIVATE int sqlite3VdbeSetColName(
55102   Vdbe *p,                         /* Vdbe being configured */
55103   int idx,                         /* Index of column zName applies to */
55104   int var,                         /* One of the COLNAME_* constants */
55105   const char *zName,               /* Pointer to buffer containing name */
55106   void (*xDel)(void*)              /* Memory management strategy for zName */
55107 ){
55108   int rc;
55109   Mem *pColName;
55110   assert( idx<p->nResColumn );
55111   assert( var<COLNAME_N );
55112   if( p->db->mallocFailed ){
55113     assert( !zName || xDel!=SQLITE_DYNAMIC );
55114     return SQLITE_NOMEM;
55115   }
55116   assert( p->aColName!=0 );
55117   pColName = &(p->aColName[idx+var*p->nResColumn]);
55118   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
55119   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
55120   return rc;
55121 }
55122
55123 /*
55124 ** A read or write transaction may or may not be active on database handle
55125 ** db. If a transaction is active, commit it. If there is a
55126 ** write-transaction spanning more than one database file, this routine
55127 ** takes care of the master journal trickery.
55128 */
55129 static int vdbeCommit(sqlite3 *db, Vdbe *p){
55130   int i;
55131   int nTrans = 0;  /* Number of databases with an active write-transaction */
55132   int rc = SQLITE_OK;
55133   int needXcommit = 0;
55134
55135 #ifdef SQLITE_OMIT_VIRTUALTABLE
55136   /* With this option, sqlite3VtabSync() is defined to be simply 
55137   ** SQLITE_OK so p is not used. 
55138   */
55139   UNUSED_PARAMETER(p);
55140 #endif
55141
55142   /* Before doing anything else, call the xSync() callback for any
55143   ** virtual module tables written in this transaction. This has to
55144   ** be done before determining whether a master journal file is 
55145   ** required, as an xSync() callback may add an attached database
55146   ** to the transaction.
55147   */
55148   rc = sqlite3VtabSync(db, &p->zErrMsg);
55149   if( rc!=SQLITE_OK ){
55150     return rc;
55151   }
55152
55153   /* This loop determines (a) if the commit hook should be invoked and
55154   ** (b) how many database files have open write transactions, not 
55155   ** including the temp database. (b) is important because if more than 
55156   ** one database file has an open write transaction, a master journal
55157   ** file is required for an atomic commit.
55158   */ 
55159   for(i=0; i<db->nDb; i++){ 
55160     Btree *pBt = db->aDb[i].pBt;
55161     if( sqlite3BtreeIsInTrans(pBt) ){
55162       needXcommit = 1;
55163       if( i!=1 ) nTrans++;
55164     }
55165   }
55166
55167   /* If there are any write-transactions at all, invoke the commit hook */
55168   if( needXcommit && db->xCommitCallback ){
55169     rc = db->xCommitCallback(db->pCommitArg);
55170     if( rc ){
55171       return SQLITE_CONSTRAINT;
55172     }
55173   }
55174
55175   /* The simple case - no more than one database file (not counting the
55176   ** TEMP database) has a transaction active.   There is no need for the
55177   ** master-journal.
55178   **
55179   ** If the return value of sqlite3BtreeGetFilename() is a zero length
55180   ** string, it means the main database is :memory: or a temp file.  In 
55181   ** that case we do not support atomic multi-file commits, so use the 
55182   ** simple case then too.
55183   */
55184   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
55185    || nTrans<=1
55186   ){
55187     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
55188       Btree *pBt = db->aDb[i].pBt;
55189       if( pBt ){
55190         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
55191       }
55192     }
55193
55194     /* Do the commit only if all databases successfully complete phase 1. 
55195     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
55196     ** IO error while deleting or truncating a journal file. It is unlikely,
55197     ** but could happen. In this case abandon processing and return the error.
55198     */
55199     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
55200       Btree *pBt = db->aDb[i].pBt;
55201       if( pBt ){
55202         rc = sqlite3BtreeCommitPhaseTwo(pBt);
55203       }
55204     }
55205     if( rc==SQLITE_OK ){
55206       sqlite3VtabCommit(db);
55207     }
55208   }
55209
55210   /* The complex case - There is a multi-file write-transaction active.
55211   ** This requires a master journal file to ensure the transaction is
55212   ** committed atomicly.
55213   */
55214 #ifndef SQLITE_OMIT_DISKIO
55215   else{
55216     sqlite3_vfs *pVfs = db->pVfs;
55217     int needSync = 0;
55218     char *zMaster = 0;   /* File-name for the master journal */
55219     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
55220     sqlite3_file *pMaster = 0;
55221     i64 offset = 0;
55222     int res;
55223
55224     /* Select a master journal file name */
55225     do {
55226       u32 iRandom;
55227       sqlite3DbFree(db, zMaster);
55228       sqlite3_randomness(sizeof(iRandom), &iRandom);
55229       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
55230       if( !zMaster ){
55231         return SQLITE_NOMEM;
55232       }
55233       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
55234     }while( rc==SQLITE_OK && res );
55235     if( rc==SQLITE_OK ){
55236       /* Open the master journal. */
55237       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
55238           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
55239           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
55240       );
55241     }
55242     if( rc!=SQLITE_OK ){
55243       sqlite3DbFree(db, zMaster);
55244       return rc;
55245     }
55246  
55247     /* Write the name of each database file in the transaction into the new
55248     ** master journal file. If an error occurs at this point close
55249     ** and delete the master journal file. All the individual journal files
55250     ** still have 'null' as the master journal pointer, so they will roll
55251     ** back independently if a failure occurs.
55252     */
55253     for(i=0; i<db->nDb; i++){
55254       Btree *pBt = db->aDb[i].pBt;
55255       if( sqlite3BtreeIsInTrans(pBt) ){
55256         char const *zFile = sqlite3BtreeGetJournalname(pBt);
55257         if( zFile==0 || zFile[0]==0 ){
55258           continue;  /* Ignore TEMP and :memory: databases */
55259         }
55260         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
55261           needSync = 1;
55262         }
55263         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
55264         offset += sqlite3Strlen30(zFile)+1;
55265         if( rc!=SQLITE_OK ){
55266           sqlite3OsCloseFree(pMaster);
55267           sqlite3OsDelete(pVfs, zMaster, 0);
55268           sqlite3DbFree(db, zMaster);
55269           return rc;
55270         }
55271       }
55272     }
55273
55274     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
55275     ** flag is set this is not required.
55276     */
55277     if( needSync 
55278      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
55279      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
55280     ){
55281       sqlite3OsCloseFree(pMaster);
55282       sqlite3OsDelete(pVfs, zMaster, 0);
55283       sqlite3DbFree(db, zMaster);
55284       return rc;
55285     }
55286
55287     /* Sync all the db files involved in the transaction. The same call
55288     ** sets the master journal pointer in each individual journal. If
55289     ** an error occurs here, do not delete the master journal file.
55290     **
55291     ** If the error occurs during the first call to
55292     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
55293     ** master journal file will be orphaned. But we cannot delete it,
55294     ** in case the master journal file name was written into the journal
55295     ** file before the failure occurred.
55296     */
55297     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
55298       Btree *pBt = db->aDb[i].pBt;
55299       if( pBt ){
55300         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
55301       }
55302     }
55303     sqlite3OsCloseFree(pMaster);
55304     if( rc!=SQLITE_OK ){
55305       sqlite3DbFree(db, zMaster);
55306       return rc;
55307     }
55308
55309     /* Delete the master journal file. This commits the transaction. After
55310     ** doing this the directory is synced again before any individual
55311     ** transaction files are deleted.
55312     */
55313     rc = sqlite3OsDelete(pVfs, zMaster, 1);
55314     sqlite3DbFree(db, zMaster);
55315     zMaster = 0;
55316     if( rc ){
55317       return rc;
55318     }
55319
55320     /* All files and directories have already been synced, so the following
55321     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
55322     ** deleting or truncating journals. If something goes wrong while
55323     ** this is happening we don't really care. The integrity of the
55324     ** transaction is already guaranteed, but some stray 'cold' journals
55325     ** may be lying around. Returning an error code won't help matters.
55326     */
55327     disable_simulated_io_errors();
55328     sqlite3BeginBenignMalloc();
55329     for(i=0; i<db->nDb; i++){ 
55330       Btree *pBt = db->aDb[i].pBt;
55331       if( pBt ){
55332         sqlite3BtreeCommitPhaseTwo(pBt);
55333       }
55334     }
55335     sqlite3EndBenignMalloc();
55336     enable_simulated_io_errors();
55337
55338     sqlite3VtabCommit(db);
55339   }
55340 #endif
55341
55342   return rc;
55343 }
55344
55345 /* 
55346 ** This routine checks that the sqlite3.activeVdbeCnt count variable
55347 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
55348 ** currently active. An assertion fails if the two counts do not match.
55349 ** This is an internal self-check only - it is not an essential processing
55350 ** step.
55351 **
55352 ** This is a no-op if NDEBUG is defined.
55353 */
55354 #ifndef NDEBUG
55355 static void checkActiveVdbeCnt(sqlite3 *db){
55356   Vdbe *p;
55357   int cnt = 0;
55358   int nWrite = 0;
55359   p = db->pVdbe;
55360   while( p ){
55361     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
55362       cnt++;
55363       if( p->readOnly==0 ) nWrite++;
55364     }
55365     p = p->pNext;
55366   }
55367   assert( cnt==db->activeVdbeCnt );
55368   assert( nWrite==db->writeVdbeCnt );
55369 }
55370 #else
55371 #define checkActiveVdbeCnt(x)
55372 #endif
55373
55374 /*
55375 ** For every Btree that in database connection db which 
55376 ** has been modified, "trip" or invalidate each cursor in
55377 ** that Btree might have been modified so that the cursor
55378 ** can never be used again.  This happens when a rollback
55379 *** occurs.  We have to trip all the other cursors, even
55380 ** cursor from other VMs in different database connections,
55381 ** so that none of them try to use the data at which they
55382 ** were pointing and which now may have been changed due
55383 ** to the rollback.
55384 **
55385 ** Remember that a rollback can delete tables complete and
55386 ** reorder rootpages.  So it is not sufficient just to save
55387 ** the state of the cursor.  We have to invalidate the cursor
55388 ** so that it is never used again.
55389 */
55390 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
55391   int i;
55392   for(i=0; i<db->nDb; i++){
55393     Btree *p = db->aDb[i].pBt;
55394     if( p && sqlite3BtreeIsInTrans(p) ){
55395       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
55396     }
55397   }
55398 }
55399
55400 /*
55401 ** If the Vdbe passed as the first argument opened a statement-transaction,
55402 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
55403 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
55404 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
55405 ** statement transaction is commtted.
55406 **
55407 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
55408 ** Otherwise SQLITE_OK.
55409 */
55410 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
55411   sqlite3 *const db = p->db;
55412   int rc = SQLITE_OK;
55413
55414   /* If p->iStatement is greater than zero, then this Vdbe opened a 
55415   ** statement transaction that should be closed here. The only exception
55416   ** is that an IO error may have occured, causing an emergency rollback.
55417   ** In this case (db->nStatement==0), and there is nothing to do.
55418   */
55419   if( db->nStatement && p->iStatement ){
55420     int i;
55421     const int iSavepoint = p->iStatement-1;
55422
55423     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
55424     assert( db->nStatement>0 );
55425     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
55426
55427     for(i=0; i<db->nDb; i++){ 
55428       int rc2 = SQLITE_OK;
55429       Btree *pBt = db->aDb[i].pBt;
55430       if( pBt ){
55431         if( eOp==SAVEPOINT_ROLLBACK ){
55432           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
55433         }
55434         if( rc2==SQLITE_OK ){
55435           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
55436         }
55437         if( rc==SQLITE_OK ){
55438           rc = rc2;
55439         }
55440       }
55441     }
55442     db->nStatement--;
55443     p->iStatement = 0;
55444
55445     /* If the statement transaction is being rolled back, also restore the 
55446     ** database handles deferred constraint counter to the value it had when 
55447     ** the statement transaction was opened.  */
55448     if( eOp==SAVEPOINT_ROLLBACK ){
55449       db->nDeferredCons = p->nStmtDefCons;
55450     }
55451   }
55452   return rc;
55453 }
55454
55455 /*
55456 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
55457 ** this routine obtains the mutex associated with each BtShared structure
55458 ** that may be accessed by the VM passed as an argument. In doing so it
55459 ** sets the BtShared.db member of each of the BtShared structures, ensuring
55460 ** that the correct busy-handler callback is invoked if required.
55461 **
55462 ** If SQLite is not threadsafe but does support shared-cache mode, then
55463 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
55464 ** of all of BtShared structures accessible via the database handle 
55465 ** associated with the VM. Of course only a subset of these structures
55466 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
55467 ** that subset out, but there is no advantage to doing so.
55468 **
55469 ** If SQLite is not threadsafe and does not support shared-cache mode, this
55470 ** function is a no-op.
55471 */
55472 #ifndef SQLITE_OMIT_SHARED_CACHE
55473 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
55474 #if SQLITE_THREADSAFE
55475   sqlite3BtreeMutexArrayEnter(&p->aMutex);
55476 #else
55477   sqlite3BtreeEnterAll(p->db);
55478 #endif
55479 }
55480 #endif
55481
55482 /*
55483 ** This function is called when a transaction opened by the database 
55484 ** handle associated with the VM passed as an argument is about to be 
55485 ** committed. If there are outstanding deferred foreign key constraint
55486 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
55487 **
55488 ** If there are outstanding FK violations and this function returns 
55489 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
55490 ** an error message to it. Then return SQLITE_ERROR.
55491 */
55492 #ifndef SQLITE_OMIT_FOREIGN_KEY
55493 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
55494   sqlite3 *db = p->db;
55495   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
55496     p->rc = SQLITE_CONSTRAINT;
55497     p->errorAction = OE_Abort;
55498     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
55499     return SQLITE_ERROR;
55500   }
55501   return SQLITE_OK;
55502 }
55503 #endif
55504
55505 /*
55506 ** This routine is called the when a VDBE tries to halt.  If the VDBE
55507 ** has made changes and is in autocommit mode, then commit those
55508 ** changes.  If a rollback is needed, then do the rollback.
55509 **
55510 ** This routine is the only way to move the state of a VM from
55511 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
55512 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
55513 **
55514 ** Return an error code.  If the commit could not complete because of
55515 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
55516 ** means the close did not happen and needs to be repeated.
55517 */
55518 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
55519   int rc;                         /* Used to store transient return codes */
55520   sqlite3 *db = p->db;
55521
55522   /* This function contains the logic that determines if a statement or
55523   ** transaction will be committed or rolled back as a result of the
55524   ** execution of this virtual machine. 
55525   **
55526   ** If any of the following errors occur:
55527   **
55528   **     SQLITE_NOMEM
55529   **     SQLITE_IOERR
55530   **     SQLITE_FULL
55531   **     SQLITE_INTERRUPT
55532   **
55533   ** Then the internal cache might have been left in an inconsistent
55534   ** state.  We need to rollback the statement transaction, if there is
55535   ** one, or the complete transaction if there is no statement transaction.
55536   */
55537
55538   if( p->db->mallocFailed ){
55539     p->rc = SQLITE_NOMEM;
55540   }
55541   closeAllCursors(p);
55542   if( p->magic!=VDBE_MAGIC_RUN ){
55543     return SQLITE_OK;
55544   }
55545   checkActiveVdbeCnt(db);
55546
55547   /* No commit or rollback needed if the program never started */
55548   if( p->pc>=0 ){
55549     int mrc;   /* Primary error code from p->rc */
55550     int eStatementOp = 0;
55551     int isSpecialError;            /* Set to true if a 'special' error */
55552
55553     /* Lock all btrees used by the statement */
55554     sqlite3VdbeMutexArrayEnter(p);
55555
55556     /* Check for one of the special errors */
55557     mrc = p->rc & 0xff;
55558     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
55559     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
55560                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
55561     if( isSpecialError ){
55562       /* If the query was read-only, we need do no rollback at all. Otherwise,
55563       ** proceed with the special handling.
55564       */
55565       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
55566         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
55567           eStatementOp = SAVEPOINT_ROLLBACK;
55568         }else{
55569           /* We are forced to roll back the active transaction. Before doing
55570           ** so, abort any other statements this handle currently has active.
55571           */
55572           invalidateCursorsOnModifiedBtrees(db);
55573           sqlite3RollbackAll(db);
55574           sqlite3CloseSavepoints(db);
55575           db->autoCommit = 1;
55576         }
55577       }
55578     }
55579
55580     /* Check for immediate foreign key violations. */
55581     if( p->rc==SQLITE_OK ){
55582       sqlite3VdbeCheckFk(p, 0);
55583     }
55584   
55585     /* If the auto-commit flag is set and this is the only active writer 
55586     ** VM, then we do either a commit or rollback of the current transaction. 
55587     **
55588     ** Note: This block also runs if one of the special errors handled 
55589     ** above has occurred. 
55590     */
55591     if( !sqlite3VtabInSync(db) 
55592      && db->autoCommit 
55593      && db->writeVdbeCnt==(p->readOnly==0) 
55594     ){
55595       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
55596         if( sqlite3VdbeCheckFk(p, 1) ){
55597           sqlite3BtreeMutexArrayLeave(&p->aMutex);
55598           return SQLITE_ERROR;
55599         }
55600         /* The auto-commit flag is true, the vdbe program was successful 
55601         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
55602         ** key constraints to hold up the transaction. This means a commit 
55603         ** is required.  */
55604         rc = vdbeCommit(db, p);
55605         if( rc==SQLITE_BUSY ){
55606           sqlite3BtreeMutexArrayLeave(&p->aMutex);
55607           return SQLITE_BUSY;
55608         }else if( rc!=SQLITE_OK ){
55609           p->rc = rc;
55610           sqlite3RollbackAll(db);
55611         }else{
55612           db->nDeferredCons = 0;
55613           sqlite3CommitInternalChanges(db);
55614         }
55615       }else{
55616         sqlite3RollbackAll(db);
55617       }
55618       db->nStatement = 0;
55619     }else if( eStatementOp==0 ){
55620       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
55621         eStatementOp = SAVEPOINT_RELEASE;
55622       }else if( p->errorAction==OE_Abort ){
55623         eStatementOp = SAVEPOINT_ROLLBACK;
55624       }else{
55625         invalidateCursorsOnModifiedBtrees(db);
55626         sqlite3RollbackAll(db);
55627         sqlite3CloseSavepoints(db);
55628         db->autoCommit = 1;
55629       }
55630     }
55631   
55632     /* If eStatementOp is non-zero, then a statement transaction needs to
55633     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
55634     ** do so. If this operation returns an error, and the current statement
55635     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
55636     ** current statement error code.
55637     **
55638     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
55639     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
55640     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
55641     ** the following code.
55642     */
55643     if( eStatementOp ){
55644       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
55645       if( rc ){
55646         assert( eStatementOp==SAVEPOINT_ROLLBACK );
55647         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
55648           p->rc = rc;
55649           sqlite3DbFree(db, p->zErrMsg);
55650           p->zErrMsg = 0;
55651         }
55652         invalidateCursorsOnModifiedBtrees(db);
55653         sqlite3RollbackAll(db);
55654         sqlite3CloseSavepoints(db);
55655         db->autoCommit = 1;
55656       }
55657     }
55658   
55659     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
55660     ** has been rolled back, update the database connection change-counter. 
55661     */
55662     if( p->changeCntOn ){
55663       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
55664         sqlite3VdbeSetChanges(db, p->nChange);
55665       }else{
55666         sqlite3VdbeSetChanges(db, 0);
55667       }
55668       p->nChange = 0;
55669     }
55670   
55671     /* Rollback or commit any schema changes that occurred. */
55672     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
55673       sqlite3ResetInternalSchema(db, 0);
55674       db->flags = (db->flags | SQLITE_InternChanges);
55675     }
55676
55677     /* Release the locks */
55678     sqlite3BtreeMutexArrayLeave(&p->aMutex);
55679   }
55680
55681   /* We have successfully halted and closed the VM.  Record this fact. */
55682   if( p->pc>=0 ){
55683     db->activeVdbeCnt--;
55684     if( !p->readOnly ){
55685       db->writeVdbeCnt--;
55686     }
55687     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
55688   }
55689   p->magic = VDBE_MAGIC_HALT;
55690   checkActiveVdbeCnt(db);
55691   if( p->db->mallocFailed ){
55692     p->rc = SQLITE_NOMEM;
55693   }
55694
55695   /* If the auto-commit flag is set to true, then any locks that were held
55696   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
55697   ** to invoke any required unlock-notify callbacks.
55698   */
55699   if( db->autoCommit ){
55700     sqlite3ConnectionUnlocked(db);
55701   }
55702
55703   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
55704   return SQLITE_OK;
55705 }
55706
55707
55708 /*
55709 ** Each VDBE holds the result of the most recent sqlite3_step() call
55710 ** in p->rc.  This routine sets that result back to SQLITE_OK.
55711 */
55712 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
55713   p->rc = SQLITE_OK;
55714 }
55715
55716 /*
55717 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
55718 ** Write any error messages into *pzErrMsg.  Return the result code.
55719 **
55720 ** After this routine is run, the VDBE should be ready to be executed
55721 ** again.
55722 **
55723 ** To look at it another way, this routine resets the state of the
55724 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
55725 ** VDBE_MAGIC_INIT.
55726 */
55727 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
55728   sqlite3 *db;
55729   db = p->db;
55730
55731   /* If the VM did not run to completion or if it encountered an
55732   ** error, then it might not have been halted properly.  So halt
55733   ** it now.
55734   */
55735   sqlite3VdbeHalt(p);
55736
55737   /* If the VDBE has be run even partially, then transfer the error code
55738   ** and error message from the VDBE into the main database structure.  But
55739   ** if the VDBE has just been set to run but has not actually executed any
55740   ** instructions yet, leave the main database error information unchanged.
55741   */
55742   if( p->pc>=0 ){
55743     if( p->zErrMsg ){
55744       sqlite3BeginBenignMalloc();
55745       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
55746       sqlite3EndBenignMalloc();
55747       db->errCode = p->rc;
55748       sqlite3DbFree(db, p->zErrMsg);
55749       p->zErrMsg = 0;
55750     }else if( p->rc ){
55751       sqlite3Error(db, p->rc, 0);
55752     }else{
55753       sqlite3Error(db, SQLITE_OK, 0);
55754     }
55755     if( p->runOnlyOnce ) p->expired = 1;
55756   }else if( p->rc && p->expired ){
55757     /* The expired flag was set on the VDBE before the first call
55758     ** to sqlite3_step(). For consistency (since sqlite3_step() was
55759     ** called), set the database error in this case as well.
55760     */
55761     sqlite3Error(db, p->rc, 0);
55762     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
55763     sqlite3DbFree(db, p->zErrMsg);
55764     p->zErrMsg = 0;
55765   }
55766
55767   /* Reclaim all memory used by the VDBE
55768   */
55769   Cleanup(p);
55770
55771   /* Save profiling information from this VDBE run.
55772   */
55773 #ifdef VDBE_PROFILE
55774   {
55775     FILE *out = fopen("vdbe_profile.out", "a");
55776     if( out ){
55777       int i;
55778       fprintf(out, "---- ");
55779       for(i=0; i<p->nOp; i++){
55780         fprintf(out, "%02x", p->aOp[i].opcode);
55781       }
55782       fprintf(out, "\n");
55783       for(i=0; i<p->nOp; i++){
55784         fprintf(out, "%6d %10lld %8lld ",
55785            p->aOp[i].cnt,
55786            p->aOp[i].cycles,
55787            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
55788         );
55789         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
55790       }
55791       fclose(out);
55792     }
55793   }
55794 #endif
55795   p->magic = VDBE_MAGIC_INIT;
55796   return p->rc & db->errMask;
55797 }
55798  
55799 /*
55800 ** Clean up and delete a VDBE after execution.  Return an integer which is
55801 ** the result code.  Write any error message text into *pzErrMsg.
55802 */
55803 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
55804   int rc = SQLITE_OK;
55805   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
55806     rc = sqlite3VdbeReset(p);
55807     assert( (rc & p->db->errMask)==rc );
55808   }
55809   sqlite3VdbeDelete(p);
55810   return rc;
55811 }
55812
55813 /*
55814 ** Call the destructor for each auxdata entry in pVdbeFunc for which
55815 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
55816 ** are always destroyed.  To destroy all auxdata entries, call this
55817 ** routine with mask==0.
55818 */
55819 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
55820   int i;
55821   for(i=0; i<pVdbeFunc->nAux; i++){
55822     struct AuxData *pAux = &pVdbeFunc->apAux[i];
55823     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
55824       if( pAux->xDelete ){
55825         pAux->xDelete(pAux->pAux);
55826       }
55827       pAux->pAux = 0;
55828     }
55829   }
55830 }
55831
55832 /*
55833 ** Delete an entire VDBE.
55834 */
55835 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
55836   sqlite3 *db;
55837
55838   if( NEVER(p==0) ) return;
55839   db = p->db;
55840   if( p->pPrev ){
55841     p->pPrev->pNext = p->pNext;
55842   }else{
55843     assert( db->pVdbe==p );
55844     db->pVdbe = p->pNext;
55845   }
55846   if( p->pNext ){
55847     p->pNext->pPrev = p->pPrev;
55848   }
55849   releaseMemArray(p->aVar, p->nVar);
55850   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55851   vdbeFreeOpArray(db, p->aOp, p->nOp);
55852   sqlite3DbFree(db, p->aLabel);
55853   sqlite3DbFree(db, p->aColName);
55854   sqlite3DbFree(db, p->zSql);
55855   p->magic = VDBE_MAGIC_DEAD;
55856   sqlite3DbFree(db, p->pFree);
55857   p->db = 0;
55858   sqlite3DbFree(db, p);
55859 }
55860
55861 /*
55862 ** Make sure the cursor p is ready to read or write the row to which it
55863 ** was last positioned.  Return an error code if an OOM fault or I/O error
55864 ** prevents us from positioning the cursor to its correct position.
55865 **
55866 ** If a MoveTo operation is pending on the given cursor, then do that
55867 ** MoveTo now.  If no move is pending, check to see if the row has been
55868 ** deleted out from under the cursor and if it has, mark the row as
55869 ** a NULL row.
55870 **
55871 ** If the cursor is already pointing to the correct row and that row has
55872 ** not been deleted out from under the cursor, then this routine is a no-op.
55873 */
55874 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
55875   if( p->deferredMoveto ){
55876     int res, rc;
55877 #ifdef SQLITE_TEST
55878     extern int sqlite3_search_count;
55879 #endif
55880     assert( p->isTable );
55881     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
55882     if( rc ) return rc;
55883     p->lastRowid = p->movetoTarget;
55884     p->rowidIsValid = ALWAYS(res==0) ?1:0;
55885     if( NEVER(res<0) ){
55886       rc = sqlite3BtreeNext(p->pCursor, &res);
55887       if( rc ) return rc;
55888     }
55889 #ifdef SQLITE_TEST
55890     sqlite3_search_count++;
55891 #endif
55892     p->deferredMoveto = 0;
55893     p->cacheStatus = CACHE_STALE;
55894   }else if( ALWAYS(p->pCursor) ){
55895     int hasMoved;
55896     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
55897     if( rc ) return rc;
55898     if( hasMoved ){
55899       p->cacheStatus = CACHE_STALE;
55900       p->nullRow = 1;
55901     }
55902   }
55903   return SQLITE_OK;
55904 }
55905
55906 /*
55907 ** The following functions:
55908 **
55909 ** sqlite3VdbeSerialType()
55910 ** sqlite3VdbeSerialTypeLen()
55911 ** sqlite3VdbeSerialLen()
55912 ** sqlite3VdbeSerialPut()
55913 ** sqlite3VdbeSerialGet()
55914 **
55915 ** encapsulate the code that serializes values for storage in SQLite
55916 ** data and index records. Each serialized value consists of a
55917 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
55918 ** integer, stored as a varint.
55919 **
55920 ** In an SQLite index record, the serial type is stored directly before
55921 ** the blob of data that it corresponds to. In a table record, all serial
55922 ** types are stored at the start of the record, and the blobs of data at
55923 ** the end. Hence these functions allow the caller to handle the
55924 ** serial-type and data blob seperately.
55925 **
55926 ** The following table describes the various storage classes for data:
55927 **
55928 **   serial type        bytes of data      type
55929 **   --------------     ---------------    ---------------
55930 **      0                     0            NULL
55931 **      1                     1            signed integer
55932 **      2                     2            signed integer
55933 **      3                     3            signed integer
55934 **      4                     4            signed integer
55935 **      5                     6            signed integer
55936 **      6                     8            signed integer
55937 **      7                     8            IEEE float
55938 **      8                     0            Integer constant 0
55939 **      9                     0            Integer constant 1
55940 **     10,11                               reserved for expansion
55941 **    N>=12 and even       (N-12)/2        BLOB
55942 **    N>=13 and odd        (N-13)/2        text
55943 **
55944 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
55945 ** of SQLite will not understand those serial types.
55946 */
55947
55948 /*
55949 ** Return the serial-type for the value stored in pMem.
55950 */
55951 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
55952   int flags = pMem->flags;
55953   int n;
55954
55955   if( flags&MEM_Null ){
55956     return 0;
55957   }
55958   if( flags&MEM_Int ){
55959     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
55960 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
55961     i64 i = pMem->u.i;
55962     u64 u;
55963     if( file_format>=4 && (i&1)==i ){
55964       return 8+(u32)i;
55965     }
55966     u = i<0 ? -i : i;
55967     if( u<=127 ) return 1;
55968     if( u<=32767 ) return 2;
55969     if( u<=8388607 ) return 3;
55970     if( u<=2147483647 ) return 4;
55971     if( u<=MAX_6BYTE ) return 5;
55972     return 6;
55973   }
55974   if( flags&MEM_Real ){
55975     return 7;
55976   }
55977   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
55978   n = pMem->n;
55979   if( flags & MEM_Zero ){
55980     n += pMem->u.nZero;
55981   }
55982   assert( n>=0 );
55983   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
55984 }
55985
55986 /*
55987 ** Return the length of the data corresponding to the supplied serial-type.
55988 */
55989 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
55990   if( serial_type>=12 ){
55991     return (serial_type-12)/2;
55992   }else{
55993     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
55994     return aSize[serial_type];
55995   }
55996 }
55997
55998 /*
55999 ** If we are on an architecture with mixed-endian floating 
56000 ** points (ex: ARM7) then swap the lower 4 bytes with the 
56001 ** upper 4 bytes.  Return the result.
56002 **
56003 ** For most architectures, this is a no-op.
56004 **
56005 ** (later):  It is reported to me that the mixed-endian problem
56006 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
56007 ** that early versions of GCC stored the two words of a 64-bit
56008 ** float in the wrong order.  And that error has been propagated
56009 ** ever since.  The blame is not necessarily with GCC, though.
56010 ** GCC might have just copying the problem from a prior compiler.
56011 ** I am also told that newer versions of GCC that follow a different
56012 ** ABI get the byte order right.
56013 **
56014 ** Developers using SQLite on an ARM7 should compile and run their
56015 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
56016 ** enabled, some asserts below will ensure that the byte order of
56017 ** floating point values is correct.
56018 **
56019 ** (2007-08-30)  Frank van Vugt has studied this problem closely
56020 ** and has send his findings to the SQLite developers.  Frank
56021 ** writes that some Linux kernels offer floating point hardware
56022 ** emulation that uses only 32-bit mantissas instead of a full 
56023 ** 48-bits as required by the IEEE standard.  (This is the
56024 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
56025 ** byte swapping becomes very complicated.  To avoid problems,
56026 ** the necessary byte swapping is carried out using a 64-bit integer
56027 ** rather than a 64-bit float.  Frank assures us that the code here
56028 ** works for him.  We, the developers, have no way to independently
56029 ** verify this, but Frank seems to know what he is talking about
56030 ** so we trust him.
56031 */
56032 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
56033 static u64 floatSwap(u64 in){
56034   union {
56035     u64 r;
56036     u32 i[2];
56037   } u;
56038   u32 t;
56039
56040   u.r = in;
56041   t = u.i[0];
56042   u.i[0] = u.i[1];
56043   u.i[1] = t;
56044   return u.r;
56045 }
56046 # define swapMixedEndianFloat(X)  X = floatSwap(X)
56047 #else
56048 # define swapMixedEndianFloat(X)
56049 #endif
56050
56051 /*
56052 ** Write the serialized data blob for the value stored in pMem into 
56053 ** buf. It is assumed that the caller has allocated sufficient space.
56054 ** Return the number of bytes written.
56055 **
56056 ** nBuf is the amount of space left in buf[].  nBuf must always be
56057 ** large enough to hold the entire field.  Except, if the field is
56058 ** a blob with a zero-filled tail, then buf[] might be just the right
56059 ** size to hold everything except for the zero-filled tail.  If buf[]
56060 ** is only big enough to hold the non-zero prefix, then only write that
56061 ** prefix into buf[].  But if buf[] is large enough to hold both the
56062 ** prefix and the tail then write the prefix and set the tail to all
56063 ** zeros.
56064 **
56065 ** Return the number of bytes actually written into buf[].  The number
56066 ** of bytes in the zero-filled tail is included in the return value only
56067 ** if those bytes were zeroed in buf[].
56068 */ 
56069 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
56070   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
56071   u32 len;
56072
56073   /* Integer and Real */
56074   if( serial_type<=7 && serial_type>0 ){
56075     u64 v;
56076     u32 i;
56077     if( serial_type==7 ){
56078       assert( sizeof(v)==sizeof(pMem->r) );
56079       memcpy(&v, &pMem->r, sizeof(v));
56080       swapMixedEndianFloat(v);
56081     }else{
56082       v = pMem->u.i;
56083     }
56084     len = i = sqlite3VdbeSerialTypeLen(serial_type);
56085     assert( len<=(u32)nBuf );
56086     while( i-- ){
56087       buf[i] = (u8)(v&0xFF);
56088       v >>= 8;
56089     }
56090     return len;
56091   }
56092
56093   /* String or blob */
56094   if( serial_type>=12 ){
56095     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
56096              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
56097     assert( pMem->n<=nBuf );
56098     len = pMem->n;
56099     memcpy(buf, pMem->z, len);
56100     if( pMem->flags & MEM_Zero ){
56101       len += pMem->u.nZero;
56102       assert( nBuf>=0 );
56103       if( len > (u32)nBuf ){
56104         len = (u32)nBuf;
56105       }
56106       memset(&buf[pMem->n], 0, len-pMem->n);
56107     }
56108     return len;
56109   }
56110
56111   /* NULL or constants 0 or 1 */
56112   return 0;
56113 }
56114
56115 /*
56116 ** Deserialize the data blob pointed to by buf as serial type serial_type
56117 ** and store the result in pMem.  Return the number of bytes read.
56118 */ 
56119 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
56120   const unsigned char *buf,     /* Buffer to deserialize from */
56121   u32 serial_type,              /* Serial type to deserialize */
56122   Mem *pMem                     /* Memory cell to write value into */
56123 ){
56124   switch( serial_type ){
56125     case 10:   /* Reserved for future use */
56126     case 11:   /* Reserved for future use */
56127     case 0: {  /* NULL */
56128       pMem->flags = MEM_Null;
56129       break;
56130     }
56131     case 1: { /* 1-byte signed integer */
56132       pMem->u.i = (signed char)buf[0];
56133       pMem->flags = MEM_Int;
56134       return 1;
56135     }
56136     case 2: { /* 2-byte signed integer */
56137       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
56138       pMem->flags = MEM_Int;
56139       return 2;
56140     }
56141     case 3: { /* 3-byte signed integer */
56142       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
56143       pMem->flags = MEM_Int;
56144       return 3;
56145     }
56146     case 4: { /* 4-byte signed integer */
56147       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
56148       pMem->flags = MEM_Int;
56149       return 4;
56150     }
56151     case 5: { /* 6-byte signed integer */
56152       u64 x = (((signed char)buf[0])<<8) | buf[1];
56153       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
56154       x = (x<<32) | y;
56155       pMem->u.i = *(i64*)&x;
56156       pMem->flags = MEM_Int;
56157       return 6;
56158     }
56159     case 6:   /* 8-byte signed integer */
56160     case 7: { /* IEEE floating point */
56161       u64 x;
56162       u32 y;
56163 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
56164       /* Verify that integers and floating point values use the same
56165       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
56166       ** defined that 64-bit floating point values really are mixed
56167       ** endian.
56168       */
56169       static const u64 t1 = ((u64)0x3ff00000)<<32;
56170       static const double r1 = 1.0;
56171       u64 t2 = t1;
56172       swapMixedEndianFloat(t2);
56173       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
56174 #endif
56175
56176       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
56177       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
56178       x = (x<<32) | y;
56179       if( serial_type==6 ){
56180         pMem->u.i = *(i64*)&x;
56181         pMem->flags = MEM_Int;
56182       }else{
56183         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
56184         swapMixedEndianFloat(x);
56185         memcpy(&pMem->r, &x, sizeof(x));
56186         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
56187       }
56188       return 8;
56189     }
56190     case 8:    /* Integer 0 */
56191     case 9: {  /* Integer 1 */
56192       pMem->u.i = serial_type-8;
56193       pMem->flags = MEM_Int;
56194       return 0;
56195     }
56196     default: {
56197       u32 len = (serial_type-12)/2;
56198       pMem->z = (char *)buf;
56199       pMem->n = len;
56200       pMem->xDel = 0;
56201       if( serial_type&0x01 ){
56202         pMem->flags = MEM_Str | MEM_Ephem;
56203       }else{
56204         pMem->flags = MEM_Blob | MEM_Ephem;
56205       }
56206       return len;
56207     }
56208   }
56209   return 0;
56210 }
56211
56212
56213 /*
56214 ** Given the nKey-byte encoding of a record in pKey[], parse the
56215 ** record into a UnpackedRecord structure.  Return a pointer to
56216 ** that structure.
56217 **
56218 ** The calling function might provide szSpace bytes of memory
56219 ** space at pSpace.  This space can be used to hold the returned
56220 ** VDbeParsedRecord structure if it is large enough.  If it is
56221 ** not big enough, space is obtained from sqlite3_malloc().
56222 **
56223 ** The returned structure should be closed by a call to
56224 ** sqlite3VdbeDeleteUnpackedRecord().
56225 */ 
56226 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
56227   KeyInfo *pKeyInfo,     /* Information about the record format */
56228   int nKey,              /* Size of the binary record */
56229   const void *pKey,      /* The binary record */
56230   char *pSpace,          /* Unaligned space available to hold the object */
56231   int szSpace            /* Size of pSpace[] in bytes */
56232 ){
56233   const unsigned char *aKey = (const unsigned char *)pKey;
56234   UnpackedRecord *p;  /* The unpacked record that we will return */
56235   int nByte;          /* Memory space needed to hold p, in bytes */
56236   int d;
56237   u32 idx;
56238   u16 u;              /* Unsigned loop counter */
56239   u32 szHdr;
56240   Mem *pMem;
56241   int nOff;           /* Increase pSpace by this much to 8-byte align it */
56242   
56243   /*
56244   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
56245   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
56246   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
56247   */
56248   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
56249   pSpace += nOff;
56250   szSpace -= nOff;
56251   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
56252   if( nByte>szSpace ){
56253     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
56254     if( p==0 ) return 0;
56255     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
56256   }else{
56257     p = (UnpackedRecord*)pSpace;
56258     p->flags = UNPACKED_NEED_DESTROY;
56259   }
56260   p->pKeyInfo = pKeyInfo;
56261   p->nField = pKeyInfo->nField + 1;
56262   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
56263   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56264   idx = getVarint32(aKey, szHdr);
56265   d = szHdr;
56266   u = 0;
56267   while( idx<szHdr && u<p->nField && d<=nKey ){
56268     u32 serial_type;
56269
56270     idx += getVarint32(&aKey[idx], serial_type);
56271     pMem->enc = pKeyInfo->enc;
56272     pMem->db = pKeyInfo->db;
56273     pMem->flags = 0;
56274     pMem->zMalloc = 0;
56275     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
56276     pMem++;
56277     u++;
56278   }
56279   assert( u<=pKeyInfo->nField + 1 );
56280   p->nField = u;
56281   return (void*)p;
56282 }
56283
56284 /*
56285 ** This routine destroys a UnpackedRecord object.
56286 */
56287 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
56288   int i;
56289   Mem *pMem;
56290
56291   assert( p!=0 );
56292   assert( p->flags & UNPACKED_NEED_DESTROY );
56293   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
56294     /* The unpacked record is always constructed by the
56295     ** sqlite3VdbeUnpackRecord() function above, which makes all
56296     ** strings and blobs static.  And none of the elements are
56297     ** ever transformed, so there is never anything to delete.
56298     */
56299     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
56300   }
56301   if( p->flags & UNPACKED_NEED_FREE ){
56302     sqlite3DbFree(p->pKeyInfo->db, p);
56303   }
56304 }
56305
56306 /*
56307 ** This function compares the two table rows or index records
56308 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
56309 ** or positive integer if key1 is less than, equal to or 
56310 ** greater than key2.  The {nKey1, pKey1} key must be a blob
56311 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
56312 ** key must be a parsed key such as obtained from
56313 ** sqlite3VdbeParseRecord.
56314 **
56315 ** Key1 and Key2 do not have to contain the same number of fields.
56316 ** The key with fewer fields is usually compares less than the 
56317 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
56318 ** and the common prefixes are equal, then key1 is less than key2.
56319 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
56320 ** equal, then the keys are considered to be equal and
56321 ** the parts beyond the common prefix are ignored.
56322 **
56323 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
56324 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
56325 ** an index key, and thus ends with a rowid value.  The last byte
56326 ** of the header will therefore be the serial type of the rowid:
56327 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
56328 ** The serial type of the final rowid will always be a single byte.
56329 ** By ignoring this last byte of the header, we force the comparison
56330 ** to ignore the rowid at the end of key1.
56331 */
56332 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
56333   int nKey1, const void *pKey1, /* Left key */
56334   UnpackedRecord *pPKey2        /* Right key */
56335 ){
56336   int d1;            /* Offset into aKey[] of next data element */
56337   u32 idx1;          /* Offset into aKey[] of next header element */
56338   u32 szHdr1;        /* Number of bytes in header */
56339   int i = 0;
56340   int nField;
56341   int rc = 0;
56342   const unsigned char *aKey1 = (const unsigned char *)pKey1;
56343   KeyInfo *pKeyInfo;
56344   Mem mem1;
56345
56346   pKeyInfo = pPKey2->pKeyInfo;
56347   mem1.enc = pKeyInfo->enc;
56348   mem1.db = pKeyInfo->db;
56349   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
56350   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
56351
56352   /* Compilers may complain that mem1.u.i is potentially uninitialized.
56353   ** We could initialize it, as shown here, to silence those complaints.
56354   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
56355   ** the unnecessary initialization has a measurable negative performance
56356   ** impact, since this routine is a very high runner.  And so, we choose
56357   ** to ignore the compiler warnings and leave this variable uninitialized.
56358   */
56359   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
56360   
56361   idx1 = getVarint32(aKey1, szHdr1);
56362   d1 = szHdr1;
56363   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
56364     szHdr1--;
56365   }
56366   nField = pKeyInfo->nField;
56367   while( idx1<szHdr1 && i<pPKey2->nField ){
56368     u32 serial_type1;
56369
56370     /* Read the serial types for the next element in each key. */
56371     idx1 += getVarint32( aKey1+idx1, serial_type1 );
56372     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
56373
56374     /* Extract the values to be compared.
56375     */
56376     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
56377
56378     /* Do the comparison
56379     */
56380     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
56381                            i<nField ? pKeyInfo->aColl[i] : 0);
56382     if( rc!=0 ){
56383       assert( mem1.zMalloc==0 );  /* See comment below */
56384
56385       /* Invert the result if we are using DESC sort order. */
56386       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
56387         rc = -rc;
56388       }
56389     
56390       /* If the PREFIX_SEARCH flag is set and all fields except the final
56391       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
56392       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
56393       ** This is used by the OP_IsUnique opcode.
56394       */
56395       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
56396         assert( idx1==szHdr1 && rc );
56397         assert( mem1.flags & MEM_Int );
56398         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
56399         pPKey2->rowid = mem1.u.i;
56400       }
56401     
56402       return rc;
56403     }
56404     i++;
56405   }
56406
56407   /* No memory allocation is ever used on mem1.  Prove this using
56408   ** the following assert().  If the assert() fails, it indicates a
56409   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
56410   */
56411   assert( mem1.zMalloc==0 );
56412
56413   /* rc==0 here means that one of the keys ran out of fields and
56414   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
56415   ** flag is set, then break the tie by treating key2 as larger.
56416   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
56417   ** are considered to be equal.  Otherwise, the longer key is the 
56418   ** larger.  As it happens, the pPKey2 will always be the longer
56419   ** if there is a difference.
56420   */
56421   assert( rc==0 );
56422   if( pPKey2->flags & UNPACKED_INCRKEY ){
56423     rc = -1;
56424   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
56425     /* Leave rc==0 */
56426   }else if( idx1<szHdr1 ){
56427     rc = 1;
56428   }
56429   return rc;
56430 }
56431  
56432
56433 /*
56434 ** pCur points at an index entry created using the OP_MakeRecord opcode.
56435 ** Read the rowid (the last field in the record) and store it in *rowid.
56436 ** Return SQLITE_OK if everything works, or an error code otherwise.
56437 **
56438 ** pCur might be pointing to text obtained from a corrupt database file.
56439 ** So the content cannot be trusted.  Do appropriate checks on the content.
56440 */
56441 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
56442   i64 nCellKey = 0;
56443   int rc;
56444   u32 szHdr;        /* Size of the header */
56445   u32 typeRowid;    /* Serial type of the rowid */
56446   u32 lenRowid;     /* Size of the rowid */
56447   Mem m, v;
56448
56449   UNUSED_PARAMETER(db);
56450
56451   /* Get the size of the index entry.  Only indices entries of less
56452   ** than 2GiB are support - anything large must be database corruption.
56453   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
56454   ** this code can safely assume that nCellKey is 32-bits  
56455   */
56456   assert( sqlite3BtreeCursorIsValid(pCur) );
56457   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56458   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
56459   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
56460
56461   /* Read in the complete content of the index entry */
56462   memset(&m, 0, sizeof(m));
56463   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
56464   if( rc ){
56465     return rc;
56466   }
56467
56468   /* The index entry must begin with a header size */
56469   (void)getVarint32((u8*)m.z, szHdr);
56470   testcase( szHdr==3 );
56471   testcase( szHdr==m.n );
56472   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
56473     goto idx_rowid_corruption;
56474   }
56475
56476   /* The last field of the index should be an integer - the ROWID.
56477   ** Verify that the last entry really is an integer. */
56478   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
56479   testcase( typeRowid==1 );
56480   testcase( typeRowid==2 );
56481   testcase( typeRowid==3 );
56482   testcase( typeRowid==4 );
56483   testcase( typeRowid==5 );
56484   testcase( typeRowid==6 );
56485   testcase( typeRowid==8 );
56486   testcase( typeRowid==9 );
56487   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
56488     goto idx_rowid_corruption;
56489   }
56490   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
56491   testcase( (u32)m.n==szHdr+lenRowid );
56492   if( unlikely((u32)m.n<szHdr+lenRowid) ){
56493     goto idx_rowid_corruption;
56494   }
56495
56496   /* Fetch the integer off the end of the index record */
56497   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
56498   *rowid = v.u.i;
56499   sqlite3VdbeMemRelease(&m);
56500   return SQLITE_OK;
56501
56502   /* Jump here if database corruption is detected after m has been
56503   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
56504 idx_rowid_corruption:
56505   testcase( m.zMalloc!=0 );
56506   sqlite3VdbeMemRelease(&m);
56507   return SQLITE_CORRUPT_BKPT;
56508 }
56509
56510 /*
56511 ** Compare the key of the index entry that cursor pC is pointing to against
56512 ** the key string in pUnpacked.  Write into *pRes a number
56513 ** that is negative, zero, or positive if pC is less than, equal to,
56514 ** or greater than pUnpacked.  Return SQLITE_OK on success.
56515 **
56516 ** pUnpacked is either created without a rowid or is truncated so that it
56517 ** omits the rowid at the end.  The rowid at the end of the index entry
56518 ** is ignored as well.  Hence, this routine only compares the prefixes 
56519 ** of the keys prior to the final rowid, not the entire key.
56520 */
56521 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
56522   VdbeCursor *pC,             /* The cursor to compare against */
56523   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
56524   int *res                    /* Write the comparison result here */
56525 ){
56526   i64 nCellKey = 0;
56527   int rc;
56528   BtCursor *pCur = pC->pCursor;
56529   Mem m;
56530
56531   assert( sqlite3BtreeCursorIsValid(pCur) );
56532   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56533   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
56534   /* nCellKey will always be between 0 and 0xffffffff because of the say
56535   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
56536   if( nCellKey<=0 || nCellKey>0x7fffffff ){
56537     *res = 0;
56538     return SQLITE_CORRUPT_BKPT;
56539   }
56540   memset(&m, 0, sizeof(m));
56541   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
56542   if( rc ){
56543     return rc;
56544   }
56545   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
56546   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
56547   sqlite3VdbeMemRelease(&m);
56548   return SQLITE_OK;
56549 }
56550
56551 /*
56552 ** This routine sets the value to be returned by subsequent calls to
56553 ** sqlite3_changes() on the database handle 'db'. 
56554 */
56555 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
56556   assert( sqlite3_mutex_held(db->mutex) );
56557   db->nChange = nChange;
56558   db->nTotalChange += nChange;
56559 }
56560
56561 /*
56562 ** Set a flag in the vdbe to update the change counter when it is finalised
56563 ** or reset.
56564 */
56565 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
56566   v->changeCntOn = 1;
56567 }
56568
56569 /*
56570 ** Mark every prepared statement associated with a database connection
56571 ** as expired.
56572 **
56573 ** An expired statement means that recompilation of the statement is
56574 ** recommend.  Statements expire when things happen that make their
56575 ** programs obsolete.  Removing user-defined functions or collating
56576 ** sequences, or changing an authorization function are the types of
56577 ** things that make prepared statements obsolete.
56578 */
56579 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
56580   Vdbe *p;
56581   for(p = db->pVdbe; p; p=p->pNext){
56582     p->expired = 1;
56583   }
56584 }
56585
56586 /*
56587 ** Return the database associated with the Vdbe.
56588 */
56589 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
56590   return v->db;
56591 }
56592
56593 /*
56594 ** Return a pointer to an sqlite3_value structure containing the value bound
56595 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
56596 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
56597 ** constants) to the value before returning it.
56598 **
56599 ** The returned value must be freed by the caller using sqlite3ValueFree().
56600 */
56601 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
56602   assert( iVar>0 );
56603   if( v ){
56604     Mem *pMem = &v->aVar[iVar-1];
56605     if( 0==(pMem->flags & MEM_Null) ){
56606       sqlite3_value *pRet = sqlite3ValueNew(v->db);
56607       if( pRet ){
56608         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
56609         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
56610         sqlite3VdbeMemStoreType((Mem *)pRet);
56611       }
56612       return pRet;
56613     }
56614   }
56615   return 0;
56616 }
56617
56618 /*
56619 ** Configure SQL variable iVar so that binding a new value to it signals
56620 ** to sqlite3_reoptimize() that re-preparing the statement may result
56621 ** in a better query plan.
56622 */
56623 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
56624   assert( iVar>0 );
56625   if( iVar>32 ){
56626     v->expmask = 0xffffffff;
56627   }else{
56628     v->expmask |= ((u32)1 << (iVar-1));
56629   }
56630 }
56631
56632 /************** End of vdbeaux.c *********************************************/
56633 /************** Begin file vdbeapi.c *****************************************/
56634 /*
56635 ** 2004 May 26
56636 **
56637 ** The author disclaims copyright to this source code.  In place of
56638 ** a legal notice, here is a blessing:
56639 **
56640 **    May you do good and not evil.
56641 **    May you find forgiveness for yourself and forgive others.
56642 **    May you share freely, never taking more than you give.
56643 **
56644 *************************************************************************
56645 **
56646 ** This file contains code use to implement APIs that are part of the
56647 ** VDBE.
56648 */
56649
56650 #ifndef SQLITE_OMIT_DEPRECATED
56651 /*
56652 ** Return TRUE (non-zero) of the statement supplied as an argument needs
56653 ** to be recompiled.  A statement needs to be recompiled whenever the
56654 ** execution environment changes in a way that would alter the program
56655 ** that sqlite3_prepare() generates.  For example, if new functions or
56656 ** collating sequences are registered or if an authorizer function is
56657 ** added or changed.
56658 */
56659 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
56660   Vdbe *p = (Vdbe*)pStmt;
56661   return p==0 || p->expired;
56662 }
56663 #endif
56664
56665 /*
56666 ** Check on a Vdbe to make sure it has not been finalized.  Log
56667 ** an error and return true if it has been finalized (or is otherwise
56668 ** invalid).  Return false if it is ok.
56669 */
56670 static int vdbeSafety(Vdbe *p){
56671   if( p->db==0 ){
56672     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
56673     return 1;
56674   }else{
56675     return 0;
56676   }
56677 }
56678 static int vdbeSafetyNotNull(Vdbe *p){
56679   if( p==0 ){
56680     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
56681     return 1;
56682   }else{
56683     return vdbeSafety(p);
56684   }
56685 }
56686
56687 /*
56688 ** The following routine destroys a virtual machine that is created by
56689 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
56690 ** success/failure code that describes the result of executing the virtual
56691 ** machine.
56692 **
56693 ** This routine sets the error code and string returned by
56694 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56695 */
56696 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
56697   int rc;
56698   if( pStmt==0 ){
56699     rc = SQLITE_OK;
56700   }else{
56701     Vdbe *v = (Vdbe*)pStmt;
56702     sqlite3 *db = v->db;
56703 #if SQLITE_THREADSAFE
56704     sqlite3_mutex *mutex;
56705 #endif
56706     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
56707 #if SQLITE_THREADSAFE
56708     mutex = v->db->mutex;
56709 #endif
56710     sqlite3_mutex_enter(mutex);
56711     rc = sqlite3VdbeFinalize(v);
56712     rc = sqlite3ApiExit(db, rc);
56713     sqlite3_mutex_leave(mutex);
56714   }
56715   return rc;
56716 }
56717
56718 /*
56719 ** Terminate the current execution of an SQL statement and reset it
56720 ** back to its starting state so that it can be reused. A success code from
56721 ** the prior execution is returned.
56722 **
56723 ** This routine sets the error code and string returned by
56724 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56725 */
56726 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
56727   int rc;
56728   if( pStmt==0 ){
56729     rc = SQLITE_OK;
56730   }else{
56731     Vdbe *v = (Vdbe*)pStmt;
56732     sqlite3_mutex_enter(v->db->mutex);
56733     rc = sqlite3VdbeReset(v);
56734     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
56735     assert( (rc & (v->db->errMask))==rc );
56736     rc = sqlite3ApiExit(v->db, rc);
56737     sqlite3_mutex_leave(v->db->mutex);
56738   }
56739   return rc;
56740 }
56741
56742 /*
56743 ** Set all the parameters in the compiled SQL statement to NULL.
56744 */
56745 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
56746   int i;
56747   int rc = SQLITE_OK;
56748   Vdbe *p = (Vdbe*)pStmt;
56749 #if SQLITE_THREADSAFE
56750   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
56751 #endif
56752   sqlite3_mutex_enter(mutex);
56753   for(i=0; i<p->nVar; i++){
56754     sqlite3VdbeMemRelease(&p->aVar[i]);
56755     p->aVar[i].flags = MEM_Null;
56756   }
56757   if( p->isPrepareV2 && p->expmask ){
56758     p->expired = 1;
56759   }
56760   sqlite3_mutex_leave(mutex);
56761   return rc;
56762 }
56763
56764
56765 /**************************** sqlite3_value_  *******************************
56766 ** The following routines extract information from a Mem or sqlite3_value
56767 ** structure.
56768 */
56769 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
56770   Mem *p = (Mem*)pVal;
56771   if( p->flags & (MEM_Blob|MEM_Str) ){
56772     sqlite3VdbeMemExpandBlob(p);
56773     p->flags &= ~MEM_Str;
56774     p->flags |= MEM_Blob;
56775     return p->z;
56776   }else{
56777     return sqlite3_value_text(pVal);
56778   }
56779 }
56780 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
56781   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
56782 }
56783 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
56784   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
56785 }
56786 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
56787   return sqlite3VdbeRealValue((Mem*)pVal);
56788 }
56789 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
56790   return (int)sqlite3VdbeIntValue((Mem*)pVal);
56791 }
56792 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
56793   return sqlite3VdbeIntValue((Mem*)pVal);
56794 }
56795 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
56796   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
56797 }
56798 #ifndef SQLITE_OMIT_UTF16
56799 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
56800   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
56801 }
56802 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
56803   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
56804 }
56805 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
56806   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
56807 }
56808 #endif /* SQLITE_OMIT_UTF16 */
56809 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
56810   return pVal->type;
56811 }
56812
56813 /**************************** sqlite3_result_  *******************************
56814 ** The following routines are used by user-defined functions to specify
56815 ** the function result.
56816 **
56817 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
56818 ** result as a string or blob but if the string or blob is too large, it
56819 ** then sets the error code to SQLITE_TOOBIG
56820 */
56821 static void setResultStrOrError(
56822   sqlite3_context *pCtx,  /* Function context */
56823   const char *z,          /* String pointer */
56824   int n,                  /* Bytes in string, or negative */
56825   u8 enc,                 /* Encoding of z.  0 for BLOBs */
56826   void (*xDel)(void*)     /* Destructor function */
56827 ){
56828   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
56829     sqlite3_result_error_toobig(pCtx);
56830   }
56831 }
56832 SQLITE_API void sqlite3_result_blob(
56833   sqlite3_context *pCtx, 
56834   const void *z, 
56835   int n, 
56836   void (*xDel)(void *)
56837 ){
56838   assert( n>=0 );
56839   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56840   setResultStrOrError(pCtx, z, n, 0, xDel);
56841 }
56842 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
56843   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56844   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
56845 }
56846 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
56847   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56848   pCtx->isError = SQLITE_ERROR;
56849   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
56850 }
56851 #ifndef SQLITE_OMIT_UTF16
56852 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
56853   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56854   pCtx->isError = SQLITE_ERROR;
56855   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
56856 }
56857 #endif
56858 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
56859   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56860   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
56861 }
56862 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
56863   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56864   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
56865 }
56866 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
56867   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56868   sqlite3VdbeMemSetNull(&pCtx->s);
56869 }
56870 SQLITE_API void sqlite3_result_text(
56871   sqlite3_context *pCtx, 
56872   const char *z, 
56873   int n,
56874   void (*xDel)(void *)
56875 ){
56876   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56877   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
56878 }
56879 #ifndef SQLITE_OMIT_UTF16
56880 SQLITE_API void sqlite3_result_text16(
56881   sqlite3_context *pCtx, 
56882   const void *z, 
56883   int n, 
56884   void (*xDel)(void *)
56885 ){
56886   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56887   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
56888 }
56889 SQLITE_API void sqlite3_result_text16be(
56890   sqlite3_context *pCtx, 
56891   const void *z, 
56892   int n, 
56893   void (*xDel)(void *)
56894 ){
56895   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56896   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
56897 }
56898 SQLITE_API void sqlite3_result_text16le(
56899   sqlite3_context *pCtx, 
56900   const void *z, 
56901   int n, 
56902   void (*xDel)(void *)
56903 ){
56904   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56905   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
56906 }
56907 #endif /* SQLITE_OMIT_UTF16 */
56908 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
56909   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56910   sqlite3VdbeMemCopy(&pCtx->s, pValue);
56911 }
56912 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
56913   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56914   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
56915 }
56916 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
56917   pCtx->isError = errCode;
56918   if( pCtx->s.flags & MEM_Null ){
56919     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
56920                          SQLITE_UTF8, SQLITE_STATIC);
56921   }
56922 }
56923
56924 /* Force an SQLITE_TOOBIG error. */
56925 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
56926   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56927   pCtx->isError = SQLITE_TOOBIG;
56928   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
56929                        SQLITE_UTF8, SQLITE_STATIC);
56930 }
56931
56932 /* An SQLITE_NOMEM error. */
56933 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
56934   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56935   sqlite3VdbeMemSetNull(&pCtx->s);
56936   pCtx->isError = SQLITE_NOMEM;
56937   pCtx->s.db->mallocFailed = 1;
56938 }
56939
56940 /*
56941 ** This function is called after a transaction has been committed. It 
56942 ** invokes callbacks registered with sqlite3_wal_hook() as required.
56943 */
56944 static int doWalCallbacks(sqlite3 *db){
56945   int rc = SQLITE_OK;
56946 #ifndef SQLITE_OMIT_WAL
56947   int i;
56948   for(i=0; i<db->nDb; i++){
56949     Btree *pBt = db->aDb[i].pBt;
56950     if( pBt ){
56951       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
56952       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
56953         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
56954       }
56955     }
56956   }
56957 #endif
56958   return rc;
56959 }
56960
56961 /*
56962 ** Execute the statement pStmt, either until a row of data is ready, the
56963 ** statement is completely executed or an error occurs.
56964 **
56965 ** This routine implements the bulk of the logic behind the sqlite_step()
56966 ** API.  The only thing omitted is the automatic recompile if a 
56967 ** schema change has occurred.  That detail is handled by the
56968 ** outer sqlite3_step() wrapper procedure.
56969 */
56970 static int sqlite3Step(Vdbe *p){
56971   sqlite3 *db;
56972   int rc;
56973
56974   assert(p);
56975   if( p->magic!=VDBE_MAGIC_RUN ){
56976     /* We used to require that sqlite3_reset() be called before retrying
56977     ** sqlite3_step() after any error.  But after 3.6.23, we changed this
56978     ** so that sqlite3_reset() would be called automatically instead of
56979     ** throwing the error.
56980     */
56981     sqlite3_reset((sqlite3_stmt*)p);
56982   }
56983
56984   /* Check that malloc() has not failed. If it has, return early. */
56985   db = p->db;
56986   if( db->mallocFailed ){
56987     p->rc = SQLITE_NOMEM;
56988     return SQLITE_NOMEM;
56989   }
56990
56991   if( p->pc<=0 && p->expired ){
56992     p->rc = SQLITE_SCHEMA;
56993     rc = SQLITE_ERROR;
56994     goto end_of_step;
56995   }
56996   if( p->pc<0 ){
56997     /* If there are no other statements currently running, then
56998     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
56999     ** from interrupting a statement that has not yet started.
57000     */
57001     if( db->activeVdbeCnt==0 ){
57002       db->u1.isInterrupted = 0;
57003     }
57004
57005     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
57006
57007 #ifndef SQLITE_OMIT_TRACE
57008     if( db->xProfile && !db->init.busy ){
57009       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
57010     }
57011 #endif
57012
57013     db->activeVdbeCnt++;
57014     if( p->readOnly==0 ) db->writeVdbeCnt++;
57015     p->pc = 0;
57016   }
57017 #ifndef SQLITE_OMIT_EXPLAIN
57018   if( p->explain ){
57019     rc = sqlite3VdbeList(p);
57020   }else
57021 #endif /* SQLITE_OMIT_EXPLAIN */
57022   {
57023     rc = sqlite3VdbeExec(p);
57024   }
57025
57026 #ifndef SQLITE_OMIT_TRACE
57027   /* Invoke the profile callback if there is one
57028   */
57029   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
57030     sqlite3_int64 iNow;
57031     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
57032     db->xProfile(db->pProfileArg, p->zSql, iNow - p->startTime);
57033   }
57034 #endif
57035
57036   if( rc==SQLITE_DONE ){
57037     assert( p->rc==SQLITE_OK );
57038     p->rc = doWalCallbacks(db);
57039     if( p->rc!=SQLITE_OK ){
57040       rc = SQLITE_ERROR;
57041     }
57042   }
57043
57044   db->errCode = rc;
57045   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
57046     p->rc = SQLITE_NOMEM;
57047   }
57048 end_of_step:
57049   /* At this point local variable rc holds the value that should be 
57050   ** returned if this statement was compiled using the legacy 
57051   ** sqlite3_prepare() interface. According to the docs, this can only
57052   ** be one of the values in the first assert() below. Variable p->rc 
57053   ** contains the value that would be returned if sqlite3_finalize() 
57054   ** were called on statement p.
57055   */
57056   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
57057        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
57058   );
57059   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
57060   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
57061     /* If this statement was prepared using sqlite3_prepare_v2(), and an
57062     ** error has occured, then return the error code in p->rc to the
57063     ** caller. Set the error code in the database handle to the same value.
57064     */ 
57065     rc = db->errCode = p->rc;
57066   }
57067   return (rc&db->errMask);
57068 }
57069
57070 /*
57071 ** This is the top-level implementation of sqlite3_step().  Call
57072 ** sqlite3Step() to do most of the work.  If a schema error occurs,
57073 ** call sqlite3Reprepare() and try again.
57074 */
57075 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
57076   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
57077   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
57078   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
57079   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
57080   sqlite3 *db;             /* The database connection */
57081
57082   if( vdbeSafetyNotNull(v) ){
57083     return SQLITE_MISUSE_BKPT;
57084   }
57085   db = v->db;
57086   sqlite3_mutex_enter(db->mutex);
57087   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
57088          && cnt++ < 5
57089          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
57090     sqlite3_reset(pStmt);
57091     v->expired = 0;
57092   }
57093   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
57094     /* This case occurs after failing to recompile an sql statement. 
57095     ** The error message from the SQL compiler has already been loaded 
57096     ** into the database handle. This block copies the error message 
57097     ** from the database handle into the statement and sets the statement
57098     ** program counter to 0 to ensure that when the statement is 
57099     ** finalized or reset the parser error message is available via
57100     ** sqlite3_errmsg() and sqlite3_errcode().
57101     */
57102     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
57103     sqlite3DbFree(db, v->zErrMsg);
57104     if( !db->mallocFailed ){
57105       v->zErrMsg = sqlite3DbStrDup(db, zErr);
57106       v->rc = rc2;
57107     } else {
57108       v->zErrMsg = 0;
57109       v->rc = rc = SQLITE_NOMEM;
57110     }
57111   }
57112   rc = sqlite3ApiExit(db, rc);
57113   sqlite3_mutex_leave(db->mutex);
57114   return rc;
57115 }
57116
57117 /*
57118 ** Extract the user data from a sqlite3_context structure and return a
57119 ** pointer to it.
57120 */
57121 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
57122   assert( p && p->pFunc );
57123   return p->pFunc->pUserData;
57124 }
57125
57126 /*
57127 ** Extract the user data from a sqlite3_context structure and return a
57128 ** pointer to it.
57129 */
57130 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
57131   assert( p && p->pFunc );
57132   return p->s.db;
57133 }
57134
57135 /*
57136 ** The following is the implementation of an SQL function that always
57137 ** fails with an error message stating that the function is used in the
57138 ** wrong context.  The sqlite3_overload_function() API might construct
57139 ** SQL function that use this routine so that the functions will exist
57140 ** for name resolution but are actually overloaded by the xFindFunction
57141 ** method of virtual tables.
57142 */
57143 SQLITE_PRIVATE void sqlite3InvalidFunction(
57144   sqlite3_context *context,  /* The function calling context */
57145   int NotUsed,               /* Number of arguments to the function */
57146   sqlite3_value **NotUsed2   /* Value of each argument */
57147 ){
57148   const char *zName = context->pFunc->zName;
57149   char *zErr;
57150   UNUSED_PARAMETER2(NotUsed, NotUsed2);
57151   zErr = sqlite3_mprintf(
57152       "unable to use function %s in the requested context", zName);
57153   sqlite3_result_error(context, zErr, -1);
57154   sqlite3_free(zErr);
57155 }
57156
57157 /*
57158 ** Allocate or return the aggregate context for a user function.  A new
57159 ** context is allocated on the first call.  Subsequent calls return the
57160 ** same context that was returned on prior calls.
57161 */
57162 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
57163   Mem *pMem;
57164   assert( p && p->pFunc && p->pFunc->xStep );
57165   assert( sqlite3_mutex_held(p->s.db->mutex) );
57166   pMem = p->pMem;
57167   testcase( nByte<0 );
57168   if( (pMem->flags & MEM_Agg)==0 ){
57169     if( nByte<=0 ){
57170       sqlite3VdbeMemReleaseExternal(pMem);
57171       pMem->flags = MEM_Null;
57172       pMem->z = 0;
57173     }else{
57174       sqlite3VdbeMemGrow(pMem, nByte, 0);
57175       pMem->flags = MEM_Agg;
57176       pMem->u.pDef = p->pFunc;
57177       if( pMem->z ){
57178         memset(pMem->z, 0, nByte);
57179       }
57180     }
57181   }
57182   return (void*)pMem->z;
57183 }
57184
57185 /*
57186 ** Return the auxilary data pointer, if any, for the iArg'th argument to
57187 ** the user-function defined by pCtx.
57188 */
57189 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
57190   VdbeFunc *pVdbeFunc;
57191
57192   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57193   pVdbeFunc = pCtx->pVdbeFunc;
57194   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
57195     return 0;
57196   }
57197   return pVdbeFunc->apAux[iArg].pAux;
57198 }
57199
57200 /*
57201 ** Set the auxilary data pointer and delete function, for the iArg'th
57202 ** argument to the user-function defined by pCtx. Any previous value is
57203 ** deleted by calling the delete function specified when it was set.
57204 */
57205 SQLITE_API void sqlite3_set_auxdata(
57206   sqlite3_context *pCtx, 
57207   int iArg, 
57208   void *pAux, 
57209   void (*xDelete)(void*)
57210 ){
57211   struct AuxData *pAuxData;
57212   VdbeFunc *pVdbeFunc;
57213   if( iArg<0 ) goto failed;
57214
57215   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57216   pVdbeFunc = pCtx->pVdbeFunc;
57217   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
57218     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
57219     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
57220     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
57221     if( !pVdbeFunc ){
57222       goto failed;
57223     }
57224     pCtx->pVdbeFunc = pVdbeFunc;
57225     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
57226     pVdbeFunc->nAux = iArg+1;
57227     pVdbeFunc->pFunc = pCtx->pFunc;
57228   }
57229
57230   pAuxData = &pVdbeFunc->apAux[iArg];
57231   if( pAuxData->pAux && pAuxData->xDelete ){
57232     pAuxData->xDelete(pAuxData->pAux);
57233   }
57234   pAuxData->pAux = pAux;
57235   pAuxData->xDelete = xDelete;
57236   return;
57237
57238 failed:
57239   if( xDelete ){
57240     xDelete(pAux);
57241   }
57242 }
57243
57244 #ifndef SQLITE_OMIT_DEPRECATED
57245 /*
57246 ** Return the number of times the Step function of a aggregate has been 
57247 ** called.
57248 **
57249 ** This function is deprecated.  Do not use it for new code.  It is
57250 ** provide only to avoid breaking legacy code.  New aggregate function
57251 ** implementations should keep their own counts within their aggregate
57252 ** context.
57253 */
57254 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
57255   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
57256   return p->pMem->n;
57257 }
57258 #endif
57259
57260 /*
57261 ** Return the number of columns in the result set for the statement pStmt.
57262 */
57263 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
57264   Vdbe *pVm = (Vdbe *)pStmt;
57265   return pVm ? pVm->nResColumn : 0;
57266 }
57267
57268 /*
57269 ** Return the number of values available from the current row of the
57270 ** currently executing statement pStmt.
57271 */
57272 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
57273   Vdbe *pVm = (Vdbe *)pStmt;
57274   if( pVm==0 || pVm->pResultSet==0 ) return 0;
57275   return pVm->nResColumn;
57276 }
57277
57278
57279 /*
57280 ** Check to see if column iCol of the given statement is valid.  If
57281 ** it is, return a pointer to the Mem for the value of that column.
57282 ** If iCol is not valid, return a pointer to a Mem which has a value
57283 ** of NULL.
57284 */
57285 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
57286   Vdbe *pVm;
57287   int vals;
57288   Mem *pOut;
57289
57290   pVm = (Vdbe *)pStmt;
57291   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
57292     sqlite3_mutex_enter(pVm->db->mutex);
57293     vals = sqlite3_data_count(pStmt);
57294     pOut = &pVm->pResultSet[i];
57295   }else{
57296     /* If the value passed as the second argument is out of range, return
57297     ** a pointer to the following static Mem object which contains the
57298     ** value SQL NULL. Even though the Mem structure contains an element
57299     ** of type i64, on certain architecture (x86) with certain compiler
57300     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
57301     ** instead of an 8-byte one. This all works fine, except that when
57302     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
57303     ** that a Mem structure is located on an 8-byte boundary. To prevent
57304     ** this assert() from failing, when building with SQLITE_DEBUG defined
57305     ** using gcc, force nullMem to be 8-byte aligned using the magical
57306     ** __attribute__((aligned(8))) macro.  */
57307     static const Mem nullMem 
57308 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
57309       __attribute__((aligned(8))) 
57310 #endif
57311       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
57312
57313     if( pVm && ALWAYS(pVm->db) ){
57314       sqlite3_mutex_enter(pVm->db->mutex);
57315       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
57316     }
57317     pOut = (Mem*)&nullMem;
57318   }
57319   return pOut;
57320 }
57321
57322 /*
57323 ** This function is called after invoking an sqlite3_value_XXX function on a 
57324 ** column value (i.e. a value returned by evaluating an SQL expression in the
57325 ** select list of a SELECT statement) that may cause a malloc() failure. If 
57326 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
57327 ** code of statement pStmt set to SQLITE_NOMEM.
57328 **
57329 ** Specifically, this is called from within:
57330 **
57331 **     sqlite3_column_int()
57332 **     sqlite3_column_int64()
57333 **     sqlite3_column_text()
57334 **     sqlite3_column_text16()
57335 **     sqlite3_column_real()
57336 **     sqlite3_column_bytes()
57337 **     sqlite3_column_bytes16()
57338 **
57339 ** But not for sqlite3_column_blob(), which never calls malloc().
57340 */
57341 static void columnMallocFailure(sqlite3_stmt *pStmt)
57342 {
57343   /* If malloc() failed during an encoding conversion within an
57344   ** sqlite3_column_XXX API, then set the return code of the statement to
57345   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
57346   ** and _finalize() will return NOMEM.
57347   */
57348   Vdbe *p = (Vdbe *)pStmt;
57349   if( p ){
57350     p->rc = sqlite3ApiExit(p->db, p->rc);
57351     sqlite3_mutex_leave(p->db->mutex);
57352   }
57353 }
57354
57355 /**************************** sqlite3_column_  *******************************
57356 ** The following routines are used to access elements of the current row
57357 ** in the result set.
57358 */
57359 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
57360   const void *val;
57361   val = sqlite3_value_blob( columnMem(pStmt,i) );
57362   /* Even though there is no encoding conversion, value_blob() might
57363   ** need to call malloc() to expand the result of a zeroblob() 
57364   ** expression. 
57365   */
57366   columnMallocFailure(pStmt);
57367   return val;
57368 }
57369 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
57370   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
57371   columnMallocFailure(pStmt);
57372   return val;
57373 }
57374 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
57375   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
57376   columnMallocFailure(pStmt);
57377   return val;
57378 }
57379 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
57380   double val = sqlite3_value_double( columnMem(pStmt,i) );
57381   columnMallocFailure(pStmt);
57382   return val;
57383 }
57384 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
57385   int val = sqlite3_value_int( columnMem(pStmt,i) );
57386   columnMallocFailure(pStmt);
57387   return val;
57388 }
57389 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
57390   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
57391   columnMallocFailure(pStmt);
57392   return val;
57393 }
57394 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
57395   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
57396   columnMallocFailure(pStmt);
57397   return val;
57398 }
57399 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
57400   Mem *pOut = columnMem(pStmt, i);
57401   if( pOut->flags&MEM_Static ){
57402     pOut->flags &= ~MEM_Static;
57403     pOut->flags |= MEM_Ephem;
57404   }
57405   columnMallocFailure(pStmt);
57406   return (sqlite3_value *)pOut;
57407 }
57408 #ifndef SQLITE_OMIT_UTF16
57409 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
57410   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
57411   columnMallocFailure(pStmt);
57412   return val;
57413 }
57414 #endif /* SQLITE_OMIT_UTF16 */
57415 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
57416   int iType = sqlite3_value_type( columnMem(pStmt,i) );
57417   columnMallocFailure(pStmt);
57418   return iType;
57419 }
57420
57421 /* The following function is experimental and subject to change or
57422 ** removal */
57423 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
57424 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
57425 **}
57426 */
57427
57428 /*
57429 ** Convert the N-th element of pStmt->pColName[] into a string using
57430 ** xFunc() then return that string.  If N is out of range, return 0.
57431 **
57432 ** There are up to 5 names for each column.  useType determines which
57433 ** name is returned.  Here are the names:
57434 **
57435 **    0      The column name as it should be displayed for output
57436 **    1      The datatype name for the column
57437 **    2      The name of the database that the column derives from
57438 **    3      The name of the table that the column derives from
57439 **    4      The name of the table column that the result column derives from
57440 **
57441 ** If the result is not a simple column reference (if it is an expression
57442 ** or a constant) then useTypes 2, 3, and 4 return NULL.
57443 */
57444 static const void *columnName(
57445   sqlite3_stmt *pStmt,
57446   int N,
57447   const void *(*xFunc)(Mem*),
57448   int useType
57449 ){
57450   const void *ret = 0;
57451   Vdbe *p = (Vdbe *)pStmt;
57452   int n;
57453   sqlite3 *db = p->db;
57454   
57455   assert( db!=0 );
57456   n = sqlite3_column_count(pStmt);
57457   if( N<n && N>=0 ){
57458     N += useType*n;
57459     sqlite3_mutex_enter(db->mutex);
57460     assert( db->mallocFailed==0 );
57461     ret = xFunc(&p->aColName[N]);
57462      /* A malloc may have failed inside of the xFunc() call. If this
57463     ** is the case, clear the mallocFailed flag and return NULL.
57464     */
57465     if( db->mallocFailed ){
57466       db->mallocFailed = 0;
57467       ret = 0;
57468     }
57469     sqlite3_mutex_leave(db->mutex);
57470   }
57471   return ret;
57472 }
57473
57474 /*
57475 ** Return the name of the Nth column of the result set returned by SQL
57476 ** statement pStmt.
57477 */
57478 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
57479   return columnName(
57480       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
57481 }
57482 #ifndef SQLITE_OMIT_UTF16
57483 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
57484   return columnName(
57485       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
57486 }
57487 #endif
57488
57489 /*
57490 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
57491 ** not define OMIT_DECLTYPE.
57492 */
57493 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
57494 # error "Must not define both SQLITE_OMIT_DECLTYPE \
57495          and SQLITE_ENABLE_COLUMN_METADATA"
57496 #endif
57497
57498 #ifndef SQLITE_OMIT_DECLTYPE
57499 /*
57500 ** Return the column declaration type (if applicable) of the 'i'th column
57501 ** of the result set of SQL statement pStmt.
57502 */
57503 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
57504   return columnName(
57505       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
57506 }
57507 #ifndef SQLITE_OMIT_UTF16
57508 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
57509   return columnName(
57510       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
57511 }
57512 #endif /* SQLITE_OMIT_UTF16 */
57513 #endif /* SQLITE_OMIT_DECLTYPE */
57514
57515 #ifdef SQLITE_ENABLE_COLUMN_METADATA
57516 /*
57517 ** Return the name of the database from which a result column derives.
57518 ** NULL is returned if the result column is an expression or constant or
57519 ** anything else which is not an unabiguous reference to a database column.
57520 */
57521 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
57522   return columnName(
57523       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
57524 }
57525 #ifndef SQLITE_OMIT_UTF16
57526 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
57527   return columnName(
57528       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
57529 }
57530 #endif /* SQLITE_OMIT_UTF16 */
57531
57532 /*
57533 ** Return the name of the table from which a result column derives.
57534 ** NULL is returned if the result column is an expression or constant or
57535 ** anything else which is not an unabiguous reference to a database column.
57536 */
57537 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
57538   return columnName(
57539       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
57540 }
57541 #ifndef SQLITE_OMIT_UTF16
57542 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
57543   return columnName(
57544       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
57545 }
57546 #endif /* SQLITE_OMIT_UTF16 */
57547
57548 /*
57549 ** Return the name of the table column from which a result column derives.
57550 ** NULL is returned if the result column is an expression or constant or
57551 ** anything else which is not an unabiguous reference to a database column.
57552 */
57553 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
57554   return columnName(
57555       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
57556 }
57557 #ifndef SQLITE_OMIT_UTF16
57558 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
57559   return columnName(
57560       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
57561 }
57562 #endif /* SQLITE_OMIT_UTF16 */
57563 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
57564
57565
57566 /******************************* sqlite3_bind_  ***************************
57567 ** 
57568 ** Routines used to attach values to wildcards in a compiled SQL statement.
57569 */
57570 /*
57571 ** Unbind the value bound to variable i in virtual machine p. This is the 
57572 ** the same as binding a NULL value to the column. If the "i" parameter is
57573 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
57574 **
57575 ** A successful evaluation of this routine acquires the mutex on p.
57576 ** the mutex is released if any kind of error occurs.
57577 **
57578 ** The error code stored in database p->db is overwritten with the return
57579 ** value in any case.
57580 */
57581 static int vdbeUnbind(Vdbe *p, int i){
57582   Mem *pVar;
57583   if( vdbeSafetyNotNull(p) ){
57584     return SQLITE_MISUSE_BKPT;
57585   }
57586   sqlite3_mutex_enter(p->db->mutex);
57587   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
57588     sqlite3Error(p->db, SQLITE_MISUSE, 0);
57589     sqlite3_mutex_leave(p->db->mutex);
57590     sqlite3_log(SQLITE_MISUSE, 
57591         "bind on a busy prepared statement: [%s]", p->zSql);
57592     return SQLITE_MISUSE_BKPT;
57593   }
57594   if( i<1 || i>p->nVar ){
57595     sqlite3Error(p->db, SQLITE_RANGE, 0);
57596     sqlite3_mutex_leave(p->db->mutex);
57597     return SQLITE_RANGE;
57598   }
57599   i--;
57600   pVar = &p->aVar[i];
57601   sqlite3VdbeMemRelease(pVar);
57602   pVar->flags = MEM_Null;
57603   sqlite3Error(p->db, SQLITE_OK, 0);
57604
57605   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
57606   ** binding a new value to this variable invalidates the current query plan.
57607   */
57608   if( p->isPrepareV2 &&
57609      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
57610   ){
57611     p->expired = 1;
57612   }
57613   return SQLITE_OK;
57614 }
57615
57616 /*
57617 ** Bind a text or BLOB value.
57618 */
57619 static int bindText(
57620   sqlite3_stmt *pStmt,   /* The statement to bind against */
57621   int i,                 /* Index of the parameter to bind */
57622   const void *zData,     /* Pointer to the data to be bound */
57623   int nData,             /* Number of bytes of data to be bound */
57624   void (*xDel)(void*),   /* Destructor for the data */
57625   u8 encoding            /* Encoding for the data */
57626 ){
57627   Vdbe *p = (Vdbe *)pStmt;
57628   Mem *pVar;
57629   int rc;
57630
57631   rc = vdbeUnbind(p, i);
57632   if( rc==SQLITE_OK ){
57633     if( zData!=0 ){
57634       pVar = &p->aVar[i-1];
57635       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
57636       if( rc==SQLITE_OK && encoding!=0 ){
57637         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
57638       }
57639       sqlite3Error(p->db, rc, 0);
57640       rc = sqlite3ApiExit(p->db, rc);
57641     }
57642     sqlite3_mutex_leave(p->db->mutex);
57643   }
57644   return rc;
57645 }
57646
57647
57648 /*
57649 ** Bind a blob value to an SQL statement variable.
57650 */
57651 SQLITE_API int sqlite3_bind_blob(
57652   sqlite3_stmt *pStmt, 
57653   int i, 
57654   const void *zData, 
57655   int nData, 
57656   void (*xDel)(void*)
57657 ){
57658   return bindText(pStmt, i, zData, nData, xDel, 0);
57659 }
57660 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
57661   int rc;
57662   Vdbe *p = (Vdbe *)pStmt;
57663   rc = vdbeUnbind(p, i);
57664   if( rc==SQLITE_OK ){
57665     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
57666     sqlite3_mutex_leave(p->db->mutex);
57667   }
57668   return rc;
57669 }
57670 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
57671   return sqlite3_bind_int64(p, i, (i64)iValue);
57672 }
57673 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
57674   int rc;
57675   Vdbe *p = (Vdbe *)pStmt;
57676   rc = vdbeUnbind(p, i);
57677   if( rc==SQLITE_OK ){
57678     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
57679     sqlite3_mutex_leave(p->db->mutex);
57680   }
57681   return rc;
57682 }
57683 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
57684   int rc;
57685   Vdbe *p = (Vdbe*)pStmt;
57686   rc = vdbeUnbind(p, i);
57687   if( rc==SQLITE_OK ){
57688     sqlite3_mutex_leave(p->db->mutex);
57689   }
57690   return rc;
57691 }
57692 SQLITE_API int sqlite3_bind_text( 
57693   sqlite3_stmt *pStmt, 
57694   int i, 
57695   const char *zData, 
57696   int nData, 
57697   void (*xDel)(void*)
57698 ){
57699   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
57700 }
57701 #ifndef SQLITE_OMIT_UTF16
57702 SQLITE_API int sqlite3_bind_text16(
57703   sqlite3_stmt *pStmt, 
57704   int i, 
57705   const void *zData, 
57706   int nData, 
57707   void (*xDel)(void*)
57708 ){
57709   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
57710 }
57711 #endif /* SQLITE_OMIT_UTF16 */
57712 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
57713   int rc;
57714   switch( pValue->type ){
57715     case SQLITE_INTEGER: {
57716       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
57717       break;
57718     }
57719     case SQLITE_FLOAT: {
57720       rc = sqlite3_bind_double(pStmt, i, pValue->r);
57721       break;
57722     }
57723     case SQLITE_BLOB: {
57724       if( pValue->flags & MEM_Zero ){
57725         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
57726       }else{
57727         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
57728       }
57729       break;
57730     }
57731     case SQLITE_TEXT: {
57732       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
57733                               pValue->enc);
57734       break;
57735     }
57736     default: {
57737       rc = sqlite3_bind_null(pStmt, i);
57738       break;
57739     }
57740   }
57741   return rc;
57742 }
57743 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
57744   int rc;
57745   Vdbe *p = (Vdbe *)pStmt;
57746   rc = vdbeUnbind(p, i);
57747   if( rc==SQLITE_OK ){
57748     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
57749     sqlite3_mutex_leave(p->db->mutex);
57750   }
57751   return rc;
57752 }
57753
57754 /*
57755 ** Return the number of wildcards that can be potentially bound to.
57756 ** This routine is added to support DBD::SQLite.  
57757 */
57758 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
57759   Vdbe *p = (Vdbe*)pStmt;
57760   return p ? p->nVar : 0;
57761 }
57762
57763 /*
57764 ** Create a mapping from variable numbers to variable names
57765 ** in the Vdbe.azVar[] array, if such a mapping does not already
57766 ** exist.
57767 */
57768 static void createVarMap(Vdbe *p){
57769   if( !p->okVar ){
57770     int j;
57771     Op *pOp;
57772     sqlite3_mutex_enter(p->db->mutex);
57773     /* The race condition here is harmless.  If two threads call this
57774     ** routine on the same Vdbe at the same time, they both might end
57775     ** up initializing the Vdbe.azVar[] array.  That is a little extra
57776     ** work but it results in the same answer.
57777     */
57778     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
57779       if( pOp->opcode==OP_Variable ){
57780         assert( pOp->p1>0 && pOp->p1<=p->nVar );
57781         p->azVar[pOp->p1-1] = pOp->p4.z;
57782       }
57783     }
57784     p->okVar = 1;
57785     sqlite3_mutex_leave(p->db->mutex);
57786   }
57787 }
57788
57789 /*
57790 ** Return the name of a wildcard parameter.  Return NULL if the index
57791 ** is out of range or if the wildcard is unnamed.
57792 **
57793 ** The result is always UTF-8.
57794 */
57795 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
57796   Vdbe *p = (Vdbe*)pStmt;
57797   if( p==0 || i<1 || i>p->nVar ){
57798     return 0;
57799   }
57800   createVarMap(p);
57801   return p->azVar[i-1];
57802 }
57803
57804 /*
57805 ** Given a wildcard parameter name, return the index of the variable
57806 ** with that name.  If there is no variable with the given name,
57807 ** return 0.
57808 */
57809 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
57810   int i;
57811   if( p==0 ){
57812     return 0;
57813   }
57814   createVarMap(p); 
57815   if( zName ){
57816     for(i=0; i<p->nVar; i++){
57817       const char *z = p->azVar[i];
57818       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
57819         return i+1;
57820       }
57821     }
57822   }
57823   return 0;
57824 }
57825 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
57826   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
57827 }
57828
57829 /*
57830 ** Transfer all bindings from the first statement over to the second.
57831 */
57832 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57833   Vdbe *pFrom = (Vdbe*)pFromStmt;
57834   Vdbe *pTo = (Vdbe*)pToStmt;
57835   int i;
57836   assert( pTo->db==pFrom->db );
57837   assert( pTo->nVar==pFrom->nVar );
57838   sqlite3_mutex_enter(pTo->db->mutex);
57839   for(i=0; i<pFrom->nVar; i++){
57840     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
57841   }
57842   sqlite3_mutex_leave(pTo->db->mutex);
57843   return SQLITE_OK;
57844 }
57845
57846 #ifndef SQLITE_OMIT_DEPRECATED
57847 /*
57848 ** Deprecated external interface.  Internal/core SQLite code
57849 ** should call sqlite3TransferBindings.
57850 **
57851 ** Is is misuse to call this routine with statements from different
57852 ** database connections.  But as this is a deprecated interface, we
57853 ** will not bother to check for that condition.
57854 **
57855 ** If the two statements contain a different number of bindings, then
57856 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
57857 ** SQLITE_OK is returned.
57858 */
57859 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57860   Vdbe *pFrom = (Vdbe*)pFromStmt;
57861   Vdbe *pTo = (Vdbe*)pToStmt;
57862   if( pFrom->nVar!=pTo->nVar ){
57863     return SQLITE_ERROR;
57864   }
57865   if( pTo->isPrepareV2 && pTo->expmask ){
57866     pTo->expired = 1;
57867   }
57868   if( pFrom->isPrepareV2 && pFrom->expmask ){
57869     pFrom->expired = 1;
57870   }
57871   return sqlite3TransferBindings(pFromStmt, pToStmt);
57872 }
57873 #endif
57874
57875 /*
57876 ** Return the sqlite3* database handle to which the prepared statement given
57877 ** in the argument belongs.  This is the same database handle that was
57878 ** the first argument to the sqlite3_prepare() that was used to create
57879 ** the statement in the first place.
57880 */
57881 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
57882   return pStmt ? ((Vdbe*)pStmt)->db : 0;
57883 }
57884
57885 /*
57886 ** Return a pointer to the next prepared statement after pStmt associated
57887 ** with database connection pDb.  If pStmt is NULL, return the first
57888 ** prepared statement for the database connection.  Return NULL if there
57889 ** are no more.
57890 */
57891 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
57892   sqlite3_stmt *pNext;
57893   sqlite3_mutex_enter(pDb->mutex);
57894   if( pStmt==0 ){
57895     pNext = (sqlite3_stmt*)pDb->pVdbe;
57896   }else{
57897     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
57898   }
57899   sqlite3_mutex_leave(pDb->mutex);
57900   return pNext;
57901 }
57902
57903 /*
57904 ** Return the value of a status counter for a prepared statement
57905 */
57906 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
57907   Vdbe *pVdbe = (Vdbe*)pStmt;
57908   int v = pVdbe->aCounter[op-1];
57909   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
57910   return v;
57911 }
57912
57913 /************** End of vdbeapi.c *********************************************/
57914 /************** Begin file vdbetrace.c ***************************************/
57915 /*
57916 ** 2009 November 25
57917 **
57918 ** The author disclaims copyright to this source code.  In place of
57919 ** a legal notice, here is a blessing:
57920 **
57921 **    May you do good and not evil.
57922 **    May you find forgiveness for yourself and forgive others.
57923 **    May you share freely, never taking more than you give.
57924 **
57925 *************************************************************************
57926 **
57927 ** This file contains code used to insert the values of host parameters
57928 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
57929 */
57930
57931 #ifndef SQLITE_OMIT_TRACE
57932
57933 /*
57934 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
57935 ** bytes in this text up to but excluding the first character in
57936 ** a host parameter.  If the text contains no host parameters, return
57937 ** the total number of bytes in the text.
57938 */
57939 static int findNextHostParameter(const char *zSql, int *pnToken){
57940   int tokenType;
57941   int nTotal = 0;
57942   int n;
57943
57944   *pnToken = 0;
57945   while( zSql[0] ){
57946     n = sqlite3GetToken((u8*)zSql, &tokenType);
57947     assert( n>0 && tokenType!=TK_ILLEGAL );
57948     if( tokenType==TK_VARIABLE ){
57949       *pnToken = n;
57950       break;
57951     }
57952     nTotal += n;
57953     zSql += n;
57954   }
57955   return nTotal;
57956 }
57957
57958 /*
57959 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
57960 ** holds a copy of zRawSql but with host parameters expanded to their
57961 ** current bindings.
57962 **
57963 ** The calling function is responsible for making sure the memory returned
57964 ** is eventually freed.
57965 **
57966 ** ALGORITHM:  Scan the input string looking for host parameters in any of
57967 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
57968 ** string literals, quoted identifier names, and comments.  For text forms,
57969 ** the host parameter index is found by scanning the perpared
57970 ** statement for the corresponding OP_Variable opcode.  Once the host
57971 ** parameter index is known, locate the value in p->aVar[].  Then render
57972 ** the value as a literal in place of the host parameter name.
57973 */
57974 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
57975   Vdbe *p,                 /* The prepared statement being evaluated */
57976   const char *zRawSql      /* Raw text of the SQL statement */
57977 ){
57978   sqlite3 *db;             /* The database connection */
57979   int idx = 0;             /* Index of a host parameter */
57980   int nextIndex = 1;       /* Index of next ? host parameter */
57981   int n;                   /* Length of a token prefix */
57982   int nToken;              /* Length of the parameter token */
57983   int i;                   /* Loop counter */
57984   Mem *pVar;               /* Value of a host parameter */
57985   StrAccum out;            /* Accumulate the output here */
57986   char zBase[100];         /* Initial working space */
57987
57988   db = p->db;
57989   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
57990                       db->aLimit[SQLITE_LIMIT_LENGTH]);
57991   out.db = db;
57992   while( zRawSql[0] ){
57993     n = findNextHostParameter(zRawSql, &nToken);
57994     assert( n>0 );
57995     sqlite3StrAccumAppend(&out, zRawSql, n);
57996     zRawSql += n;
57997     assert( zRawSql[0] || nToken==0 );
57998     if( nToken==0 ) break;
57999     if( zRawSql[0]=='?' ){
58000       if( nToken>1 ){
58001         assert( sqlite3Isdigit(zRawSql[1]) );
58002         sqlite3GetInt32(&zRawSql[1], &idx);
58003       }else{
58004         idx = nextIndex;
58005       }
58006     }else{
58007       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
58008       testcase( zRawSql[0]==':' );
58009       testcase( zRawSql[0]=='$' );
58010       testcase( zRawSql[0]=='@' );
58011       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
58012       assert( idx>0 );
58013     }
58014     zRawSql += nToken;
58015     nextIndex = idx + 1;
58016     assert( idx>0 && idx<=p->nVar );
58017     pVar = &p->aVar[idx-1];
58018     if( pVar->flags & MEM_Null ){
58019       sqlite3StrAccumAppend(&out, "NULL", 4);
58020     }else if( pVar->flags & MEM_Int ){
58021       sqlite3XPrintf(&out, "%lld", pVar->u.i);
58022     }else if( pVar->flags & MEM_Real ){
58023       sqlite3XPrintf(&out, "%!.15g", pVar->r);
58024     }else if( pVar->flags & MEM_Str ){
58025 #ifndef SQLITE_OMIT_UTF16
58026       u8 enc = ENC(db);
58027       if( enc!=SQLITE_UTF8 ){
58028         Mem utf8;
58029         memset(&utf8, 0, sizeof(utf8));
58030         utf8.db = db;
58031         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
58032         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
58033         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
58034         sqlite3VdbeMemRelease(&utf8);
58035       }else
58036 #endif
58037       {
58038         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
58039       }
58040     }else if( pVar->flags & MEM_Zero ){
58041       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
58042     }else{
58043       assert( pVar->flags & MEM_Blob );
58044       sqlite3StrAccumAppend(&out, "x'", 2);
58045       for(i=0; i<pVar->n; i++){
58046         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
58047       }
58048       sqlite3StrAccumAppend(&out, "'", 1);
58049     }
58050   }
58051   return sqlite3StrAccumFinish(&out);
58052 }
58053
58054 #endif /* #ifndef SQLITE_OMIT_TRACE */
58055
58056 /************** End of vdbetrace.c *******************************************/
58057 /************** Begin file vdbe.c ********************************************/
58058 /*
58059 ** 2001 September 15
58060 **
58061 ** The author disclaims copyright to this source code.  In place of
58062 ** a legal notice, here is a blessing:
58063 **
58064 **    May you do good and not evil.
58065 **    May you find forgiveness for yourself and forgive others.
58066 **    May you share freely, never taking more than you give.
58067 **
58068 *************************************************************************
58069 ** The code in this file implements execution method of the 
58070 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
58071 ** handles housekeeping details such as creating and deleting
58072 ** VDBE instances.  This file is solely interested in executing
58073 ** the VDBE program.
58074 **
58075 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
58076 ** to a VDBE.
58077 **
58078 ** The SQL parser generates a program which is then executed by
58079 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
58080 ** similar in form to assembly language.  The program consists of
58081 ** a linear sequence of operations.  Each operation has an opcode 
58082 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
58083 ** is a null-terminated string.  Operand P5 is an unsigned character.
58084 ** Few opcodes use all 5 operands.
58085 **
58086 ** Computation results are stored on a set of registers numbered beginning
58087 ** with 1 and going up to Vdbe.nMem.  Each register can store
58088 ** either an integer, a null-terminated string, a floating point
58089 ** number, or the SQL "NULL" value.  An implicit conversion from one
58090 ** type to the other occurs as necessary.
58091 ** 
58092 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
58093 ** function which does the work of interpreting a VDBE program.
58094 ** But other routines are also provided to help in building up
58095 ** a program instruction by instruction.
58096 **
58097 ** Various scripts scan this source file in order to generate HTML
58098 ** documentation, headers files, or other derived files.  The formatting
58099 ** of the code in this file is, therefore, important.  See other comments
58100 ** in this file for details.  If in doubt, do not deviate from existing
58101 ** commenting and indentation practices when changing or adding code.
58102 */
58103
58104 /*
58105 ** The following global variable is incremented every time a cursor
58106 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
58107 ** procedures use this information to make sure that indices are
58108 ** working correctly.  This variable has no function other than to
58109 ** help verify the correct operation of the library.
58110 */
58111 #ifdef SQLITE_TEST
58112 SQLITE_API int sqlite3_search_count = 0;
58113 #endif
58114
58115 /*
58116 ** When this global variable is positive, it gets decremented once before
58117 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
58118 ** field of the sqlite3 structure is set in order to simulate and interrupt.
58119 **
58120 ** This facility is used for testing purposes only.  It does not function
58121 ** in an ordinary build.
58122 */
58123 #ifdef SQLITE_TEST
58124 SQLITE_API int sqlite3_interrupt_count = 0;
58125 #endif
58126
58127 /*
58128 ** The next global variable is incremented each type the OP_Sort opcode
58129 ** is executed.  The test procedures use this information to make sure that
58130 ** sorting is occurring or not occurring at appropriate times.   This variable
58131 ** has no function other than to help verify the correct operation of the
58132 ** library.
58133 */
58134 #ifdef SQLITE_TEST
58135 SQLITE_API int sqlite3_sort_count = 0;
58136 #endif
58137
58138 /*
58139 ** The next global variable records the size of the largest MEM_Blob
58140 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
58141 ** use this information to make sure that the zero-blob functionality
58142 ** is working correctly.   This variable has no function other than to
58143 ** help verify the correct operation of the library.
58144 */
58145 #ifdef SQLITE_TEST
58146 SQLITE_API int sqlite3_max_blobsize = 0;
58147 static void updateMaxBlobsize(Mem *p){
58148   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
58149     sqlite3_max_blobsize = p->n;
58150   }
58151 }
58152 #endif
58153
58154 /*
58155 ** The next global variable is incremented each type the OP_Found opcode
58156 ** is executed. This is used to test whether or not the foreign key
58157 ** operation implemented using OP_FkIsZero is working. This variable
58158 ** has no function other than to help verify the correct operation of the
58159 ** library.
58160 */
58161 #ifdef SQLITE_TEST
58162 SQLITE_API int sqlite3_found_count = 0;
58163 #endif
58164
58165 /*
58166 ** Test a register to see if it exceeds the current maximum blob size.
58167 ** If it does, record the new maximum blob size.
58168 */
58169 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
58170 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
58171 #else
58172 # define UPDATE_MAX_BLOBSIZE(P)
58173 #endif
58174
58175 /*
58176 ** Convert the given register into a string if it isn't one
58177 ** already. Return non-zero if a malloc() fails.
58178 */
58179 #define Stringify(P, enc) \
58180    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
58181      { goto no_mem; }
58182
58183 /*
58184 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
58185 ** a pointer to a dynamically allocated string where some other entity
58186 ** is responsible for deallocating that string.  Because the register
58187 ** does not control the string, it might be deleted without the register
58188 ** knowing it.
58189 **
58190 ** This routine converts an ephemeral string into a dynamically allocated
58191 ** string that the register itself controls.  In other words, it
58192 ** converts an MEM_Ephem string into an MEM_Dyn string.
58193 */
58194 #define Deephemeralize(P) \
58195    if( ((P)->flags&MEM_Ephem)!=0 \
58196        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
58197
58198 /*
58199 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
58200 ** P if required.
58201 */
58202 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
58203
58204 /*
58205 ** Argument pMem points at a register that will be passed to a
58206 ** user-defined function or returned to the user as the result of a query.
58207 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
58208 ** routines.
58209 */
58210 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
58211   int flags = pMem->flags;
58212   if( flags & MEM_Null ){
58213     pMem->type = SQLITE_NULL;
58214   }
58215   else if( flags & MEM_Int ){
58216     pMem->type = SQLITE_INTEGER;
58217   }
58218   else if( flags & MEM_Real ){
58219     pMem->type = SQLITE_FLOAT;
58220   }
58221   else if( flags & MEM_Str ){
58222     pMem->type = SQLITE_TEXT;
58223   }else{
58224     pMem->type = SQLITE_BLOB;
58225   }
58226 }
58227
58228 /*
58229 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
58230 ** if we run out of memory.
58231 */
58232 static VdbeCursor *allocateCursor(
58233   Vdbe *p,              /* The virtual machine */
58234   int iCur,             /* Index of the new VdbeCursor */
58235   int nField,           /* Number of fields in the table or index */
58236   int iDb,              /* When database the cursor belongs to, or -1 */
58237   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
58238 ){
58239   /* Find the memory cell that will be used to store the blob of memory
58240   ** required for this VdbeCursor structure. It is convenient to use a 
58241   ** vdbe memory cell to manage the memory allocation required for a
58242   ** VdbeCursor structure for the following reasons:
58243   **
58244   **   * Sometimes cursor numbers are used for a couple of different
58245   **     purposes in a vdbe program. The different uses might require
58246   **     different sized allocations. Memory cells provide growable
58247   **     allocations.
58248   **
58249   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
58250   **     be freed lazily via the sqlite3_release_memory() API. This
58251   **     minimizes the number of malloc calls made by the system.
58252   **
58253   ** Memory cells for cursors are allocated at the top of the address
58254   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
58255   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
58256   */
58257   Mem *pMem = &p->aMem[p->nMem-iCur];
58258
58259   int nByte;
58260   VdbeCursor *pCx = 0;
58261   nByte = 
58262       ROUND8(sizeof(VdbeCursor)) + 
58263       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
58264       2*nField*sizeof(u32);
58265
58266   assert( iCur<p->nCursor );
58267   if( p->apCsr[iCur] ){
58268     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
58269     p->apCsr[iCur] = 0;
58270   }
58271   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
58272     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
58273     memset(pCx, 0, sizeof(VdbeCursor));
58274     pCx->iDb = iDb;
58275     pCx->nField = nField;
58276     if( nField ){
58277       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
58278     }
58279     if( isBtreeCursor ){
58280       pCx->pCursor = (BtCursor*)
58281           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
58282       sqlite3BtreeCursorZero(pCx->pCursor);
58283     }
58284   }
58285   return pCx;
58286 }
58287
58288 /*
58289 ** Try to convert a value into a numeric representation if we can
58290 ** do so without loss of information.  In other words, if the string
58291 ** looks like a number, convert it into a number.  If it does not
58292 ** look like a number, leave it alone.
58293 */
58294 static void applyNumericAffinity(Mem *pRec){
58295   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
58296     int realnum;
58297     u8 enc = pRec->enc;
58298     sqlite3VdbeMemNulTerminate(pRec);
58299     if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){
58300       i64 value;
58301       char *zUtf8 = pRec->z;
58302 #ifndef SQLITE_OMIT_UTF16
58303       if( enc!=SQLITE_UTF8 ){
58304         assert( pRec->db );
58305         zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc);
58306         if( !zUtf8 ) return;
58307       }
58308 #endif
58309       if( !realnum && sqlite3Atoi64(zUtf8, &value) ){
58310         pRec->u.i = value;
58311         MemSetTypeFlag(pRec, MEM_Int);
58312       }else{
58313         sqlite3AtoF(zUtf8, &pRec->r);
58314         MemSetTypeFlag(pRec, MEM_Real);
58315       }
58316 #ifndef SQLITE_OMIT_UTF16
58317       if( enc!=SQLITE_UTF8 ){
58318         sqlite3DbFree(pRec->db, zUtf8);
58319       }
58320 #endif
58321     }
58322   }
58323 }
58324
58325 /*
58326 ** Processing is determine by the affinity parameter:
58327 **
58328 ** SQLITE_AFF_INTEGER:
58329 ** SQLITE_AFF_REAL:
58330 ** SQLITE_AFF_NUMERIC:
58331 **    Try to convert pRec to an integer representation or a 
58332 **    floating-point representation if an integer representation
58333 **    is not possible.  Note that the integer representation is
58334 **    always preferred, even if the affinity is REAL, because
58335 **    an integer representation is more space efficient on disk.
58336 **
58337 ** SQLITE_AFF_TEXT:
58338 **    Convert pRec to a text representation.
58339 **
58340 ** SQLITE_AFF_NONE:
58341 **    No-op.  pRec is unchanged.
58342 */
58343 static void applyAffinity(
58344   Mem *pRec,          /* The value to apply affinity to */
58345   char affinity,      /* The affinity to be applied */
58346   u8 enc              /* Use this text encoding */
58347 ){
58348   if( affinity==SQLITE_AFF_TEXT ){
58349     /* Only attempt the conversion to TEXT if there is an integer or real
58350     ** representation (blob and NULL do not get converted) but no string
58351     ** representation.
58352     */
58353     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
58354       sqlite3VdbeMemStringify(pRec, enc);
58355     }
58356     pRec->flags &= ~(MEM_Real|MEM_Int);
58357   }else if( affinity!=SQLITE_AFF_NONE ){
58358     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
58359              || affinity==SQLITE_AFF_NUMERIC );
58360     applyNumericAffinity(pRec);
58361     if( pRec->flags & MEM_Real ){
58362       sqlite3VdbeIntegerAffinity(pRec);
58363     }
58364   }
58365 }
58366
58367 /*
58368 ** Try to convert the type of a function argument or a result column
58369 ** into a numeric representation.  Use either INTEGER or REAL whichever
58370 ** is appropriate.  But only do the conversion if it is possible without
58371 ** loss of information and return the revised type of the argument.
58372 **
58373 ** This is an EXPERIMENTAL api and is subject to change or removal.
58374 */
58375 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
58376   Mem *pMem = (Mem*)pVal;
58377   applyNumericAffinity(pMem);
58378   sqlite3VdbeMemStoreType(pMem);
58379   return pMem->type;
58380 }
58381
58382 /*
58383 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
58384 ** not the internal Mem* type.
58385 */
58386 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
58387   sqlite3_value *pVal, 
58388   u8 affinity, 
58389   u8 enc
58390 ){
58391   applyAffinity((Mem *)pVal, affinity, enc);
58392 }
58393
58394 #ifdef SQLITE_DEBUG
58395 /*
58396 ** Write a nice string representation of the contents of cell pMem
58397 ** into buffer zBuf, length nBuf.
58398 */
58399 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
58400   char *zCsr = zBuf;
58401   int f = pMem->flags;
58402
58403   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
58404
58405   if( f&MEM_Blob ){
58406     int i;
58407     char c;
58408     if( f & MEM_Dyn ){
58409       c = 'z';
58410       assert( (f & (MEM_Static|MEM_Ephem))==0 );
58411     }else if( f & MEM_Static ){
58412       c = 't';
58413       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58414     }else if( f & MEM_Ephem ){
58415       c = 'e';
58416       assert( (f & (MEM_Static|MEM_Dyn))==0 );
58417     }else{
58418       c = 's';
58419     }
58420
58421     sqlite3_snprintf(100, zCsr, "%c", c);
58422     zCsr += sqlite3Strlen30(zCsr);
58423     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
58424     zCsr += sqlite3Strlen30(zCsr);
58425     for(i=0; i<16 && i<pMem->n; i++){
58426       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
58427       zCsr += sqlite3Strlen30(zCsr);
58428     }
58429     for(i=0; i<16 && i<pMem->n; i++){
58430       char z = pMem->z[i];
58431       if( z<32 || z>126 ) *zCsr++ = '.';
58432       else *zCsr++ = z;
58433     }
58434
58435     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
58436     zCsr += sqlite3Strlen30(zCsr);
58437     if( f & MEM_Zero ){
58438       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
58439       zCsr += sqlite3Strlen30(zCsr);
58440     }
58441     *zCsr = '\0';
58442   }else if( f & MEM_Str ){
58443     int j, k;
58444     zBuf[0] = ' ';
58445     if( f & MEM_Dyn ){
58446       zBuf[1] = 'z';
58447       assert( (f & (MEM_Static|MEM_Ephem))==0 );
58448     }else if( f & MEM_Static ){
58449       zBuf[1] = 't';
58450       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58451     }else if( f & MEM_Ephem ){
58452       zBuf[1] = 'e';
58453       assert( (f & (MEM_Static|MEM_Dyn))==0 );
58454     }else{
58455       zBuf[1] = 's';
58456     }
58457     k = 2;
58458     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
58459     k += sqlite3Strlen30(&zBuf[k]);
58460     zBuf[k++] = '[';
58461     for(j=0; j<15 && j<pMem->n; j++){
58462       u8 c = pMem->z[j];
58463       if( c>=0x20 && c<0x7f ){
58464         zBuf[k++] = c;
58465       }else{
58466         zBuf[k++] = '.';
58467       }
58468     }
58469     zBuf[k++] = ']';
58470     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
58471     k += sqlite3Strlen30(&zBuf[k]);
58472     zBuf[k++] = 0;
58473   }
58474 }
58475 #endif
58476
58477 #ifdef SQLITE_DEBUG
58478 /*
58479 ** Print the value of a register for tracing purposes:
58480 */
58481 static void memTracePrint(FILE *out, Mem *p){
58482   if( p->flags & MEM_Null ){
58483     fprintf(out, " NULL");
58484   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
58485     fprintf(out, " si:%lld", p->u.i);
58486   }else if( p->flags & MEM_Int ){
58487     fprintf(out, " i:%lld", p->u.i);
58488 #ifndef SQLITE_OMIT_FLOATING_POINT
58489   }else if( p->flags & MEM_Real ){
58490     fprintf(out, " r:%g", p->r);
58491 #endif
58492   }else if( p->flags & MEM_RowSet ){
58493     fprintf(out, " (rowset)");
58494   }else{
58495     char zBuf[200];
58496     sqlite3VdbeMemPrettyPrint(p, zBuf);
58497     fprintf(out, " ");
58498     fprintf(out, "%s", zBuf);
58499   }
58500 }
58501 static void registerTrace(FILE *out, int iReg, Mem *p){
58502   fprintf(out, "REG[%d] = ", iReg);
58503   memTracePrint(out, p);
58504   fprintf(out, "\n");
58505 }
58506 #endif
58507
58508 #ifdef SQLITE_DEBUG
58509 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
58510 #else
58511 #  define REGISTER_TRACE(R,M)
58512 #endif
58513
58514
58515 #ifdef VDBE_PROFILE
58516
58517 /* 
58518 ** hwtime.h contains inline assembler code for implementing 
58519 ** high-performance timing routines.
58520 */
58521 /************** Include hwtime.h in the middle of vdbe.c *********************/
58522 /************** Begin file hwtime.h ******************************************/
58523 /*
58524 ** 2008 May 27
58525 **
58526 ** The author disclaims copyright to this source code.  In place of
58527 ** a legal notice, here is a blessing:
58528 **
58529 **    May you do good and not evil.
58530 **    May you find forgiveness for yourself and forgive others.
58531 **    May you share freely, never taking more than you give.
58532 **
58533 ******************************************************************************
58534 **
58535 ** This file contains inline asm code for retrieving "high-performance"
58536 ** counters for x86 class CPUs.
58537 */
58538 #ifndef _HWTIME_H_
58539 #define _HWTIME_H_
58540
58541 /*
58542 ** The following routine only works on pentium-class (or newer) processors.
58543 ** It uses the RDTSC opcode to read the cycle count value out of the
58544 ** processor and returns that value.  This can be used for high-res
58545 ** profiling.
58546 */
58547 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
58548       (defined(i386) || defined(__i386__) || defined(_M_IX86))
58549
58550   #if defined(__GNUC__)
58551
58552   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58553      unsigned int lo, hi;
58554      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
58555      return (sqlite_uint64)hi << 32 | lo;
58556   }
58557
58558   #elif defined(_MSC_VER)
58559
58560   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
58561      __asm {
58562         rdtsc
58563         ret       ; return value at EDX:EAX
58564      }
58565   }
58566
58567   #endif
58568
58569 #elif (defined(__GNUC__) && defined(__x86_64__))
58570
58571   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58572       unsigned long val;
58573       __asm__ __volatile__ ("rdtsc" : "=A" (val));
58574       return val;
58575   }
58576  
58577 #elif (defined(__GNUC__) && defined(__ppc__))
58578
58579   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58580       unsigned long long retval;
58581       unsigned long junk;
58582       __asm__ __volatile__ ("\n\
58583           1:      mftbu   %1\n\
58584                   mftb    %L0\n\
58585                   mftbu   %0\n\
58586                   cmpw    %0,%1\n\
58587                   bne     1b"
58588                   : "=r" (retval), "=r" (junk));
58589       return retval;
58590   }
58591
58592 #else
58593
58594   #error Need implementation of sqlite3Hwtime() for your platform.
58595
58596   /*
58597   ** To compile without implementing sqlite3Hwtime() for your platform,
58598   ** you can remove the above #error and use the following
58599   ** stub function.  You will lose timing support for many
58600   ** of the debugging and testing utilities, but it should at
58601   ** least compile and run.
58602   */
58603 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
58604
58605 #endif
58606
58607 #endif /* !defined(_HWTIME_H_) */
58608
58609 /************** End of hwtime.h **********************************************/
58610 /************** Continuing where we left off in vdbe.c ***********************/
58611
58612 #endif
58613
58614 /*
58615 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
58616 ** sqlite3_interrupt() routine has been called.  If it has been, then
58617 ** processing of the VDBE program is interrupted.
58618 **
58619 ** This macro added to every instruction that does a jump in order to
58620 ** implement a loop.  This test used to be on every single instruction,
58621 ** but that meant we more testing that we needed.  By only testing the
58622 ** flag on jump instructions, we get a (small) speed improvement.
58623 */
58624 #define CHECK_FOR_INTERRUPT \
58625    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
58626
58627
58628 #ifndef NDEBUG
58629 /*
58630 ** This function is only called from within an assert() expression. It
58631 ** checks that the sqlite3.nTransaction variable is correctly set to
58632 ** the number of non-transaction savepoints currently in the 
58633 ** linked list starting at sqlite3.pSavepoint.
58634 ** 
58635 ** Usage:
58636 **
58637 **     assert( checkSavepointCount(db) );
58638 */
58639 static int checkSavepointCount(sqlite3 *db){
58640   int n = 0;
58641   Savepoint *p;
58642   for(p=db->pSavepoint; p; p=p->pNext) n++;
58643   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
58644   return 1;
58645 }
58646 #endif
58647
58648 /*
58649 ** Execute as much of a VDBE program as we can then return.
58650 **
58651 ** sqlite3VdbeMakeReady() must be called before this routine in order to
58652 ** close the program with a final OP_Halt and to set up the callbacks
58653 ** and the error message pointer.
58654 **
58655 ** Whenever a row or result data is available, this routine will either
58656 ** invoke the result callback (if there is one) or return with
58657 ** SQLITE_ROW.
58658 **
58659 ** If an attempt is made to open a locked database, then this routine
58660 ** will either invoke the busy callback (if there is one) or it will
58661 ** return SQLITE_BUSY.
58662 **
58663 ** If an error occurs, an error message is written to memory obtained
58664 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
58665 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
58666 **
58667 ** If the callback ever returns non-zero, then the program exits
58668 ** immediately.  There will be no error message but the p->rc field is
58669 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
58670 **
58671 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
58672 ** routine to return SQLITE_ERROR.
58673 **
58674 ** Other fatal errors return SQLITE_ERROR.
58675 **
58676 ** After this routine has finished, sqlite3VdbeFinalize() should be
58677 ** used to clean up the mess that was left behind.
58678 */
58679 SQLITE_PRIVATE int sqlite3VdbeExec(
58680   Vdbe *p                    /* The VDBE */
58681 ){
58682   int pc=0;                  /* The program counter */
58683   Op *aOp = p->aOp;          /* Copy of p->aOp */
58684   Op *pOp;                   /* Current operation */
58685   int rc = SQLITE_OK;        /* Value to return */
58686   sqlite3 *db = p->db;       /* The database */
58687   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
58688   u8 encoding = ENC(db);     /* The database encoding */
58689 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
58690   int checkProgress;         /* True if progress callbacks are enabled */
58691   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
58692 #endif
58693   Mem *aMem = p->aMem;       /* Copy of p->aMem */
58694   Mem *pIn1 = 0;             /* 1st input operand */
58695   Mem *pIn2 = 0;             /* 2nd input operand */
58696   Mem *pIn3 = 0;             /* 3rd input operand */
58697   Mem *pOut = 0;             /* Output operand */
58698   int iCompare = 0;          /* Result of last OP_Compare operation */
58699   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
58700 #ifdef VDBE_PROFILE
58701   u64 start;                 /* CPU clock count at start of opcode */
58702   int origPc;                /* Program counter at start of opcode */
58703 #endif
58704   /********************************************************************
58705   ** Automatically generated code
58706   **
58707   ** The following union is automatically generated by the
58708   ** vdbe-compress.tcl script.  The purpose of this union is to
58709   ** reduce the amount of stack space required by this function.
58710   ** See comments in the vdbe-compress.tcl script for details.
58711   */
58712   union vdbeExecUnion {
58713     struct OP_Yield_stack_vars {
58714       int pcDest;
58715     } aa;
58716     struct OP_Variable_stack_vars {
58717       Mem *pVar;       /* Value being transferred */
58718     } ab;
58719     struct OP_Move_stack_vars {
58720       char *zMalloc;   /* Holding variable for allocated memory */
58721       int n;           /* Number of registers left to copy */
58722       int p1;          /* Register to copy from */
58723       int p2;          /* Register to copy to */
58724     } ac;
58725     struct OP_ResultRow_stack_vars {
58726       Mem *pMem;
58727       int i;
58728     } ad;
58729     struct OP_Concat_stack_vars {
58730       i64 nByte;
58731     } ae;
58732     struct OP_Remainder_stack_vars {
58733       int flags;      /* Combined MEM_* flags from both inputs */
58734       i64 iA;         /* Integer value of left operand */
58735       i64 iB;         /* Integer value of right operand */
58736       double rA;      /* Real value of left operand */
58737       double rB;      /* Real value of right operand */
58738     } af;
58739     struct OP_Function_stack_vars {
58740       int i;
58741       Mem *pArg;
58742       sqlite3_context ctx;
58743       sqlite3_value **apVal;
58744       int n;
58745     } ag;
58746     struct OP_ShiftRight_stack_vars {
58747       i64 a;
58748       i64 b;
58749     } ah;
58750     struct OP_Ge_stack_vars {
58751       int res;            /* Result of the comparison of pIn1 against pIn3 */
58752       char affinity;      /* Affinity to use for comparison */
58753       u16 flags1;         /* Copy of initial value of pIn1->flags */
58754       u16 flags3;         /* Copy of initial value of pIn3->flags */
58755     } ai;
58756     struct OP_Compare_stack_vars {
58757       int n;
58758       int i;
58759       int p1;
58760       int p2;
58761       const KeyInfo *pKeyInfo;
58762       int idx;
58763       CollSeq *pColl;    /* Collating sequence to use on this term */
58764       int bRev;          /* True for DESCENDING sort order */
58765     } aj;
58766     struct OP_Or_stack_vars {
58767       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58768       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58769     } ak;
58770     struct OP_IfNot_stack_vars {
58771       int c;
58772     } al;
58773     struct OP_Column_stack_vars {
58774       u32 payloadSize;   /* Number of bytes in the record */
58775       i64 payloadSize64; /* Number of bytes in the record */
58776       int p1;            /* P1 value of the opcode */
58777       int p2;            /* column number to retrieve */
58778       VdbeCursor *pC;    /* The VDBE cursor */
58779       char *zRec;        /* Pointer to complete record-data */
58780       BtCursor *pCrsr;   /* The BTree cursor */
58781       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
58782       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
58783       int nField;        /* number of fields in the record */
58784       int len;           /* The length of the serialized data for the column */
58785       int i;             /* Loop counter */
58786       char *zData;       /* Part of the record being decoded */
58787       Mem *pDest;        /* Where to write the extracted value */
58788       Mem sMem;          /* For storing the record being decoded */
58789       u8 *zIdx;          /* Index into header */
58790       u8 *zEndHdr;       /* Pointer to first byte after the header */
58791       u32 offset;        /* Offset into the data */
58792       u32 szField;       /* Number of bytes in the content of a field */
58793       int szHdr;         /* Size of the header size field at start of record */
58794       int avail;         /* Number of bytes of available data */
58795       Mem *pReg;         /* PseudoTable input register */
58796     } am;
58797     struct OP_Affinity_stack_vars {
58798       const char *zAffinity;   /* The affinity to be applied */
58799       char cAff;               /* A single character of affinity */
58800     } an;
58801     struct OP_MakeRecord_stack_vars {
58802       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
58803       Mem *pRec;             /* The new record */
58804       u64 nData;             /* Number of bytes of data space */
58805       int nHdr;              /* Number of bytes of header space */
58806       i64 nByte;             /* Data space required for this record */
58807       int nZero;             /* Number of zero bytes at the end of the record */
58808       int nVarint;           /* Number of bytes in a varint */
58809       u32 serial_type;       /* Type field */
58810       Mem *pData0;           /* First field to be combined into the record */
58811       Mem *pLast;            /* Last field of the record */
58812       int nField;            /* Number of fields in the record */
58813       char *zAffinity;       /* The affinity string for the record */
58814       int file_format;       /* File format to use for encoding */
58815       int i;                 /* Space used in zNewRecord[] */
58816       int len;               /* Length of a field */
58817     } ao;
58818     struct OP_Count_stack_vars {
58819       i64 nEntry;
58820       BtCursor *pCrsr;
58821     } ap;
58822     struct OP_Savepoint_stack_vars {
58823       int p1;                         /* Value of P1 operand */
58824       char *zName;                    /* Name of savepoint */
58825       int nName;
58826       Savepoint *pNew;
58827       Savepoint *pSavepoint;
58828       Savepoint *pTmp;
58829       int iSavepoint;
58830       int ii;
58831     } aq;
58832     struct OP_AutoCommit_stack_vars {
58833       int desiredAutoCommit;
58834       int iRollback;
58835       int turnOnAC;
58836     } ar;
58837     struct OP_Transaction_stack_vars {
58838       Btree *pBt;
58839     } as;
58840     struct OP_ReadCookie_stack_vars {
58841       int iMeta;
58842       int iDb;
58843       int iCookie;
58844     } at;
58845     struct OP_SetCookie_stack_vars {
58846       Db *pDb;
58847     } au;
58848     struct OP_VerifyCookie_stack_vars {
58849       int iMeta;
58850       Btree *pBt;
58851     } av;
58852     struct OP_OpenWrite_stack_vars {
58853       int nField;
58854       KeyInfo *pKeyInfo;
58855       int p2;
58856       int iDb;
58857       int wrFlag;
58858       Btree *pX;
58859       VdbeCursor *pCur;
58860       Db *pDb;
58861     } aw;
58862     struct OP_OpenEphemeral_stack_vars {
58863       VdbeCursor *pCx;
58864     } ax;
58865     struct OP_OpenPseudo_stack_vars {
58866       VdbeCursor *pCx;
58867     } ay;
58868     struct OP_SeekGt_stack_vars {
58869       int res;
58870       int oc;
58871       VdbeCursor *pC;
58872       UnpackedRecord r;
58873       int nField;
58874       i64 iKey;      /* The rowid we are to seek to */
58875     } az;
58876     struct OP_Seek_stack_vars {
58877       VdbeCursor *pC;
58878     } ba;
58879     struct OP_Found_stack_vars {
58880       int alreadyExists;
58881       VdbeCursor *pC;
58882       int res;
58883       UnpackedRecord *pIdxKey;
58884       UnpackedRecord r;
58885       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
58886     } bb;
58887     struct OP_IsUnique_stack_vars {
58888       u16 ii;
58889       VdbeCursor *pCx;
58890       BtCursor *pCrsr;
58891       u16 nField;
58892       Mem *aMx;
58893       UnpackedRecord r;                  /* B-Tree index search key */
58894       i64 R;                             /* Rowid stored in register P3 */
58895     } bc;
58896     struct OP_NotExists_stack_vars {
58897       VdbeCursor *pC;
58898       BtCursor *pCrsr;
58899       int res;
58900       u64 iKey;
58901     } bd;
58902     struct OP_NewRowid_stack_vars {
58903       i64 v;                 /* The new rowid */
58904       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
58905       int res;               /* Result of an sqlite3BtreeLast() */
58906       int cnt;               /* Counter to limit the number of searches */
58907       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
58908       VdbeFrame *pFrame;     /* Root frame of VDBE */
58909     } be;
58910     struct OP_InsertInt_stack_vars {
58911       Mem *pData;       /* MEM cell holding data for the record to be inserted */
58912       Mem *pKey;        /* MEM cell holding key  for the record */
58913       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
58914       VdbeCursor *pC;   /* Cursor to table into which insert is written */
58915       int nZero;        /* Number of zero-bytes to append */
58916       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
58917       const char *zDb;  /* database name - used by the update hook */
58918       const char *zTbl; /* Table name - used by the opdate hook */
58919       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
58920     } bf;
58921     struct OP_Delete_stack_vars {
58922       i64 iKey;
58923       VdbeCursor *pC;
58924     } bg;
58925     struct OP_RowData_stack_vars {
58926       VdbeCursor *pC;
58927       BtCursor *pCrsr;
58928       u32 n;
58929       i64 n64;
58930     } bh;
58931     struct OP_Rowid_stack_vars {
58932       VdbeCursor *pC;
58933       i64 v;
58934       sqlite3_vtab *pVtab;
58935       const sqlite3_module *pModule;
58936     } bi;
58937     struct OP_NullRow_stack_vars {
58938       VdbeCursor *pC;
58939     } bj;
58940     struct OP_Last_stack_vars {
58941       VdbeCursor *pC;
58942       BtCursor *pCrsr;
58943       int res;
58944     } bk;
58945     struct OP_Rewind_stack_vars {
58946       VdbeCursor *pC;
58947       BtCursor *pCrsr;
58948       int res;
58949     } bl;
58950     struct OP_Next_stack_vars {
58951       VdbeCursor *pC;
58952       BtCursor *pCrsr;
58953       int res;
58954     } bm;
58955     struct OP_IdxInsert_stack_vars {
58956       VdbeCursor *pC;
58957       BtCursor *pCrsr;
58958       int nKey;
58959       const char *zKey;
58960     } bn;
58961     struct OP_IdxDelete_stack_vars {
58962       VdbeCursor *pC;
58963       BtCursor *pCrsr;
58964       int res;
58965       UnpackedRecord r;
58966     } bo;
58967     struct OP_IdxRowid_stack_vars {
58968       BtCursor *pCrsr;
58969       VdbeCursor *pC;
58970       i64 rowid;
58971     } bp;
58972     struct OP_IdxGE_stack_vars {
58973       VdbeCursor *pC;
58974       int res;
58975       UnpackedRecord r;
58976     } bq;
58977     struct OP_Destroy_stack_vars {
58978       int iMoved;
58979       int iCnt;
58980       Vdbe *pVdbe;
58981       int iDb;
58982     } br;
58983     struct OP_Clear_stack_vars {
58984       int nChange;
58985     } bs;
58986     struct OP_CreateTable_stack_vars {
58987       int pgno;
58988       int flags;
58989       Db *pDb;
58990     } bt;
58991     struct OP_ParseSchema_stack_vars {
58992       int iDb;
58993       const char *zMaster;
58994       char *zSql;
58995       InitData initData;
58996     } bu;
58997     struct OP_IntegrityCk_stack_vars {
58998       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
58999       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
59000       int j;          /* Loop counter */
59001       int nErr;       /* Number of errors reported */
59002       char *z;        /* Text of the error report */
59003       Mem *pnErr;     /* Register keeping track of errors remaining */
59004     } bv;
59005     struct OP_RowSetRead_stack_vars {
59006       i64 val;
59007     } bw;
59008     struct OP_RowSetTest_stack_vars {
59009       int iSet;
59010       int exists;
59011     } bx;
59012     struct OP_Program_stack_vars {
59013       int nMem;               /* Number of memory registers for sub-program */
59014       int nByte;              /* Bytes of runtime space required for sub-program */
59015       Mem *pRt;               /* Register to allocate runtime space */
59016       Mem *pMem;              /* Used to iterate through memory cells */
59017       Mem *pEnd;              /* Last memory cell in new array */
59018       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
59019       SubProgram *pProgram;   /* Sub-program to execute */
59020       void *t;                /* Token identifying trigger */
59021     } by;
59022     struct OP_Param_stack_vars {
59023       VdbeFrame *pFrame;
59024       Mem *pIn;
59025     } bz;
59026     struct OP_MemMax_stack_vars {
59027       Mem *pIn1;
59028       VdbeFrame *pFrame;
59029     } ca;
59030     struct OP_AggStep_stack_vars {
59031       int n;
59032       int i;
59033       Mem *pMem;
59034       Mem *pRec;
59035       sqlite3_context ctx;
59036       sqlite3_value **apVal;
59037     } cb;
59038     struct OP_AggFinal_stack_vars {
59039       Mem *pMem;
59040     } cc;
59041     struct OP_JournalMode_stack_vars {
59042       Btree *pBt;                     /* Btree to change journal mode of */
59043       Pager *pPager;                  /* Pager associated with pBt */
59044       int eNew;                       /* New journal mode */
59045       int eOld;                       /* The old journal mode */
59046       const char *zFilename;          /* Name of database file for pPager */
59047     } cd;
59048     struct OP_IncrVacuum_stack_vars {
59049       Btree *pBt;
59050     } ce;
59051     struct OP_VBegin_stack_vars {
59052       VTable *pVTab;
59053     } cf;
59054     struct OP_VOpen_stack_vars {
59055       VdbeCursor *pCur;
59056       sqlite3_vtab_cursor *pVtabCursor;
59057       sqlite3_vtab *pVtab;
59058       sqlite3_module *pModule;
59059     } cg;
59060     struct OP_VFilter_stack_vars {
59061       int nArg;
59062       int iQuery;
59063       const sqlite3_module *pModule;
59064       Mem *pQuery;
59065       Mem *pArgc;
59066       sqlite3_vtab_cursor *pVtabCursor;
59067       sqlite3_vtab *pVtab;
59068       VdbeCursor *pCur;
59069       int res;
59070       int i;
59071       Mem **apArg;
59072     } ch;
59073     struct OP_VColumn_stack_vars {
59074       sqlite3_vtab *pVtab;
59075       const sqlite3_module *pModule;
59076       Mem *pDest;
59077       sqlite3_context sContext;
59078     } ci;
59079     struct OP_VNext_stack_vars {
59080       sqlite3_vtab *pVtab;
59081       const sqlite3_module *pModule;
59082       int res;
59083       VdbeCursor *pCur;
59084     } cj;
59085     struct OP_VRename_stack_vars {
59086       sqlite3_vtab *pVtab;
59087       Mem *pName;
59088     } ck;
59089     struct OP_VUpdate_stack_vars {
59090       sqlite3_vtab *pVtab;
59091       sqlite3_module *pModule;
59092       int nArg;
59093       int i;
59094       sqlite_int64 rowid;
59095       Mem **apArg;
59096       Mem *pX;
59097     } cl;
59098     struct OP_Trace_stack_vars {
59099       char *zTrace;
59100     } cm;
59101   } u;
59102   /* End automatically generated code
59103   ********************************************************************/
59104
59105   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
59106   sqlite3VdbeMutexArrayEnter(p);
59107   if( p->rc==SQLITE_NOMEM ){
59108     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59109     ** sqlite3_column_text16() failed.  */
59110     goto no_mem;
59111   }
59112   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
59113   p->rc = SQLITE_OK;
59114   assert( p->explain==0 );
59115   p->pResultSet = 0;
59116   db->busyHandler.nBusy = 0;
59117   CHECK_FOR_INTERRUPT;
59118   sqlite3VdbeIOTraceSql(p);
59119 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
59120   checkProgress = db->xProgress!=0;
59121 #endif
59122 #ifdef SQLITE_DEBUG
59123   sqlite3BeginBenignMalloc();
59124   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
59125     int i;
59126     printf("VDBE Program Listing:\n");
59127     sqlite3VdbePrintSql(p);
59128     for(i=0; i<p->nOp; i++){
59129       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
59130     }
59131   }
59132   sqlite3EndBenignMalloc();
59133 #endif
59134   for(pc=p->pc; rc==SQLITE_OK; pc++){
59135     assert( pc>=0 && pc<p->nOp );
59136     if( db->mallocFailed ) goto no_mem;
59137 #ifdef VDBE_PROFILE
59138     origPc = pc;
59139     start = sqlite3Hwtime();
59140 #endif
59141     pOp = &aOp[pc];
59142
59143     /* Only allow tracing if SQLITE_DEBUG is defined.
59144     */
59145 #ifdef SQLITE_DEBUG
59146     if( p->trace ){
59147       if( pc==0 ){
59148         printf("VDBE Execution Trace:\n");
59149         sqlite3VdbePrintSql(p);
59150       }
59151       sqlite3VdbePrintOp(p->trace, pc, pOp);
59152     }
59153 #endif
59154       
59155
59156     /* Check to see if we need to simulate an interrupt.  This only happens
59157     ** if we have a special test build.
59158     */
59159 #ifdef SQLITE_TEST
59160     if( sqlite3_interrupt_count>0 ){
59161       sqlite3_interrupt_count--;
59162       if( sqlite3_interrupt_count==0 ){
59163         sqlite3_interrupt(db);
59164       }
59165     }
59166 #endif
59167
59168 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
59169     /* Call the progress callback if it is configured and the required number
59170     ** of VDBE ops have been executed (either since this invocation of
59171     ** sqlite3VdbeExec() or since last time the progress callback was called).
59172     ** If the progress callback returns non-zero, exit the virtual machine with
59173     ** a return code SQLITE_ABORT.
59174     */
59175     if( checkProgress ){
59176       if( db->nProgressOps==nProgressOps ){
59177         int prc;
59178         prc = db->xProgress(db->pProgressArg);
59179         if( prc!=0 ){
59180           rc = SQLITE_INTERRUPT;
59181           goto vdbe_error_halt;
59182         }
59183         nProgressOps = 0;
59184       }
59185       nProgressOps++;
59186     }
59187 #endif
59188
59189     /* On any opcode with the "out2-prerelase" tag, free any
59190     ** external allocations out of mem[p2] and set mem[p2] to be
59191     ** an undefined integer.  Opcodes will either fill in the integer
59192     ** value or convert mem[p2] to a different type.
59193     */
59194     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
59195     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
59196       assert( pOp->p2>0 );
59197       assert( pOp->p2<=p->nMem );
59198       pOut = &aMem[pOp->p2];
59199       sqlite3VdbeMemReleaseExternal(pOut);
59200       pOut->flags = MEM_Int;
59201     }
59202
59203     /* Sanity checking on other operands */
59204 #ifdef SQLITE_DEBUG
59205     if( (pOp->opflags & OPFLG_IN1)!=0 ){
59206       assert( pOp->p1>0 );
59207       assert( pOp->p1<=p->nMem );
59208       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
59209     }
59210     if( (pOp->opflags & OPFLG_IN2)!=0 ){
59211       assert( pOp->p2>0 );
59212       assert( pOp->p2<=p->nMem );
59213       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
59214     }
59215     if( (pOp->opflags & OPFLG_IN3)!=0 ){
59216       assert( pOp->p3>0 );
59217       assert( pOp->p3<=p->nMem );
59218       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
59219     }
59220     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
59221       assert( pOp->p2>0 );
59222       assert( pOp->p2<=p->nMem );
59223     }
59224     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
59225       assert( pOp->p3>0 );
59226       assert( pOp->p3<=p->nMem );
59227     }
59228 #endif
59229   
59230     switch( pOp->opcode ){
59231
59232 /*****************************************************************************
59233 ** What follows is a massive switch statement where each case implements a
59234 ** separate instruction in the virtual machine.  If we follow the usual
59235 ** indentation conventions, each case should be indented by 6 spaces.  But
59236 ** that is a lot of wasted space on the left margin.  So the code within
59237 ** the switch statement will break with convention and be flush-left. Another
59238 ** big comment (similar to this one) will mark the point in the code where
59239 ** we transition back to normal indentation.
59240 **
59241 ** The formatting of each case is important.  The makefile for SQLite
59242 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
59243 ** file looking for lines that begin with "case OP_".  The opcodes.h files
59244 ** will be filled with #defines that give unique integer values to each
59245 ** opcode and the opcodes.c file is filled with an array of strings where
59246 ** each string is the symbolic name for the corresponding opcode.  If the
59247 ** case statement is followed by a comment of the form "/# same as ... #/"
59248 ** that comment is used to determine the particular value of the opcode.
59249 **
59250 ** Other keywords in the comment that follows each case are used to
59251 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
59252 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
59253 ** the mkopcodeh.awk script for additional information.
59254 **
59255 ** Documentation about VDBE opcodes is generated by scanning this file
59256 ** for lines of that contain "Opcode:".  That line and all subsequent
59257 ** comment lines are used in the generation of the opcode.html documentation
59258 ** file.
59259 **
59260 ** SUMMARY:
59261 **
59262 **     Formatting is important to scripts that scan this file.
59263 **     Do not deviate from the formatting style currently in use.
59264 **
59265 *****************************************************************************/
59266
59267 /* Opcode:  Goto * P2 * * *
59268 **
59269 ** An unconditional jump to address P2.
59270 ** The next instruction executed will be 
59271 ** the one at index P2 from the beginning of
59272 ** the program.
59273 */
59274 case OP_Goto: {             /* jump */
59275   CHECK_FOR_INTERRUPT;
59276   pc = pOp->p2 - 1;
59277   break;
59278 }
59279
59280 /* Opcode:  Gosub P1 P2 * * *
59281 **
59282 ** Write the current address onto register P1
59283 ** and then jump to address P2.
59284 */
59285 case OP_Gosub: {            /* jump, in1 */
59286   pIn1 = &aMem[pOp->p1];
59287   assert( (pIn1->flags & MEM_Dyn)==0 );
59288   pIn1->flags = MEM_Int;
59289   pIn1->u.i = pc;
59290   REGISTER_TRACE(pOp->p1, pIn1);
59291   pc = pOp->p2 - 1;
59292   break;
59293 }
59294
59295 /* Opcode:  Return P1 * * * *
59296 **
59297 ** Jump to the next instruction after the address in register P1.
59298 */
59299 case OP_Return: {           /* in1 */
59300   pIn1 = &aMem[pOp->p1];
59301   assert( pIn1->flags & MEM_Int );
59302   pc = (int)pIn1->u.i;
59303   break;
59304 }
59305
59306 /* Opcode:  Yield P1 * * * *
59307 **
59308 ** Swap the program counter with the value in register P1.
59309 */
59310 case OP_Yield: {            /* in1 */
59311 #if 0  /* local variables moved into u.aa */
59312   int pcDest;
59313 #endif /* local variables moved into u.aa */
59314   pIn1 = &aMem[pOp->p1];
59315   assert( (pIn1->flags & MEM_Dyn)==0 );
59316   pIn1->flags = MEM_Int;
59317   u.aa.pcDest = (int)pIn1->u.i;
59318   pIn1->u.i = pc;
59319   REGISTER_TRACE(pOp->p1, pIn1);
59320   pc = u.aa.pcDest;
59321   break;
59322 }
59323
59324 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
59325 **
59326 ** Check the value in register P3.  If is is NULL then Halt using
59327 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
59328 ** value in register P3 is not NULL, then this routine is a no-op.
59329 */
59330 case OP_HaltIfNull: {      /* in3 */
59331   pIn3 = &aMem[pOp->p3];
59332   if( (pIn3->flags & MEM_Null)==0 ) break;
59333   /* Fall through into OP_Halt */
59334 }
59335
59336 /* Opcode:  Halt P1 P2 * P4 *
59337 **
59338 ** Exit immediately.  All open cursors, etc are closed
59339 ** automatically.
59340 **
59341 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
59342 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
59343 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
59344 ** whether or not to rollback the current transaction.  Do not rollback
59345 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
59346 ** then back out all changes that have occurred during this execution of the
59347 ** VDBE, but do not rollback the transaction. 
59348 **
59349 ** If P4 is not null then it is an error message string.
59350 **
59351 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
59352 ** every program.  So a jump past the last instruction of the program
59353 ** is the same as executing Halt.
59354 */
59355 case OP_Halt: {
59356   if( pOp->p1==SQLITE_OK && p->pFrame ){
59357     /* Halt the sub-program. Return control to the parent frame. */
59358     VdbeFrame *pFrame = p->pFrame;
59359     p->pFrame = pFrame->pParent;
59360     p->nFrame--;
59361     sqlite3VdbeSetChanges(db, p->nChange);
59362     pc = sqlite3VdbeFrameRestore(pFrame);
59363     if( pOp->p2==OE_Ignore ){
59364       /* Instruction pc is the OP_Program that invoked the sub-program 
59365       ** currently being halted. If the p2 instruction of this OP_Halt
59366       ** instruction is set to OE_Ignore, then the sub-program is throwing
59367       ** an IGNORE exception. In this case jump to the address specified
59368       ** as the p2 of the calling OP_Program.  */
59369       pc = p->aOp[pc].p2-1;
59370     }
59371     aOp = p->aOp;
59372     aMem = p->aMem;
59373     break;
59374   }
59375
59376   p->rc = pOp->p1;
59377   p->errorAction = (u8)pOp->p2;
59378   p->pc = pc;
59379   if( pOp->p4.z ){
59380     assert( p->rc!=SQLITE_OK );
59381     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
59382     testcase( sqlite3GlobalConfig.xLog!=0 );
59383     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
59384   }else if( p->rc ){
59385     testcase( sqlite3GlobalConfig.xLog!=0 );
59386     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
59387   }
59388   rc = sqlite3VdbeHalt(p);
59389   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
59390   if( rc==SQLITE_BUSY ){
59391     p->rc = rc = SQLITE_BUSY;
59392   }else{
59393     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
59394     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
59395     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
59396   }
59397   goto vdbe_return;
59398 }
59399
59400 /* Opcode: Integer P1 P2 * * *
59401 **
59402 ** The 32-bit integer value P1 is written into register P2.
59403 */
59404 case OP_Integer: {         /* out2-prerelease */
59405   pOut->u.i = pOp->p1;
59406   break;
59407 }
59408
59409 /* Opcode: Int64 * P2 * P4 *
59410 **
59411 ** P4 is a pointer to a 64-bit integer value.
59412 ** Write that value into register P2.
59413 */
59414 case OP_Int64: {           /* out2-prerelease */
59415   assert( pOp->p4.pI64!=0 );
59416   pOut->u.i = *pOp->p4.pI64;
59417   break;
59418 }
59419
59420 #ifndef SQLITE_OMIT_FLOATING_POINT
59421 /* Opcode: Real * P2 * P4 *
59422 **
59423 ** P4 is a pointer to a 64-bit floating point value.
59424 ** Write that value into register P2.
59425 */
59426 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
59427   pOut->flags = MEM_Real;
59428   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
59429   pOut->r = *pOp->p4.pReal;
59430   break;
59431 }
59432 #endif
59433
59434 /* Opcode: String8 * P2 * P4 *
59435 **
59436 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
59437 ** into an OP_String before it is executed for the first time.
59438 */
59439 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
59440   assert( pOp->p4.z!=0 );
59441   pOp->opcode = OP_String;
59442   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
59443
59444 #ifndef SQLITE_OMIT_UTF16
59445   if( encoding!=SQLITE_UTF8 ){
59446     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
59447     if( rc==SQLITE_TOOBIG ) goto too_big;
59448     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
59449     assert( pOut->zMalloc==pOut->z );
59450     assert( pOut->flags & MEM_Dyn );
59451     pOut->zMalloc = 0;
59452     pOut->flags |= MEM_Static;
59453     pOut->flags &= ~MEM_Dyn;
59454     if( pOp->p4type==P4_DYNAMIC ){
59455       sqlite3DbFree(db, pOp->p4.z);
59456     }
59457     pOp->p4type = P4_DYNAMIC;
59458     pOp->p4.z = pOut->z;
59459     pOp->p1 = pOut->n;
59460   }
59461 #endif
59462   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59463     goto too_big;
59464   }
59465   /* Fall through to the next case, OP_String */
59466 }
59467   
59468 /* Opcode: String P1 P2 * P4 *
59469 **
59470 ** The string value P4 of length P1 (bytes) is stored in register P2.
59471 */
59472 case OP_String: {          /* out2-prerelease */
59473   assert( pOp->p4.z!=0 );
59474   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
59475   pOut->z = pOp->p4.z;
59476   pOut->n = pOp->p1;
59477   pOut->enc = encoding;
59478   UPDATE_MAX_BLOBSIZE(pOut);
59479   break;
59480 }
59481
59482 /* Opcode: Null * P2 * * *
59483 **
59484 ** Write a NULL into register P2.
59485 */
59486 case OP_Null: {           /* out2-prerelease */
59487   pOut->flags = MEM_Null;
59488   break;
59489 }
59490
59491
59492 /* Opcode: Blob P1 P2 * P4
59493 **
59494 ** P4 points to a blob of data P1 bytes long.  Store this
59495 ** blob in register P2. This instruction is not coded directly
59496 ** by the compiler. Instead, the compiler layer specifies
59497 ** an OP_HexBlob opcode, with the hex string representation of
59498 ** the blob as P4. This opcode is transformed to an OP_Blob
59499 ** the first time it is executed.
59500 */
59501 case OP_Blob: {                /* out2-prerelease */
59502   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
59503   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
59504   pOut->enc = encoding;
59505   UPDATE_MAX_BLOBSIZE(pOut);
59506   break;
59507 }
59508
59509 /* Opcode: Variable P1 P2 * P4 *
59510 **
59511 ** Transfer the values of bound parameter P1 into register P2
59512 **
59513 ** If the parameter is named, then its name appears in P4 and P3==1.
59514 ** The P4 value is used by sqlite3_bind_parameter_name().
59515 */
59516 case OP_Variable: {            /* out2-prerelease */
59517 #if 0  /* local variables moved into u.ab */
59518   Mem *pVar;       /* Value being transferred */
59519 #endif /* local variables moved into u.ab */
59520
59521   assert( pOp->p1>0 && pOp->p1<=p->nVar );
59522   u.ab.pVar = &p->aVar[pOp->p1 - 1];
59523   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
59524     goto too_big;
59525   }
59526   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
59527   UPDATE_MAX_BLOBSIZE(pOut);
59528   break;
59529 }
59530
59531 /* Opcode: Move P1 P2 P3 * *
59532 **
59533 ** Move the values in register P1..P1+P3-1 over into
59534 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
59535 ** left holding a NULL.  It is an error for register ranges
59536 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
59537 */
59538 case OP_Move: {
59539 #if 0  /* local variables moved into u.ac */
59540   char *zMalloc;   /* Holding variable for allocated memory */
59541   int n;           /* Number of registers left to copy */
59542   int p1;          /* Register to copy from */
59543   int p2;          /* Register to copy to */
59544 #endif /* local variables moved into u.ac */
59545
59546   u.ac.n = pOp->p3;
59547   u.ac.p1 = pOp->p1;
59548   u.ac.p2 = pOp->p2;
59549   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
59550   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
59551
59552   pIn1 = &aMem[u.ac.p1];
59553   pOut = &aMem[u.ac.p2];
59554   while( u.ac.n-- ){
59555     assert( pOut<=&aMem[p->nMem] );
59556     assert( pIn1<=&aMem[p->nMem] );
59557     u.ac.zMalloc = pOut->zMalloc;
59558     pOut->zMalloc = 0;
59559     sqlite3VdbeMemMove(pOut, pIn1);
59560     pIn1->zMalloc = u.ac.zMalloc;
59561     REGISTER_TRACE(u.ac.p2++, pOut);
59562     pIn1++;
59563     pOut++;
59564   }
59565   break;
59566 }
59567
59568 /* Opcode: Copy P1 P2 * * *
59569 **
59570 ** Make a copy of register P1 into register P2.
59571 **
59572 ** This instruction makes a deep copy of the value.  A duplicate
59573 ** is made of any string or blob constant.  See also OP_SCopy.
59574 */
59575 case OP_Copy: {             /* in1, out2 */
59576   pIn1 = &aMem[pOp->p1];
59577   pOut = &aMem[pOp->p2];
59578   assert( pOut!=pIn1 );
59579   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59580   Deephemeralize(pOut);
59581   REGISTER_TRACE(pOp->p2, pOut);
59582   break;
59583 }
59584
59585 /* Opcode: SCopy P1 P2 * * *
59586 **
59587 ** Make a shallow copy of register P1 into register P2.
59588 **
59589 ** This instruction makes a shallow copy of the value.  If the value
59590 ** is a string or blob, then the copy is only a pointer to the
59591 ** original and hence if the original changes so will the copy.
59592 ** Worse, if the original is deallocated, the copy becomes invalid.
59593 ** Thus the program must guarantee that the original will not change
59594 ** during the lifetime of the copy.  Use OP_Copy to make a complete
59595 ** copy.
59596 */
59597 case OP_SCopy: {            /* in1, out2 */
59598   pIn1 = &aMem[pOp->p1];
59599   pOut = &aMem[pOp->p2];
59600   assert( pOut!=pIn1 );
59601   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59602   REGISTER_TRACE(pOp->p2, pOut);
59603   break;
59604 }
59605
59606 /* Opcode: ResultRow P1 P2 * * *
59607 **
59608 ** The registers P1 through P1+P2-1 contain a single row of
59609 ** results. This opcode causes the sqlite3_step() call to terminate
59610 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
59611 ** structure to provide access to the top P1 values as the result
59612 ** row.
59613 */
59614 case OP_ResultRow: {
59615 #if 0  /* local variables moved into u.ad */
59616   Mem *pMem;
59617   int i;
59618 #endif /* local variables moved into u.ad */
59619   assert( p->nResColumn==pOp->p2 );
59620   assert( pOp->p1>0 );
59621   assert( pOp->p1+pOp->p2<=p->nMem+1 );
59622
59623   /* If this statement has violated immediate foreign key constraints, do
59624   ** not return the number of rows modified. And do not RELEASE the statement
59625   ** transaction. It needs to be rolled back.  */
59626   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
59627     assert( db->flags&SQLITE_CountRows );
59628     assert( p->usesStmtJournal );
59629     break;
59630   }
59631
59632   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
59633   ** DML statements invoke this opcode to return the number of rows
59634   ** modified to the user. This is the only way that a VM that
59635   ** opens a statement transaction may invoke this opcode.
59636   **
59637   ** In case this is such a statement, close any statement transaction
59638   ** opened by this VM before returning control to the user. This is to
59639   ** ensure that statement-transactions are always nested, not overlapping.
59640   ** If the open statement-transaction is not closed here, then the user
59641   ** may step another VM that opens its own statement transaction. This
59642   ** may lead to overlapping statement transactions.
59643   **
59644   ** The statement transaction is never a top-level transaction.  Hence
59645   ** the RELEASE call below can never fail.
59646   */
59647   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
59648   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
59649   if( NEVER(rc!=SQLITE_OK) ){
59650     break;
59651   }
59652
59653   /* Invalidate all ephemeral cursor row caches */
59654   p->cacheCtr = (p->cacheCtr + 2)|1;
59655
59656   /* Make sure the results of the current row are \000 terminated
59657   ** and have an assigned type.  The results are de-ephemeralized as
59658   ** as side effect.
59659   */
59660   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
59661   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
59662     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
59663     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
59664     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
59665   }
59666   if( db->mallocFailed ) goto no_mem;
59667
59668   /* Return SQLITE_ROW
59669   */
59670   p->pc = pc + 1;
59671   rc = SQLITE_ROW;
59672   goto vdbe_return;
59673 }
59674
59675 /* Opcode: Concat P1 P2 P3 * *
59676 **
59677 ** Add the text in register P1 onto the end of the text in
59678 ** register P2 and store the result in register P3.
59679 ** If either the P1 or P2 text are NULL then store NULL in P3.
59680 **
59681 **   P3 = P2 || P1
59682 **
59683 ** It is illegal for P1 and P3 to be the same register. Sometimes,
59684 ** if P3 is the same register as P2, the implementation is able
59685 ** to avoid a memcpy().
59686 */
59687 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
59688 #if 0  /* local variables moved into u.ae */
59689   i64 nByte;
59690 #endif /* local variables moved into u.ae */
59691
59692   pIn1 = &aMem[pOp->p1];
59693   pIn2 = &aMem[pOp->p2];
59694   pOut = &aMem[pOp->p3];
59695   assert( pIn1!=pOut );
59696   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
59697     sqlite3VdbeMemSetNull(pOut);
59698     break;
59699   }
59700   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
59701   Stringify(pIn1, encoding);
59702   Stringify(pIn2, encoding);
59703   u.ae.nByte = pIn1->n + pIn2->n;
59704   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59705     goto too_big;
59706   }
59707   MemSetTypeFlag(pOut, MEM_Str);
59708   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
59709     goto no_mem;
59710   }
59711   if( pOut!=pIn2 ){
59712     memcpy(pOut->z, pIn2->z, pIn2->n);
59713   }
59714   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
59715   pOut->z[u.ae.nByte] = 0;
59716   pOut->z[u.ae.nByte+1] = 0;
59717   pOut->flags |= MEM_Term;
59718   pOut->n = (int)u.ae.nByte;
59719   pOut->enc = encoding;
59720   UPDATE_MAX_BLOBSIZE(pOut);
59721   break;
59722 }
59723
59724 /* Opcode: Add P1 P2 P3 * *
59725 **
59726 ** Add the value in register P1 to the value in register P2
59727 ** and store the result in register P3.
59728 ** If either input is NULL, the result is NULL.
59729 */
59730 /* Opcode: Multiply P1 P2 P3 * *
59731 **
59732 **
59733 ** Multiply the value in register P1 by the value in register P2
59734 ** and store the result in register P3.
59735 ** If either input is NULL, the result is NULL.
59736 */
59737 /* Opcode: Subtract P1 P2 P3 * *
59738 **
59739 ** Subtract the value in register P1 from the value in register P2
59740 ** and store the result in register P3.
59741 ** If either input is NULL, the result is NULL.
59742 */
59743 /* Opcode: Divide P1 P2 P3 * *
59744 **
59745 ** Divide the value in register P1 by the value in register P2
59746 ** and store the result in register P3 (P3=P2/P1). If the value in 
59747 ** register P1 is zero, then the result is NULL. If either input is 
59748 ** NULL, the result is NULL.
59749 */
59750 /* Opcode: Remainder P1 P2 P3 * *
59751 **
59752 ** Compute the remainder after integer division of the value in
59753 ** register P1 by the value in register P2 and store the result in P3. 
59754 ** If the value in register P2 is zero the result is NULL.
59755 ** If either operand is NULL, the result is NULL.
59756 */
59757 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
59758 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
59759 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
59760 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
59761 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
59762 #if 0  /* local variables moved into u.af */
59763   int flags;      /* Combined MEM_* flags from both inputs */
59764   i64 iA;         /* Integer value of left operand */
59765   i64 iB;         /* Integer value of right operand */
59766   double rA;      /* Real value of left operand */
59767   double rB;      /* Real value of right operand */
59768 #endif /* local variables moved into u.af */
59769
59770   pIn1 = &aMem[pOp->p1];
59771   applyNumericAffinity(pIn1);
59772   pIn2 = &aMem[pOp->p2];
59773   applyNumericAffinity(pIn2);
59774   pOut = &aMem[pOp->p3];
59775   u.af.flags = pIn1->flags | pIn2->flags;
59776   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
59777   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
59778     u.af.iA = pIn1->u.i;
59779     u.af.iB = pIn2->u.i;
59780     switch( pOp->opcode ){
59781       case OP_Add:         u.af.iB += u.af.iA;       break;
59782       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
59783       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
59784       case OP_Divide: {
59785         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59786         /* Dividing the largest possible negative 64-bit integer (1<<63) by
59787         ** -1 returns an integer too large to store in a 64-bit data-type. On
59788         ** some architectures, the value overflows to (1<<63). On others,
59789         ** a SIGFPE is issued. The following statement normalizes this
59790         ** behavior so that all architectures behave as if integer
59791         ** overflow occurred.
59792         */
59793         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
59794         u.af.iB /= u.af.iA;
59795         break;
59796       }
59797       default: {
59798         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59799         if( u.af.iA==-1 ) u.af.iA = 1;
59800         u.af.iB %= u.af.iA;
59801         break;
59802       }
59803     }
59804     pOut->u.i = u.af.iB;
59805     MemSetTypeFlag(pOut, MEM_Int);
59806   }else{
59807     u.af.rA = sqlite3VdbeRealValue(pIn1);
59808     u.af.rB = sqlite3VdbeRealValue(pIn2);
59809     switch( pOp->opcode ){
59810       case OP_Add:         u.af.rB += u.af.rA;       break;
59811       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
59812       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
59813       case OP_Divide: {
59814         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59815         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
59816         u.af.rB /= u.af.rA;
59817         break;
59818       }
59819       default: {
59820         u.af.iA = (i64)u.af.rA;
59821         u.af.iB = (i64)u.af.rB;
59822         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59823         if( u.af.iA==-1 ) u.af.iA = 1;
59824         u.af.rB = (double)(u.af.iB % u.af.iA);
59825         break;
59826       }
59827     }
59828 #ifdef SQLITE_OMIT_FLOATING_POINT
59829     pOut->u.i = u.af.rB;
59830     MemSetTypeFlag(pOut, MEM_Int);
59831 #else
59832     if( sqlite3IsNaN(u.af.rB) ){
59833       goto arithmetic_result_is_null;
59834     }
59835     pOut->r = u.af.rB;
59836     MemSetTypeFlag(pOut, MEM_Real);
59837     if( (u.af.flags & MEM_Real)==0 ){
59838       sqlite3VdbeIntegerAffinity(pOut);
59839     }
59840 #endif
59841   }
59842   break;
59843
59844 arithmetic_result_is_null:
59845   sqlite3VdbeMemSetNull(pOut);
59846   break;
59847 }
59848
59849 /* Opcode: CollSeq * * P4
59850 **
59851 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
59852 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
59853 ** be returned. This is used by the built-in min(), max() and nullif()
59854 ** functions.
59855 **
59856 ** The interface used by the implementation of the aforementioned functions
59857 ** to retrieve the collation sequence set by this opcode is not available
59858 ** publicly, only to user functions defined in func.c.
59859 */
59860 case OP_CollSeq: {
59861   assert( pOp->p4type==P4_COLLSEQ );
59862   break;
59863 }
59864
59865 /* Opcode: Function P1 P2 P3 P4 P5
59866 **
59867 ** Invoke a user function (P4 is a pointer to a Function structure that
59868 ** defines the function) with P5 arguments taken from register P2 and
59869 ** successors.  The result of the function is stored in register P3.
59870 ** Register P3 must not be one of the function inputs.
59871 **
59872 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
59873 ** function was determined to be constant at compile time. If the first
59874 ** argument was constant then bit 0 of P1 is set. This is used to determine
59875 ** whether meta data associated with a user function argument using the
59876 ** sqlite3_set_auxdata() API may be safely retained until the next
59877 ** invocation of this opcode.
59878 **
59879 ** See also: AggStep and AggFinal
59880 */
59881 case OP_Function: {
59882 #if 0  /* local variables moved into u.ag */
59883   int i;
59884   Mem *pArg;
59885   sqlite3_context ctx;
59886   sqlite3_value **apVal;
59887   int n;
59888 #endif /* local variables moved into u.ag */
59889
59890   u.ag.n = pOp->p5;
59891   u.ag.apVal = p->apArg;
59892   assert( u.ag.apVal || u.ag.n==0 );
59893
59894   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
59895   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
59896   u.ag.pArg = &aMem[pOp->p2];
59897   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
59898     u.ag.apVal[u.ag.i] = u.ag.pArg;
59899     sqlite3VdbeMemStoreType(u.ag.pArg);
59900     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
59901   }
59902
59903   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
59904   if( pOp->p4type==P4_FUNCDEF ){
59905     u.ag.ctx.pFunc = pOp->p4.pFunc;
59906     u.ag.ctx.pVdbeFunc = 0;
59907   }else{
59908     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
59909     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
59910   }
59911
59912   assert( pOp->p3>0 && pOp->p3<=p->nMem );
59913   pOut = &aMem[pOp->p3];
59914   u.ag.ctx.s.flags = MEM_Null;
59915   u.ag.ctx.s.db = db;
59916   u.ag.ctx.s.xDel = 0;
59917   u.ag.ctx.s.zMalloc = 0;
59918
59919   /* The output cell may already have a buffer allocated. Move
59920   ** the pointer to u.ag.ctx.s so in case the user-function can use
59921   ** the already allocated buffer instead of allocating a new one.
59922   */
59923   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
59924   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
59925
59926   u.ag.ctx.isError = 0;
59927   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
59928     assert( pOp>aOp );
59929     assert( pOp[-1].p4type==P4_COLLSEQ );
59930     assert( pOp[-1].opcode==OP_CollSeq );
59931     u.ag.ctx.pColl = pOp[-1].p4.pColl;
59932   }
59933   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
59934   if( db->mallocFailed ){
59935     /* Even though a malloc() has failed, the implementation of the
59936     ** user function may have called an sqlite3_result_XXX() function
59937     ** to return a value. The following call releases any resources
59938     ** associated with such a value.
59939     */
59940     sqlite3VdbeMemRelease(&u.ag.ctx.s);
59941     goto no_mem;
59942   }
59943
59944   /* If any auxiliary data functions have been called by this user function,
59945   ** immediately call the destructor for any non-static values.
59946   */
59947   if( u.ag.ctx.pVdbeFunc ){
59948     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
59949     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
59950     pOp->p4type = P4_VDBEFUNC;
59951   }
59952
59953   /* If the function returned an error, throw an exception */
59954   if( u.ag.ctx.isError ){
59955     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
59956     rc = u.ag.ctx.isError;
59957   }
59958
59959   /* Copy the result of the function into register P3 */
59960   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
59961   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
59962   if( sqlite3VdbeMemTooBig(pOut) ){
59963     goto too_big;
59964   }
59965   REGISTER_TRACE(pOp->p3, pOut);
59966   UPDATE_MAX_BLOBSIZE(pOut);
59967   break;
59968 }
59969
59970 /* Opcode: BitAnd P1 P2 P3 * *
59971 **
59972 ** Take the bit-wise AND of the values in register P1 and P2 and
59973 ** store the result in register P3.
59974 ** If either input is NULL, the result is NULL.
59975 */
59976 /* Opcode: BitOr P1 P2 P3 * *
59977 **
59978 ** Take the bit-wise OR of the values in register P1 and P2 and
59979 ** store the result in register P3.
59980 ** If either input is NULL, the result is NULL.
59981 */
59982 /* Opcode: ShiftLeft P1 P2 P3 * *
59983 **
59984 ** Shift the integer value in register P2 to the left by the
59985 ** number of bits specified by the integer in regiser P1.
59986 ** Store the result in register P3.
59987 ** If either input is NULL, the result is NULL.
59988 */
59989 /* Opcode: ShiftRight P1 P2 P3 * *
59990 **
59991 ** Shift the integer value in register P2 to the right by the
59992 ** number of bits specified by the integer in register P1.
59993 ** Store the result in register P3.
59994 ** If either input is NULL, the result is NULL.
59995 */
59996 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
59997 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
59998 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
59999 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
60000 #if 0  /* local variables moved into u.ah */
60001   i64 a;
60002   i64 b;
60003 #endif /* local variables moved into u.ah */
60004
60005   pIn1 = &aMem[pOp->p1];
60006   pIn2 = &aMem[pOp->p2];
60007   pOut = &aMem[pOp->p3];
60008   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
60009     sqlite3VdbeMemSetNull(pOut);
60010     break;
60011   }
60012   u.ah.a = sqlite3VdbeIntValue(pIn2);
60013   u.ah.b = sqlite3VdbeIntValue(pIn1);
60014   switch( pOp->opcode ){
60015     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
60016     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
60017     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
60018     default:  assert( pOp->opcode==OP_ShiftRight );
60019                          u.ah.a >>= u.ah.b;    break;
60020   }
60021   pOut->u.i = u.ah.a;
60022   MemSetTypeFlag(pOut, MEM_Int);
60023   break;
60024 }
60025
60026 /* Opcode: AddImm  P1 P2 * * *
60027 ** 
60028 ** Add the constant P2 to the value in register P1.
60029 ** The result is always an integer.
60030 **
60031 ** To force any register to be an integer, just add 0.
60032 */
60033 case OP_AddImm: {            /* in1 */
60034   pIn1 = &aMem[pOp->p1];
60035   sqlite3VdbeMemIntegerify(pIn1);
60036   pIn1->u.i += pOp->p2;
60037   break;
60038 }
60039
60040 /* Opcode: MustBeInt P1 P2 * * *
60041 ** 
60042 ** Force the value in register P1 to be an integer.  If the value
60043 ** in P1 is not an integer and cannot be converted into an integer
60044 ** without data loss, then jump immediately to P2, or if P2==0
60045 ** raise an SQLITE_MISMATCH exception.
60046 */
60047 case OP_MustBeInt: {            /* jump, in1 */
60048   pIn1 = &aMem[pOp->p1];
60049   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
60050   if( (pIn1->flags & MEM_Int)==0 ){
60051     if( pOp->p2==0 ){
60052       rc = SQLITE_MISMATCH;
60053       goto abort_due_to_error;
60054     }else{
60055       pc = pOp->p2 - 1;
60056     }
60057   }else{
60058     MemSetTypeFlag(pIn1, MEM_Int);
60059   }
60060   break;
60061 }
60062
60063 #ifndef SQLITE_OMIT_FLOATING_POINT
60064 /* Opcode: RealAffinity P1 * * * *
60065 **
60066 ** If register P1 holds an integer convert it to a real value.
60067 **
60068 ** This opcode is used when extracting information from a column that
60069 ** has REAL affinity.  Such column values may still be stored as
60070 ** integers, for space efficiency, but after extraction we want them
60071 ** to have only a real value.
60072 */
60073 case OP_RealAffinity: {                  /* in1 */
60074   pIn1 = &aMem[pOp->p1];
60075   if( pIn1->flags & MEM_Int ){
60076     sqlite3VdbeMemRealify(pIn1);
60077   }
60078   break;
60079 }
60080 #endif
60081
60082 #ifndef SQLITE_OMIT_CAST
60083 /* Opcode: ToText P1 * * * *
60084 **
60085 ** Force the value in register P1 to be text.
60086 ** If the value is numeric, convert it to a string using the
60087 ** equivalent of printf().  Blob values are unchanged and
60088 ** are afterwards simply interpreted as text.
60089 **
60090 ** A NULL value is not changed by this routine.  It remains NULL.
60091 */
60092 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
60093   pIn1 = &aMem[pOp->p1];
60094   if( pIn1->flags & MEM_Null ) break;
60095   assert( MEM_Str==(MEM_Blob>>3) );
60096   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
60097   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
60098   rc = ExpandBlob(pIn1);
60099   assert( pIn1->flags & MEM_Str || db->mallocFailed );
60100   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
60101   UPDATE_MAX_BLOBSIZE(pIn1);
60102   break;
60103 }
60104
60105 /* Opcode: ToBlob P1 * * * *
60106 **
60107 ** Force the value in register P1 to be a BLOB.
60108 ** If the value is numeric, convert it to a string first.
60109 ** Strings are simply reinterpreted as blobs with no change
60110 ** to the underlying data.
60111 **
60112 ** A NULL value is not changed by this routine.  It remains NULL.
60113 */
60114 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
60115   pIn1 = &aMem[pOp->p1];
60116   if( pIn1->flags & MEM_Null ) break;
60117   if( (pIn1->flags & MEM_Blob)==0 ){
60118     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
60119     assert( pIn1->flags & MEM_Str || db->mallocFailed );
60120     MemSetTypeFlag(pIn1, MEM_Blob);
60121   }else{
60122     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
60123   }
60124   UPDATE_MAX_BLOBSIZE(pIn1);
60125   break;
60126 }
60127
60128 /* Opcode: ToNumeric P1 * * * *
60129 **
60130 ** Force the value in register P1 to be numeric (either an
60131 ** integer or a floating-point number.)
60132 ** If the value is text or blob, try to convert it to an using the
60133 ** equivalent of atoi() or atof() and store 0 if no such conversion 
60134 ** is possible.
60135 **
60136 ** A NULL value is not changed by this routine.  It remains NULL.
60137 */
60138 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
60139   pIn1 = &aMem[pOp->p1];
60140   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
60141     sqlite3VdbeMemNumerify(pIn1);
60142   }
60143   break;
60144 }
60145 #endif /* SQLITE_OMIT_CAST */
60146
60147 /* Opcode: ToInt P1 * * * *
60148 **
60149 ** Force the value in register P1 be an integer.  If
60150 ** The value is currently a real number, drop its fractional part.
60151 ** If the value is text or blob, try to convert it to an integer using the
60152 ** equivalent of atoi() and store 0 if no such conversion is possible.
60153 **
60154 ** A NULL value is not changed by this routine.  It remains NULL.
60155 */
60156 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
60157   pIn1 = &aMem[pOp->p1];
60158   if( (pIn1->flags & MEM_Null)==0 ){
60159     sqlite3VdbeMemIntegerify(pIn1);
60160   }
60161   break;
60162 }
60163
60164 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
60165 /* Opcode: ToReal P1 * * * *
60166 **
60167 ** Force the value in register P1 to be a floating point number.
60168 ** If The value is currently an integer, convert it.
60169 ** If the value is text or blob, try to convert it to an integer using the
60170 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
60171 **
60172 ** A NULL value is not changed by this routine.  It remains NULL.
60173 */
60174 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
60175   pIn1 = &aMem[pOp->p1];
60176   if( (pIn1->flags & MEM_Null)==0 ){
60177     sqlite3VdbeMemRealify(pIn1);
60178   }
60179   break;
60180 }
60181 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
60182
60183 /* Opcode: Lt P1 P2 P3 P4 P5
60184 **
60185 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
60186 ** jump to address P2.  
60187 **
60188 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
60189 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
60190 ** bit is clear then fall thru if either operand is NULL.
60191 **
60192 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
60193 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
60194 ** to coerce both inputs according to this affinity before the
60195 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
60196 ** affinity is used. Note that the affinity conversions are stored
60197 ** back into the input registers P1 and P3.  So this opcode can cause
60198 ** persistent changes to registers P1 and P3.
60199 **
60200 ** Once any conversions have taken place, and neither value is NULL, 
60201 ** the values are compared. If both values are blobs then memcmp() is
60202 ** used to determine the results of the comparison.  If both values
60203 ** are text, then the appropriate collating function specified in
60204 ** P4 is  used to do the comparison.  If P4 is not specified then
60205 ** memcmp() is used to compare text string.  If both values are
60206 ** numeric, then a numeric comparison is used. If the two values
60207 ** are of different types, then numbers are considered less than
60208 ** strings and strings are considered less than blobs.
60209 **
60210 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
60211 ** store a boolean result (either 0, or 1, or NULL) in register P2.
60212 */
60213 /* Opcode: Ne P1 P2 P3 P4 P5
60214 **
60215 ** This works just like the Lt opcode except that the jump is taken if
60216 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
60217 ** additional information.
60218 **
60219 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
60220 ** true or false and is never NULL.  If both operands are NULL then the result
60221 ** of comparison is false.  If either operand is NULL then the result is true.
60222 ** If neither operand is NULL the the result is the same as it would be if
60223 ** the SQLITE_NULLEQ flag were omitted from P5.
60224 */
60225 /* Opcode: Eq P1 P2 P3 P4 P5
60226 **
60227 ** This works just like the Lt opcode except that the jump is taken if
60228 ** the operands in registers P1 and P3 are equal.
60229 ** See the Lt opcode for additional information.
60230 **
60231 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
60232 ** true or false and is never NULL.  If both operands are NULL then the result
60233 ** of comparison is true.  If either operand is NULL then the result is false.
60234 ** If neither operand is NULL the the result is the same as it would be if
60235 ** the SQLITE_NULLEQ flag were omitted from P5.
60236 */
60237 /* Opcode: Le P1 P2 P3 P4 P5
60238 **
60239 ** This works just like the Lt opcode except that the jump is taken if
60240 ** the content of register P3 is less than or equal to the content of
60241 ** register P1.  See the Lt opcode for additional information.
60242 */
60243 /* Opcode: Gt P1 P2 P3 P4 P5
60244 **
60245 ** This works just like the Lt opcode except that the jump is taken if
60246 ** the content of register P3 is greater than the content of
60247 ** register P1.  See the Lt opcode for additional information.
60248 */
60249 /* Opcode: Ge P1 P2 P3 P4 P5
60250 **
60251 ** This works just like the Lt opcode except that the jump is taken if
60252 ** the content of register P3 is greater than or equal to the content of
60253 ** register P1.  See the Lt opcode for additional information.
60254 */
60255 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
60256 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
60257 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
60258 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
60259 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
60260 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
60261 #if 0  /* local variables moved into u.ai */
60262   int res;            /* Result of the comparison of pIn1 against pIn3 */
60263   char affinity;      /* Affinity to use for comparison */
60264   u16 flags1;         /* Copy of initial value of pIn1->flags */
60265   u16 flags3;         /* Copy of initial value of pIn3->flags */
60266 #endif /* local variables moved into u.ai */
60267
60268   pIn1 = &aMem[pOp->p1];
60269   pIn3 = &aMem[pOp->p3];
60270   u.ai.flags1 = pIn1->flags;
60271   u.ai.flags3 = pIn3->flags;
60272   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
60273     /* One or both operands are NULL */
60274     if( pOp->p5 & SQLITE_NULLEQ ){
60275       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
60276       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
60277       ** or not both operands are null.
60278       */
60279       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
60280       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
60281     }else{
60282       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
60283       ** then the result is always NULL.
60284       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
60285       */
60286       if( pOp->p5 & SQLITE_STOREP2 ){
60287         pOut = &aMem[pOp->p2];
60288         MemSetTypeFlag(pOut, MEM_Null);
60289         REGISTER_TRACE(pOp->p2, pOut);
60290       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
60291         pc = pOp->p2-1;
60292       }
60293       break;
60294     }
60295   }else{
60296     /* Neither operand is NULL.  Do a comparison. */
60297     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
60298     if( u.ai.affinity ){
60299       applyAffinity(pIn1, u.ai.affinity, encoding);
60300       applyAffinity(pIn3, u.ai.affinity, encoding);
60301       if( db->mallocFailed ) goto no_mem;
60302     }
60303
60304     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
60305     ExpandBlob(pIn1);
60306     ExpandBlob(pIn3);
60307     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
60308   }
60309   switch( pOp->opcode ){
60310     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
60311     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
60312     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
60313     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
60314     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
60315     default:       u.ai.res = u.ai.res>=0;     break;
60316   }
60317
60318   if( pOp->p5 & SQLITE_STOREP2 ){
60319     pOut = &aMem[pOp->p2];
60320     MemSetTypeFlag(pOut, MEM_Int);
60321     pOut->u.i = u.ai.res;
60322     REGISTER_TRACE(pOp->p2, pOut);
60323   }else if( u.ai.res ){
60324     pc = pOp->p2-1;
60325   }
60326
60327   /* Undo any changes made by applyAffinity() to the input registers. */
60328   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
60329   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
60330   break;
60331 }
60332
60333 /* Opcode: Permutation * * * P4 *
60334 **
60335 ** Set the permutation used by the OP_Compare operator to be the array
60336 ** of integers in P4.
60337 **
60338 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
60339 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
60340 ** immediately prior to the OP_Compare.
60341 */
60342 case OP_Permutation: {
60343   assert( pOp->p4type==P4_INTARRAY );
60344   assert( pOp->p4.ai );
60345   aPermute = pOp->p4.ai;
60346   break;
60347 }
60348
60349 /* Opcode: Compare P1 P2 P3 P4 *
60350 **
60351 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
60352 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
60353 ** the comparison for use by the next OP_Jump instruct.
60354 **
60355 ** P4 is a KeyInfo structure that defines collating sequences and sort
60356 ** orders for the comparison.  The permutation applies to registers
60357 ** only.  The KeyInfo elements are used sequentially.
60358 **
60359 ** The comparison is a sort comparison, so NULLs compare equal,
60360 ** NULLs are less than numbers, numbers are less than strings,
60361 ** and strings are less than blobs.
60362 */
60363 case OP_Compare: {
60364 #if 0  /* local variables moved into u.aj */
60365   int n;
60366   int i;
60367   int p1;
60368   int p2;
60369   const KeyInfo *pKeyInfo;
60370   int idx;
60371   CollSeq *pColl;    /* Collating sequence to use on this term */
60372   int bRev;          /* True for DESCENDING sort order */
60373 #endif /* local variables moved into u.aj */
60374
60375   u.aj.n = pOp->p3;
60376   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
60377   assert( u.aj.n>0 );
60378   assert( u.aj.pKeyInfo!=0 );
60379   u.aj.p1 = pOp->p1;
60380   u.aj.p2 = pOp->p2;
60381 #if SQLITE_DEBUG
60382   if( aPermute ){
60383     int k, mx = 0;
60384     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
60385     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
60386     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
60387   }else{
60388     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
60389     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
60390   }
60391 #endif /* SQLITE_DEBUG */
60392   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
60393     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
60394     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
60395     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
60396     assert( u.aj.i<u.aj.pKeyInfo->nField );
60397     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
60398     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
60399     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
60400     if( iCompare ){
60401       if( u.aj.bRev ) iCompare = -iCompare;
60402       break;
60403     }
60404   }
60405   aPermute = 0;
60406   break;
60407 }
60408
60409 /* Opcode: Jump P1 P2 P3 * *
60410 **
60411 ** Jump to the instruction at address P1, P2, or P3 depending on whether
60412 ** in the most recent OP_Compare instruction the P1 vector was less than
60413 ** equal to, or greater than the P2 vector, respectively.
60414 */
60415 case OP_Jump: {             /* jump */
60416   if( iCompare<0 ){
60417     pc = pOp->p1 - 1;
60418   }else if( iCompare==0 ){
60419     pc = pOp->p2 - 1;
60420   }else{
60421     pc = pOp->p3 - 1;
60422   }
60423   break;
60424 }
60425
60426 /* Opcode: And P1 P2 P3 * *
60427 **
60428 ** Take the logical AND of the values in registers P1 and P2 and
60429 ** write the result into register P3.
60430 **
60431 ** If either P1 or P2 is 0 (false) then the result is 0 even if
60432 ** the other input is NULL.  A NULL and true or two NULLs give
60433 ** a NULL output.
60434 */
60435 /* Opcode: Or P1 P2 P3 * *
60436 **
60437 ** Take the logical OR of the values in register P1 and P2 and
60438 ** store the answer in register P3.
60439 **
60440 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
60441 ** even if the other input is NULL.  A NULL and false or two NULLs
60442 ** give a NULL output.
60443 */
60444 case OP_And:              /* same as TK_AND, in1, in2, out3 */
60445 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
60446 #if 0  /* local variables moved into u.ak */
60447   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60448   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60449 #endif /* local variables moved into u.ak */
60450
60451   pIn1 = &aMem[pOp->p1];
60452   if( pIn1->flags & MEM_Null ){
60453     u.ak.v1 = 2;
60454   }else{
60455     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
60456   }
60457   pIn2 = &aMem[pOp->p2];
60458   if( pIn2->flags & MEM_Null ){
60459     u.ak.v2 = 2;
60460   }else{
60461     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
60462   }
60463   if( pOp->opcode==OP_And ){
60464     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
60465     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
60466   }else{
60467     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
60468     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
60469   }
60470   pOut = &aMem[pOp->p3];
60471   if( u.ak.v1==2 ){
60472     MemSetTypeFlag(pOut, MEM_Null);
60473   }else{
60474     pOut->u.i = u.ak.v1;
60475     MemSetTypeFlag(pOut, MEM_Int);
60476   }
60477   break;
60478 }
60479
60480 /* Opcode: Not P1 P2 * * *
60481 **
60482 ** Interpret the value in register P1 as a boolean value.  Store the
60483 ** boolean complement in register P2.  If the value in register P1 is 
60484 ** NULL, then a NULL is stored in P2.
60485 */
60486 case OP_Not: {                /* same as TK_NOT, in1, out2 */
60487   pIn1 = &aMem[pOp->p1];
60488   pOut = &aMem[pOp->p2];
60489   if( pIn1->flags & MEM_Null ){
60490     sqlite3VdbeMemSetNull(pOut);
60491   }else{
60492     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
60493   }
60494   break;
60495 }
60496
60497 /* Opcode: BitNot P1 P2 * * *
60498 **
60499 ** Interpret the content of register P1 as an integer.  Store the
60500 ** ones-complement of the P1 value into register P2.  If P1 holds
60501 ** a NULL then store a NULL in P2.
60502 */
60503 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
60504   pIn1 = &aMem[pOp->p1];
60505   pOut = &aMem[pOp->p2];
60506   if( pIn1->flags & MEM_Null ){
60507     sqlite3VdbeMemSetNull(pOut);
60508   }else{
60509     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
60510   }
60511   break;
60512 }
60513
60514 /* Opcode: If P1 P2 P3 * *
60515 **
60516 ** Jump to P2 if the value in register P1 is true.  The value is
60517 ** is considered true if it is numeric and non-zero.  If the value
60518 ** in P1 is NULL then take the jump if P3 is true.
60519 */
60520 /* Opcode: IfNot P1 P2 P3 * *
60521 **
60522 ** Jump to P2 if the value in register P1 is False.  The value is
60523 ** is considered true if it has a numeric value of zero.  If the value
60524 ** in P1 is NULL then take the jump if P3 is true.
60525 */
60526 case OP_If:                 /* jump, in1 */
60527 case OP_IfNot: {            /* jump, in1 */
60528 #if 0  /* local variables moved into u.al */
60529   int c;
60530 #endif /* local variables moved into u.al */
60531   pIn1 = &aMem[pOp->p1];
60532   if( pIn1->flags & MEM_Null ){
60533     u.al.c = pOp->p3;
60534   }else{
60535 #ifdef SQLITE_OMIT_FLOATING_POINT
60536     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
60537 #else
60538     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
60539 #endif
60540     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
60541   }
60542   if( u.al.c ){
60543     pc = pOp->p2-1;
60544   }
60545   break;
60546 }
60547
60548 /* Opcode: IsNull P1 P2 * * *
60549 **
60550 ** Jump to P2 if the value in register P1 is NULL.
60551 */
60552 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
60553   pIn1 = &aMem[pOp->p1];
60554   if( (pIn1->flags & MEM_Null)!=0 ){
60555     pc = pOp->p2 - 1;
60556   }
60557   break;
60558 }
60559
60560 /* Opcode: NotNull P1 P2 * * *
60561 **
60562 ** Jump to P2 if the value in register P1 is not NULL.  
60563 */
60564 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
60565   pIn1 = &aMem[pOp->p1];
60566   if( (pIn1->flags & MEM_Null)==0 ){
60567     pc = pOp->p2 - 1;
60568   }
60569   break;
60570 }
60571
60572 /* Opcode: Column P1 P2 P3 P4 P5
60573 **
60574 ** Interpret the data that cursor P1 points to as a structure built using
60575 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
60576 ** information about the format of the data.)  Extract the P2-th column
60577 ** from this record.  If there are less that (P2+1) 
60578 ** values in the record, extract a NULL.
60579 **
60580 ** The value extracted is stored in register P3.
60581 **
60582 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
60583 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
60584 ** the result.
60585 **
60586 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
60587 ** then the cache of the cursor is reset prior to extracting the column.
60588 ** The first OP_Column against a pseudo-table after the value of the content
60589 ** register has changed should have this bit set.
60590 */
60591 case OP_Column: {
60592 #if 0  /* local variables moved into u.am */
60593   u32 payloadSize;   /* Number of bytes in the record */
60594   i64 payloadSize64; /* Number of bytes in the record */
60595   int p1;            /* P1 value of the opcode */
60596   int p2;            /* column number to retrieve */
60597   VdbeCursor *pC;    /* The VDBE cursor */
60598   char *zRec;        /* Pointer to complete record-data */
60599   BtCursor *pCrsr;   /* The BTree cursor */
60600   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60601   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60602   int nField;        /* number of fields in the record */
60603   int len;           /* The length of the serialized data for the column */
60604   int i;             /* Loop counter */
60605   char *zData;       /* Part of the record being decoded */
60606   Mem *pDest;        /* Where to write the extracted value */
60607   Mem sMem;          /* For storing the record being decoded */
60608   u8 *zIdx;          /* Index into header */
60609   u8 *zEndHdr;       /* Pointer to first byte after the header */
60610   u32 offset;        /* Offset into the data */
60611   u32 szField;       /* Number of bytes in the content of a field */
60612   int szHdr;         /* Size of the header size field at start of record */
60613   int avail;         /* Number of bytes of available data */
60614   Mem *pReg;         /* PseudoTable input register */
60615 #endif /* local variables moved into u.am */
60616
60617
60618   u.am.p1 = pOp->p1;
60619   u.am.p2 = pOp->p2;
60620   u.am.pC = 0;
60621   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
60622   assert( u.am.p1<p->nCursor );
60623   assert( pOp->p3>0 && pOp->p3<=p->nMem );
60624   u.am.pDest = &aMem[pOp->p3];
60625   MemSetTypeFlag(u.am.pDest, MEM_Null);
60626   u.am.zRec = 0;
60627
60628   /* This block sets the variable u.am.payloadSize to be the total number of
60629   ** bytes in the record.
60630   **
60631   ** u.am.zRec is set to be the complete text of the record if it is available.
60632   ** The complete record text is always available for pseudo-tables
60633   ** If the record is stored in a cursor, the complete record text
60634   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
60635   ** If the data is unavailable,  u.am.zRec is set to NULL.
60636   **
60637   ** We also compute the number of columns in the record.  For cursors,
60638   ** the number of columns is stored in the VdbeCursor.nField element.
60639   */
60640   u.am.pC = p->apCsr[u.am.p1];
60641   assert( u.am.pC!=0 );
60642 #ifndef SQLITE_OMIT_VIRTUALTABLE
60643   assert( u.am.pC->pVtabCursor==0 );
60644 #endif
60645   u.am.pCrsr = u.am.pC->pCursor;
60646   if( u.am.pCrsr!=0 ){
60647     /* The record is stored in a B-Tree */
60648     rc = sqlite3VdbeCursorMoveto(u.am.pC);
60649     if( rc ) goto abort_due_to_error;
60650     if( u.am.pC->nullRow ){
60651       u.am.payloadSize = 0;
60652     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
60653       u.am.payloadSize = u.am.pC->payloadSize;
60654       u.am.zRec = (char*)u.am.pC->aRow;
60655     }else if( u.am.pC->isIndex ){
60656       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60657       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
60658       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
60659       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
60660       ** payload size, so it is impossible for u.am.payloadSize64 to be
60661       ** larger than 32 bits. */
60662       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
60663       u.am.payloadSize = (u32)u.am.payloadSize64;
60664     }else{
60665       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60666       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
60667       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
60668     }
60669   }else if( u.am.pC->pseudoTableReg>0 ){
60670     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
60671     assert( u.am.pReg->flags & MEM_Blob );
60672     u.am.payloadSize = u.am.pReg->n;
60673     u.am.zRec = u.am.pReg->z;
60674     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
60675     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
60676   }else{
60677     /* Consider the row to be NULL */
60678     u.am.payloadSize = 0;
60679   }
60680
60681   /* If u.am.payloadSize is 0, then just store a NULL */
60682   if( u.am.payloadSize==0 ){
60683     assert( u.am.pDest->flags&MEM_Null );
60684     goto op_column_out;
60685   }
60686   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
60687   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
60688     goto too_big;
60689   }
60690
60691   u.am.nField = u.am.pC->nField;
60692   assert( u.am.p2<u.am.nField );
60693
60694   /* Read and parse the table header.  Store the results of the parse
60695   ** into the record header cache fields of the cursor.
60696   */
60697   u.am.aType = u.am.pC->aType;
60698   if( u.am.pC->cacheStatus==p->cacheCtr ){
60699     u.am.aOffset = u.am.pC->aOffset;
60700   }else{
60701     assert(u.am.aType);
60702     u.am.avail = 0;
60703     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
60704     u.am.pC->payloadSize = u.am.payloadSize;
60705     u.am.pC->cacheStatus = p->cacheCtr;
60706
60707     /* Figure out how many bytes are in the header */
60708     if( u.am.zRec ){
60709       u.am.zData = u.am.zRec;
60710     }else{
60711       if( u.am.pC->isIndex ){
60712         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
60713       }else{
60714         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
60715       }
60716       /* If KeyFetch()/DataFetch() managed to get the entire payload,
60717       ** save the payload in the u.am.pC->aRow cache.  That will save us from
60718       ** having to make additional calls to fetch the content portion of
60719       ** the record.
60720       */
60721       assert( u.am.avail>=0 );
60722       if( u.am.payloadSize <= (u32)u.am.avail ){
60723         u.am.zRec = u.am.zData;
60724         u.am.pC->aRow = (u8*)u.am.zData;
60725       }else{
60726         u.am.pC->aRow = 0;
60727       }
60728     }
60729     /* The following assert is true in all cases accept when
60730     ** the database file has been corrupted externally.
60731     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
60732     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
60733
60734     /* Make sure a corrupt database has not given us an oversize header.
60735     ** Do this now to avoid an oversize memory allocation.
60736     **
60737     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
60738     ** types use so much data space that there can only be 4096 and 32 of
60739     ** them, respectively.  So the maximum header length results from a
60740     ** 3-byte type for each of the maximum of 32768 columns plus three
60741     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
60742     */
60743     if( u.am.offset > 98307 ){
60744       rc = SQLITE_CORRUPT_BKPT;
60745       goto op_column_out;
60746     }
60747
60748     /* Compute in u.am.len the number of bytes of data we need to read in order
60749     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
60750     ** u.am.nField might be significantly less than the true number of columns
60751     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
60752     ** We want to minimize u.am.len in order to limit the size of the memory
60753     ** allocation, especially if a corrupt database file has caused u.am.offset
60754     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
60755     ** still exceed Robson memory allocation limits on some configurations.
60756     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
60757     ** will likely be much smaller since u.am.nField will likely be less than
60758     ** 20 or so.  This insures that Robson memory allocation limits are
60759     ** not exceeded even for corrupt database files.
60760     */
60761     u.am.len = u.am.nField*5 + 3;
60762     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
60763
60764     /* The KeyFetch() or DataFetch() above are fast and will get the entire
60765     ** record header in most cases.  But they will fail to get the complete
60766     ** record header if the record header does not fit on a single page
60767     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
60768     ** acquire the complete header text.
60769     */
60770     if( !u.am.zRec && u.am.avail<u.am.len ){
60771       u.am.sMem.flags = 0;
60772       u.am.sMem.db = 0;
60773       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
60774       if( rc!=SQLITE_OK ){
60775         goto op_column_out;
60776       }
60777       u.am.zData = u.am.sMem.z;
60778     }
60779     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
60780     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
60781
60782     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
60783     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
60784     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
60785     ** of the record to the start of the data for the u.am.i-th column
60786     */
60787     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
60788       if( u.am.zIdx<u.am.zEndHdr ){
60789         u.am.aOffset[u.am.i] = u.am.offset;
60790         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
60791         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
60792         u.am.offset += u.am.szField;
60793         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
60794           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
60795           break;
60796         }
60797       }else{
60798         /* If u.am.i is less that u.am.nField, then there are less fields in this
60799         ** record than SetNumColumns indicated there are columns in the
60800         ** table. Set the u.am.offset for any extra columns not present in
60801         ** the record to 0. This tells code below to store a NULL
60802         ** instead of deserializing a value from the record.
60803         */
60804         u.am.aOffset[u.am.i] = 0;
60805       }
60806     }
60807     sqlite3VdbeMemRelease(&u.am.sMem);
60808     u.am.sMem.flags = MEM_Null;
60809
60810     /* If we have read more header data than was contained in the header,
60811     ** or if the end of the last field appears to be past the end of the
60812     ** record, or if the end of the last field appears to be before the end
60813     ** of the record (when all fields present), then we must be dealing
60814     ** with a corrupt database.
60815     */
60816     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
60817          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
60818       rc = SQLITE_CORRUPT_BKPT;
60819       goto op_column_out;
60820     }
60821   }
60822
60823   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
60824   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
60825   ** then there are not enough fields in the record to satisfy the
60826   ** request.  In this case, set the value NULL or to P4 if P4 is
60827   ** a pointer to a Mem object.
60828   */
60829   if( u.am.aOffset[u.am.p2] ){
60830     assert( rc==SQLITE_OK );
60831     if( u.am.zRec ){
60832       sqlite3VdbeMemReleaseExternal(u.am.pDest);
60833       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
60834     }else{
60835       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
60836       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
60837       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
60838       if( rc!=SQLITE_OK ){
60839         goto op_column_out;
60840       }
60841       u.am.zData = u.am.sMem.z;
60842       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
60843     }
60844     u.am.pDest->enc = encoding;
60845   }else{
60846     if( pOp->p4type==P4_MEM ){
60847       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
60848     }else{
60849       assert( u.am.pDest->flags&MEM_Null );
60850     }
60851   }
60852
60853   /* If we dynamically allocated space to hold the data (in the
60854   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
60855   ** dynamically allocated space over to the u.am.pDest structure.
60856   ** This prevents a memory copy.
60857   */
60858   if( u.am.sMem.zMalloc ){
60859     assert( u.am.sMem.z==u.am.sMem.zMalloc );
60860     assert( !(u.am.pDest->flags & MEM_Dyn) );
60861     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
60862     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
60863     u.am.pDest->flags |= MEM_Term;
60864     u.am.pDest->z = u.am.sMem.z;
60865     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
60866   }
60867
60868   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
60869
60870 op_column_out:
60871   UPDATE_MAX_BLOBSIZE(u.am.pDest);
60872   REGISTER_TRACE(pOp->p3, u.am.pDest);
60873   break;
60874 }
60875
60876 /* Opcode: Affinity P1 P2 * P4 *
60877 **
60878 ** Apply affinities to a range of P2 registers starting with P1.
60879 **
60880 ** P4 is a string that is P2 characters long. The nth character of the
60881 ** string indicates the column affinity that should be used for the nth
60882 ** memory cell in the range.
60883 */
60884 case OP_Affinity: {
60885 #if 0  /* local variables moved into u.an */
60886   const char *zAffinity;   /* The affinity to be applied */
60887   char cAff;               /* A single character of affinity */
60888 #endif /* local variables moved into u.an */
60889
60890   u.an.zAffinity = pOp->p4.z;
60891   assert( u.an.zAffinity!=0 );
60892   assert( u.an.zAffinity[pOp->p2]==0 );
60893   pIn1 = &aMem[pOp->p1];
60894   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
60895     assert( pIn1 <= &p->aMem[p->nMem] );
60896     ExpandBlob(pIn1);
60897     applyAffinity(pIn1, u.an.cAff, encoding);
60898     pIn1++;
60899   }
60900   break;
60901 }
60902
60903 /* Opcode: MakeRecord P1 P2 P3 P4 *
60904 **
60905 ** Convert P2 registers beginning with P1 into a single entry
60906 ** suitable for use as a data record in a database table or as a key
60907 ** in an index.  The details of the format are irrelevant as long as
60908 ** the OP_Column opcode can decode the record later.
60909 ** Refer to source code comments for the details of the record
60910 ** format.
60911 **
60912 ** P4 may be a string that is P2 characters long.  The nth character of the
60913 ** string indicates the column affinity that should be used for the nth
60914 ** field of the index key.
60915 **
60916 ** The mapping from character to affinity is given by the SQLITE_AFF_
60917 ** macros defined in sqliteInt.h.
60918 **
60919 ** If P4 is NULL then all index fields have the affinity NONE.
60920 */
60921 case OP_MakeRecord: {
60922 #if 0  /* local variables moved into u.ao */
60923   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60924   Mem *pRec;             /* The new record */
60925   u64 nData;             /* Number of bytes of data space */
60926   int nHdr;              /* Number of bytes of header space */
60927   i64 nByte;             /* Data space required for this record */
60928   int nZero;             /* Number of zero bytes at the end of the record */
60929   int nVarint;           /* Number of bytes in a varint */
60930   u32 serial_type;       /* Type field */
60931   Mem *pData0;           /* First field to be combined into the record */
60932   Mem *pLast;            /* Last field of the record */
60933   int nField;            /* Number of fields in the record */
60934   char *zAffinity;       /* The affinity string for the record */
60935   int file_format;       /* File format to use for encoding */
60936   int i;                 /* Space used in zNewRecord[] */
60937   int len;               /* Length of a field */
60938 #endif /* local variables moved into u.ao */
60939
60940   /* Assuming the record contains N fields, the record format looks
60941   ** like this:
60942   **
60943   ** ------------------------------------------------------------------------
60944   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
60945   ** ------------------------------------------------------------------------
60946   **
60947   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
60948   ** and so froth.
60949   **
60950   ** Each type field is a varint representing the serial type of the
60951   ** corresponding data element (see sqlite3VdbeSerialType()). The
60952   ** hdr-size field is also a varint which is the offset from the beginning
60953   ** of the record to data0.
60954   */
60955   u.ao.nData = 0;         /* Number of bytes of data space */
60956   u.ao.nHdr = 0;          /* Number of bytes of header space */
60957   u.ao.nByte = 0;         /* Data space required for this record */
60958   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
60959   u.ao.nField = pOp->p1;
60960   u.ao.zAffinity = pOp->p4.z;
60961   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
60962   u.ao.pData0 = &aMem[u.ao.nField];
60963   u.ao.nField = pOp->p2;
60964   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
60965   u.ao.file_format = p->minWriteFileFormat;
60966
60967   /* Loop through the elements that will make up the record to figure
60968   ** out how much space is required for the new record.
60969   */
60970   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
60971     if( u.ao.zAffinity ){
60972       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
60973     }
60974     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
60975       sqlite3VdbeMemExpandBlob(u.ao.pRec);
60976     }
60977     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
60978     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
60979     u.ao.nData += u.ao.len;
60980     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
60981     if( u.ao.pRec->flags & MEM_Zero ){
60982       /* Only pure zero-filled BLOBs can be input to this Opcode.
60983       ** We do not allow blobs with a prefix and a zero-filled tail. */
60984       u.ao.nZero += u.ao.pRec->u.nZero;
60985     }else if( u.ao.len ){
60986       u.ao.nZero = 0;
60987     }
60988   }
60989
60990   /* Add the initial header varint and total the size */
60991   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
60992   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
60993     u.ao.nHdr++;
60994   }
60995   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
60996   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60997     goto too_big;
60998   }
60999
61000   /* Make sure the output register has a buffer large enough to store
61001   ** the new record. The output register (pOp->p3) is not allowed to
61002   ** be one of the input registers (because the following call to
61003   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
61004   */
61005   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
61006   pOut = &aMem[pOp->p3];
61007   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
61008     goto no_mem;
61009   }
61010   u.ao.zNewRecord = (u8 *)pOut->z;
61011
61012   /* Write the record */
61013   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
61014   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
61015     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
61016     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
61017   }
61018   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
61019     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
61020   }
61021   assert( u.ao.i==u.ao.nByte );
61022
61023   assert( pOp->p3>0 && pOp->p3<=p->nMem );
61024   pOut->n = (int)u.ao.nByte;
61025   pOut->flags = MEM_Blob | MEM_Dyn;
61026   pOut->xDel = 0;
61027   if( u.ao.nZero ){
61028     pOut->u.nZero = u.ao.nZero;
61029     pOut->flags |= MEM_Zero;
61030   }
61031   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
61032   REGISTER_TRACE(pOp->p3, pOut);
61033   UPDATE_MAX_BLOBSIZE(pOut);
61034   break;
61035 }
61036
61037 /* Opcode: Count P1 P2 * * *
61038 **
61039 ** Store the number of entries (an integer value) in the table or index 
61040 ** opened by cursor P1 in register P2
61041 */
61042 #ifndef SQLITE_OMIT_BTREECOUNT
61043 case OP_Count: {         /* out2-prerelease */
61044 #if 0  /* local variables moved into u.ap */
61045   i64 nEntry;
61046   BtCursor *pCrsr;
61047 #endif /* local variables moved into u.ap */
61048
61049   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
61050   if( u.ap.pCrsr ){
61051     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
61052   }else{
61053     u.ap.nEntry = 0;
61054   }
61055   pOut->u.i = u.ap.nEntry;
61056   break;
61057 }
61058 #endif
61059
61060 /* Opcode: Savepoint P1 * * P4 *
61061 **
61062 ** Open, release or rollback the savepoint named by parameter P4, depending
61063 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
61064 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
61065 */
61066 case OP_Savepoint: {
61067 #if 0  /* local variables moved into u.aq */
61068   int p1;                         /* Value of P1 operand */
61069   char *zName;                    /* Name of savepoint */
61070   int nName;
61071   Savepoint *pNew;
61072   Savepoint *pSavepoint;
61073   Savepoint *pTmp;
61074   int iSavepoint;
61075   int ii;
61076 #endif /* local variables moved into u.aq */
61077
61078   u.aq.p1 = pOp->p1;
61079   u.aq.zName = pOp->p4.z;
61080
61081   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
61082   ** transaction, then there cannot be any savepoints.
61083   */
61084   assert( db->pSavepoint==0 || db->autoCommit==0 );
61085   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
61086   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
61087   assert( checkSavepointCount(db) );
61088
61089   if( u.aq.p1==SAVEPOINT_BEGIN ){
61090     if( db->writeVdbeCnt>0 ){
61091       /* A new savepoint cannot be created if there are active write
61092       ** statements (i.e. open read/write incremental blob handles).
61093       */
61094       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
61095         "SQL statements in progress");
61096       rc = SQLITE_BUSY;
61097     }else{
61098       u.aq.nName = sqlite3Strlen30(u.aq.zName);
61099
61100       /* Create a new savepoint structure. */
61101       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
61102       if( u.aq.pNew ){
61103         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
61104         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
61105
61106         /* If there is no open transaction, then mark this as a special
61107         ** "transaction savepoint". */
61108         if( db->autoCommit ){
61109           db->autoCommit = 0;
61110           db->isTransactionSavepoint = 1;
61111         }else{
61112           db->nSavepoint++;
61113         }
61114
61115         /* Link the new savepoint into the database handle's list. */
61116         u.aq.pNew->pNext = db->pSavepoint;
61117         db->pSavepoint = u.aq.pNew;
61118         u.aq.pNew->nDeferredCons = db->nDeferredCons;
61119       }
61120     }
61121   }else{
61122     u.aq.iSavepoint = 0;
61123
61124     /* Find the named savepoint. If there is no such savepoint, then an
61125     ** an error is returned to the user.  */
61126     for(
61127       u.aq.pSavepoint = db->pSavepoint;
61128       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
61129       u.aq.pSavepoint = u.aq.pSavepoint->pNext
61130     ){
61131       u.aq.iSavepoint++;
61132     }
61133     if( !u.aq.pSavepoint ){
61134       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
61135       rc = SQLITE_ERROR;
61136     }else if(
61137         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
61138     ){
61139       /* It is not possible to release (commit) a savepoint if there are
61140       ** active write statements. It is not possible to rollback a savepoint
61141       ** if there are any active statements at all.
61142       */
61143       sqlite3SetString(&p->zErrMsg, db,
61144         "cannot %s savepoint - SQL statements in progress",
61145         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
61146       );
61147       rc = SQLITE_BUSY;
61148     }else{
61149
61150       /* Determine whether or not this is a transaction savepoint. If so,
61151       ** and this is a RELEASE command, then the current transaction
61152       ** is committed.
61153       */
61154       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
61155       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
61156         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
61157           goto vdbe_return;
61158         }
61159         db->autoCommit = 1;
61160         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
61161           p->pc = pc;
61162           db->autoCommit = 0;
61163           p->rc = rc = SQLITE_BUSY;
61164           goto vdbe_return;
61165         }
61166         db->isTransactionSavepoint = 0;
61167         rc = p->rc;
61168       }else{
61169         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
61170         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
61171           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
61172           if( rc!=SQLITE_OK ){
61173             goto abort_due_to_error;
61174           }
61175         }
61176         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
61177           sqlite3ExpirePreparedStatements(db);
61178           sqlite3ResetInternalSchema(db, 0);
61179         }
61180       }
61181
61182       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
61183       ** savepoints nested inside of the savepoint being operated on. */
61184       while( db->pSavepoint!=u.aq.pSavepoint ){
61185         u.aq.pTmp = db->pSavepoint;
61186         db->pSavepoint = u.aq.pTmp->pNext;
61187         sqlite3DbFree(db, u.aq.pTmp);
61188         db->nSavepoint--;
61189       }
61190
61191       /* If it is a RELEASE, then destroy the savepoint being operated on
61192       ** too. If it is a ROLLBACK TO, then set the number of deferred
61193       ** constraint violations present in the database to the value stored
61194       ** when the savepoint was created.  */
61195       if( u.aq.p1==SAVEPOINT_RELEASE ){
61196         assert( u.aq.pSavepoint==db->pSavepoint );
61197         db->pSavepoint = u.aq.pSavepoint->pNext;
61198         sqlite3DbFree(db, u.aq.pSavepoint);
61199         if( !isTransaction ){
61200           db->nSavepoint--;
61201         }
61202       }else{
61203         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
61204       }
61205     }
61206   }
61207
61208   break;
61209 }
61210
61211 /* Opcode: AutoCommit P1 P2 * * *
61212 **
61213 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
61214 ** back any currently active btree transactions. If there are any active
61215 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
61216 ** there are active writing VMs or active VMs that use shared cache.
61217 **
61218 ** This instruction causes the VM to halt.
61219 */
61220 case OP_AutoCommit: {
61221 #if 0  /* local variables moved into u.ar */
61222   int desiredAutoCommit;
61223   int iRollback;
61224   int turnOnAC;
61225 #endif /* local variables moved into u.ar */
61226
61227   u.ar.desiredAutoCommit = pOp->p1;
61228   u.ar.iRollback = pOp->p2;
61229   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
61230   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
61231   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
61232   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
61233
61234   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
61235     /* If this instruction implements a ROLLBACK and other VMs are
61236     ** still running, and a transaction is active, return an error indicating
61237     ** that the other VMs must complete first.
61238     */
61239     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
61240         "SQL statements in progress");
61241     rc = SQLITE_BUSY;
61242   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
61243     /* If this instruction implements a COMMIT and other VMs are writing
61244     ** return an error indicating that the other VMs must complete first.
61245     */
61246     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
61247         "SQL statements in progress");
61248     rc = SQLITE_BUSY;
61249   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
61250     if( u.ar.iRollback ){
61251       assert( u.ar.desiredAutoCommit==1 );
61252       sqlite3RollbackAll(db);
61253       db->autoCommit = 1;
61254     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
61255       goto vdbe_return;
61256     }else{
61257       db->autoCommit = (u8)u.ar.desiredAutoCommit;
61258       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
61259         p->pc = pc;
61260         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
61261         p->rc = rc = SQLITE_BUSY;
61262         goto vdbe_return;
61263       }
61264     }
61265     assert( db->nStatement==0 );
61266     sqlite3CloseSavepoints(db);
61267     if( p->rc==SQLITE_OK ){
61268       rc = SQLITE_DONE;
61269     }else{
61270       rc = SQLITE_ERROR;
61271     }
61272     goto vdbe_return;
61273   }else{
61274     sqlite3SetString(&p->zErrMsg, db,
61275         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
61276         (u.ar.iRollback)?"cannot rollback - no transaction is active":
61277                    "cannot commit - no transaction is active"));
61278
61279     rc = SQLITE_ERROR;
61280   }
61281   break;
61282 }
61283
61284 /* Opcode: Transaction P1 P2 * * *
61285 **
61286 ** Begin a transaction.  The transaction ends when a Commit or Rollback
61287 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
61288 ** transaction might also be rolled back if an error is encountered.
61289 **
61290 ** P1 is the index of the database file on which the transaction is
61291 ** started.  Index 0 is the main database file and index 1 is the
61292 ** file used for temporary tables.  Indices of 2 or more are used for
61293 ** attached databases.
61294 **
61295 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
61296 ** obtained on the database file when a write-transaction is started.  No
61297 ** other process can start another write transaction while this transaction is
61298 ** underway.  Starting a write transaction also creates a rollback journal. A
61299 ** write transaction must be started before any changes can be made to the
61300 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
61301 ** on the file.
61302 **
61303 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
61304 ** true (this flag is set if the Vdbe may modify more than one row and may
61305 ** throw an ABORT exception), a statement transaction may also be opened.
61306 ** More specifically, a statement transaction is opened iff the database
61307 ** connection is currently not in autocommit mode, or if there are other
61308 ** active statements. A statement transaction allows the affects of this
61309 ** VDBE to be rolled back after an error without having to roll back the
61310 ** entire transaction. If no error is encountered, the statement transaction
61311 ** will automatically commit when the VDBE halts.
61312 **
61313 ** If P2 is zero, then a read-lock is obtained on the database file.
61314 */
61315 case OP_Transaction: {
61316 #if 0  /* local variables moved into u.as */
61317   Btree *pBt;
61318 #endif /* local variables moved into u.as */
61319
61320   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61321   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61322   u.as.pBt = db->aDb[pOp->p1].pBt;
61323
61324   if( u.as.pBt ){
61325     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
61326     if( rc==SQLITE_BUSY ){
61327       p->pc = pc;
61328       p->rc = rc = SQLITE_BUSY;
61329       goto vdbe_return;
61330     }
61331     if( rc!=SQLITE_OK ){
61332       goto abort_due_to_error;
61333     }
61334
61335     if( pOp->p2 && p->usesStmtJournal
61336      && (db->autoCommit==0 || db->activeVdbeCnt>1)
61337     ){
61338       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
61339       if( p->iStatement==0 ){
61340         assert( db->nStatement>=0 && db->nSavepoint>=0 );
61341         db->nStatement++;
61342         p->iStatement = db->nSavepoint + db->nStatement;
61343       }
61344       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
61345
61346       /* Store the current value of the database handles deferred constraint
61347       ** counter. If the statement transaction needs to be rolled back,
61348       ** the value of this counter needs to be restored too.  */
61349       p->nStmtDefCons = db->nDeferredCons;
61350     }
61351   }
61352   break;
61353 }
61354
61355 /* Opcode: ReadCookie P1 P2 P3 * *
61356 **
61357 ** Read cookie number P3 from database P1 and write it into register P2.
61358 ** P3==1 is the schema version.  P3==2 is the database format.
61359 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
61360 ** the main database file and P1==1 is the database file used to store
61361 ** temporary tables.
61362 **
61363 ** There must be a read-lock on the database (either a transaction
61364 ** must be started or there must be an open cursor) before
61365 ** executing this instruction.
61366 */
61367 case OP_ReadCookie: {               /* out2-prerelease */
61368 #if 0  /* local variables moved into u.at */
61369   int iMeta;
61370   int iDb;
61371   int iCookie;
61372 #endif /* local variables moved into u.at */
61373
61374   u.at.iDb = pOp->p1;
61375   u.at.iCookie = pOp->p3;
61376   assert( pOp->p3<SQLITE_N_BTREE_META );
61377   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
61378   assert( db->aDb[u.at.iDb].pBt!=0 );
61379   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
61380
61381   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
61382   pOut->u.i = u.at.iMeta;
61383   break;
61384 }
61385
61386 /* Opcode: SetCookie P1 P2 P3 * *
61387 **
61388 ** Write the content of register P3 (interpreted as an integer)
61389 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
61390 ** P2==2 is the database format. P2==3 is the recommended pager cache 
61391 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
61392 ** database file used to store temporary tables.
61393 **
61394 ** A transaction must be started before executing this opcode.
61395 */
61396 case OP_SetCookie: {       /* in3 */
61397 #if 0  /* local variables moved into u.au */
61398   Db *pDb;
61399 #endif /* local variables moved into u.au */
61400   assert( pOp->p2<SQLITE_N_BTREE_META );
61401   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61402   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61403   u.au.pDb = &db->aDb[pOp->p1];
61404   assert( u.au.pDb->pBt!=0 );
61405   pIn3 = &aMem[pOp->p3];
61406   sqlite3VdbeMemIntegerify(pIn3);
61407   /* See note about index shifting on OP_ReadCookie */
61408   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
61409   if( pOp->p2==BTREE_SCHEMA_VERSION ){
61410     /* When the schema cookie changes, record the new cookie internally */
61411     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
61412     db->flags |= SQLITE_InternChanges;
61413   }else if( pOp->p2==BTREE_FILE_FORMAT ){
61414     /* Record changes in the file format */
61415     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
61416   }
61417   if( pOp->p1==1 ){
61418     /* Invalidate all prepared statements whenever the TEMP database
61419     ** schema is changed.  Ticket #1644 */
61420     sqlite3ExpirePreparedStatements(db);
61421     p->expired = 0;
61422   }
61423   break;
61424 }
61425
61426 /* Opcode: VerifyCookie P1 P2 *
61427 **
61428 ** Check the value of global database parameter number 0 (the
61429 ** schema version) and make sure it is equal to P2.  
61430 ** P1 is the database number which is 0 for the main database file
61431 ** and 1 for the file holding temporary tables and some higher number
61432 ** for auxiliary databases.
61433 **
61434 ** The cookie changes its value whenever the database schema changes.
61435 ** This operation is used to detect when that the cookie has changed
61436 ** and that the current process needs to reread the schema.
61437 **
61438 ** Either a transaction needs to have been started or an OP_Open needs
61439 ** to be executed (to establish a read lock) before this opcode is
61440 ** invoked.
61441 */
61442 case OP_VerifyCookie: {
61443 #if 0  /* local variables moved into u.av */
61444   int iMeta;
61445   Btree *pBt;
61446 #endif /* local variables moved into u.av */
61447   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61448   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61449   u.av.pBt = db->aDb[pOp->p1].pBt;
61450   if( u.av.pBt ){
61451     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
61452   }else{
61453     u.av.iMeta = 0;
61454   }
61455   if( u.av.iMeta!=pOp->p2 ){
61456     sqlite3DbFree(db, p->zErrMsg);
61457     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
61458     /* If the schema-cookie from the database file matches the cookie
61459     ** stored with the in-memory representation of the schema, do
61460     ** not reload the schema from the database file.
61461     **
61462     ** If virtual-tables are in use, this is not just an optimization.
61463     ** Often, v-tables store their data in other SQLite tables, which
61464     ** are queried from within xNext() and other v-table methods using
61465     ** prepared queries. If such a query is out-of-date, we do not want to
61466     ** discard the database schema, as the user code implementing the
61467     ** v-table would have to be ready for the sqlite3_vtab structure itself
61468     ** to be invalidated whenever sqlite3_step() is called from within
61469     ** a v-table method.
61470     */
61471     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
61472       sqlite3ResetInternalSchema(db, pOp->p1);
61473     }
61474
61475     sqlite3ExpirePreparedStatements(db);
61476     rc = SQLITE_SCHEMA;
61477   }
61478   break;
61479 }
61480
61481 /* Opcode: OpenRead P1 P2 P3 P4 P5
61482 **
61483 ** Open a read-only cursor for the database table whose root page is
61484 ** P2 in a database file.  The database file is determined by P3. 
61485 ** P3==0 means the main database, P3==1 means the database used for 
61486 ** temporary tables, and P3>1 means used the corresponding attached
61487 ** database.  Give the new cursor an identifier of P1.  The P1
61488 ** values need not be contiguous but all P1 values should be small integers.
61489 ** It is an error for P1 to be negative.
61490 **
61491 ** If P5!=0 then use the content of register P2 as the root page, not
61492 ** the value of P2 itself.
61493 **
61494 ** There will be a read lock on the database whenever there is an
61495 ** open cursor.  If the database was unlocked prior to this instruction
61496 ** then a read lock is acquired as part of this instruction.  A read
61497 ** lock allows other processes to read the database but prohibits
61498 ** any other process from modifying the database.  The read lock is
61499 ** released when all cursors are closed.  If this instruction attempts
61500 ** to get a read lock but fails, the script terminates with an
61501 ** SQLITE_BUSY error code.
61502 **
61503 ** The P4 value may be either an integer (P4_INT32) or a pointer to
61504 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
61505 ** structure, then said structure defines the content and collating 
61506 ** sequence of the index being opened. Otherwise, if P4 is an integer 
61507 ** value, it is set to the number of columns in the table.
61508 **
61509 ** See also OpenWrite.
61510 */
61511 /* Opcode: OpenWrite P1 P2 P3 P4 P5
61512 **
61513 ** Open a read/write cursor named P1 on the table or index whose root
61514 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
61515 ** root page.
61516 **
61517 ** The P4 value may be either an integer (P4_INT32) or a pointer to
61518 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
61519 ** structure, then said structure defines the content and collating 
61520 ** sequence of the index being opened. Otherwise, if P4 is an integer 
61521 ** value, it is set to the number of columns in the table, or to the
61522 ** largest index of any column of the table that is actually used.
61523 **
61524 ** This instruction works just like OpenRead except that it opens the cursor
61525 ** in read/write mode.  For a given table, there can be one or more read-only
61526 ** cursors or a single read/write cursor but not both.
61527 **
61528 ** See also OpenRead.
61529 */
61530 case OP_OpenRead:
61531 case OP_OpenWrite: {
61532 #if 0  /* local variables moved into u.aw */
61533   int nField;
61534   KeyInfo *pKeyInfo;
61535   int p2;
61536   int iDb;
61537   int wrFlag;
61538   Btree *pX;
61539   VdbeCursor *pCur;
61540   Db *pDb;
61541 #endif /* local variables moved into u.aw */
61542
61543   if( p->expired ){
61544     rc = SQLITE_ABORT;
61545     break;
61546   }
61547
61548   u.aw.nField = 0;
61549   u.aw.pKeyInfo = 0;
61550   u.aw.p2 = pOp->p2;
61551   u.aw.iDb = pOp->p3;
61552   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
61553   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
61554   u.aw.pDb = &db->aDb[u.aw.iDb];
61555   u.aw.pX = u.aw.pDb->pBt;
61556   assert( u.aw.pX!=0 );
61557   if( pOp->opcode==OP_OpenWrite ){
61558     u.aw.wrFlag = 1;
61559     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
61560       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
61561     }
61562   }else{
61563     u.aw.wrFlag = 0;
61564   }
61565   if( pOp->p5 ){
61566     assert( u.aw.p2>0 );
61567     assert( u.aw.p2<=p->nMem );
61568     pIn2 = &aMem[u.aw.p2];
61569     sqlite3VdbeMemIntegerify(pIn2);
61570     u.aw.p2 = (int)pIn2->u.i;
61571     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
61572     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
61573     ** If there were a failure, the prepared statement would have halted
61574     ** before reaching this instruction. */
61575     if( NEVER(u.aw.p2<2) ) {
61576       rc = SQLITE_CORRUPT_BKPT;
61577       goto abort_due_to_error;
61578     }
61579   }
61580   if( pOp->p4type==P4_KEYINFO ){
61581     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
61582     u.aw.pKeyInfo->enc = ENC(p->db);
61583     u.aw.nField = u.aw.pKeyInfo->nField+1;
61584   }else if( pOp->p4type==P4_INT32 ){
61585     u.aw.nField = pOp->p4.i;
61586   }
61587   assert( pOp->p1>=0 );
61588   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
61589   if( u.aw.pCur==0 ) goto no_mem;
61590   u.aw.pCur->nullRow = 1;
61591   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
61592   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
61593
61594   /* Since it performs no memory allocation or IO, the only values that
61595   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
61596   ** SQLITE_EMPTY is only returned when attempting to open the table
61597   ** rooted at page 1 of a zero-byte database.  */
61598   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
61599   if( rc==SQLITE_EMPTY ){
61600     u.aw.pCur->pCursor = 0;
61601     rc = SQLITE_OK;
61602   }
61603
61604   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
61605   ** SQLite used to check if the root-page flags were sane at this point
61606   ** and report database corruption if they were not, but this check has
61607   ** since moved into the btree layer.  */
61608   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
61609   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
61610   break;
61611 }
61612
61613 /* Opcode: OpenEphemeral P1 P2 * P4 *
61614 **
61615 ** Open a new cursor P1 to a transient table.
61616 ** The cursor is always opened read/write even if 
61617 ** the main database is read-only.  The ephemeral
61618 ** table is deleted automatically when the cursor is closed.
61619 **
61620 ** P2 is the number of columns in the ephemeral table.
61621 ** The cursor points to a BTree table if P4==0 and to a BTree index
61622 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
61623 ** that defines the format of keys in the index.
61624 **
61625 ** This opcode was once called OpenTemp.  But that created
61626 ** confusion because the term "temp table", might refer either
61627 ** to a TEMP table at the SQL level, or to a table opened by
61628 ** this opcode.  Then this opcode was call OpenVirtual.  But
61629 ** that created confusion with the whole virtual-table idea.
61630 */
61631 /* Opcode: OpenAutoindex P1 P2 * P4 *
61632 **
61633 ** This opcode works the same as OP_OpenEphemeral.  It has a
61634 ** different name to distinguish its use.  Tables created using
61635 ** by this opcode will be used for automatically created transient
61636 ** indices in joins.
61637 */
61638 case OP_OpenAutoindex: 
61639 case OP_OpenEphemeral: {
61640 #if 0  /* local variables moved into u.ax */
61641   VdbeCursor *pCx;
61642 #endif /* local variables moved into u.ax */
61643   static const int openFlags =
61644       SQLITE_OPEN_READWRITE |
61645       SQLITE_OPEN_CREATE |
61646       SQLITE_OPEN_EXCLUSIVE |
61647       SQLITE_OPEN_DELETEONCLOSE |
61648       SQLITE_OPEN_TRANSIENT_DB;
61649
61650   assert( pOp->p1>=0 );
61651   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
61652   if( u.ax.pCx==0 ) goto no_mem;
61653   u.ax.pCx->nullRow = 1;
61654   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
61655                            &u.ax.pCx->pBt);
61656   if( rc==SQLITE_OK ){
61657     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
61658   }
61659   if( rc==SQLITE_OK ){
61660     /* If a transient index is required, create it by calling
61661     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
61662     ** opening it. If a transient table is required, just use the
61663     ** automatically created table with root-page 1 (an INTKEY table).
61664     */
61665     if( pOp->p4.pKeyInfo ){
61666       int pgno;
61667       assert( pOp->p4type==P4_KEYINFO );
61668       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
61669       if( rc==SQLITE_OK ){
61670         assert( pgno==MASTER_ROOT+1 );
61671         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
61672                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
61673         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
61674         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
61675       }
61676       u.ax.pCx->isTable = 0;
61677     }else{
61678       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
61679       u.ax.pCx->isTable = 1;
61680     }
61681   }
61682   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
61683   break;
61684 }
61685
61686 /* Opcode: OpenPseudo P1 P2 P3 * *
61687 **
61688 ** Open a new cursor that points to a fake table that contains a single
61689 ** row of data.  The content of that one row in the content of memory
61690 ** register P2.  In other words, cursor P1 becomes an alias for the 
61691 ** MEM_Blob content contained in register P2.
61692 **
61693 ** A pseudo-table created by this opcode is used to hold a single
61694 ** row output from the sorter so that the row can be decomposed into
61695 ** individual columns using the OP_Column opcode.  The OP_Column opcode
61696 ** is the only cursor opcode that works with a pseudo-table.
61697 **
61698 ** P3 is the number of fields in the records that will be stored by
61699 ** the pseudo-table.
61700 */
61701 case OP_OpenPseudo: {
61702 #if 0  /* local variables moved into u.ay */
61703   VdbeCursor *pCx;
61704 #endif /* local variables moved into u.ay */
61705
61706   assert( pOp->p1>=0 );
61707   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
61708   if( u.ay.pCx==0 ) goto no_mem;
61709   u.ay.pCx->nullRow = 1;
61710   u.ay.pCx->pseudoTableReg = pOp->p2;
61711   u.ay.pCx->isTable = 1;
61712   u.ay.pCx->isIndex = 0;
61713   break;
61714 }
61715
61716 /* Opcode: Close P1 * * * *
61717 **
61718 ** Close a cursor previously opened as P1.  If P1 is not
61719 ** currently open, this instruction is a no-op.
61720 */
61721 case OP_Close: {
61722   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61723   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
61724   p->apCsr[pOp->p1] = 0;
61725   break;
61726 }
61727
61728 /* Opcode: SeekGe P1 P2 P3 P4 *
61729 **
61730 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61731 ** use the value in register P3 as the key.  If cursor P1 refers 
61732 ** to an SQL index, then P3 is the first in an array of P4 registers 
61733 ** that are used as an unpacked index key. 
61734 **
61735 ** Reposition cursor P1 so that  it points to the smallest entry that 
61736 ** is greater than or equal to the key value. If there are no records 
61737 ** greater than or equal to the key and P2 is not zero, then jump to P2.
61738 **
61739 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
61740 */
61741 /* Opcode: SeekGt P1 P2 P3 P4 *
61742 **
61743 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61744 ** use the value in register P3 as a key. If cursor P1 refers 
61745 ** to an SQL index, then P3 is the first in an array of P4 registers 
61746 ** that are used as an unpacked index key. 
61747 **
61748 ** Reposition cursor P1 so that  it points to the smallest entry that 
61749 ** is greater than the key value. If there are no records greater than 
61750 ** the key and P2 is not zero, then jump to P2.
61751 **
61752 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
61753 */
61754 /* Opcode: SeekLt P1 P2 P3 P4 * 
61755 **
61756 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61757 ** use the value in register P3 as a key. If cursor P1 refers 
61758 ** to an SQL index, then P3 is the first in an array of P4 registers 
61759 ** that are used as an unpacked index key. 
61760 **
61761 ** Reposition cursor P1 so that  it points to the largest entry that 
61762 ** is less than the key value. If there are no records less than 
61763 ** the key and P2 is not zero, then jump to P2.
61764 **
61765 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
61766 */
61767 /* Opcode: SeekLe P1 P2 P3 P4 *
61768 **
61769 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61770 ** use the value in register P3 as a key. If cursor P1 refers 
61771 ** to an SQL index, then P3 is the first in an array of P4 registers 
61772 ** that are used as an unpacked index key. 
61773 **
61774 ** Reposition cursor P1 so that it points to the largest entry that 
61775 ** is less than or equal to the key value. If there are no records 
61776 ** less than or equal to the key and P2 is not zero, then jump to P2.
61777 **
61778 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
61779 */
61780 case OP_SeekLt:         /* jump, in3 */
61781 case OP_SeekLe:         /* jump, in3 */
61782 case OP_SeekGe:         /* jump, in3 */
61783 case OP_SeekGt: {       /* jump, in3 */
61784 #if 0  /* local variables moved into u.az */
61785   int res;
61786   int oc;
61787   VdbeCursor *pC;
61788   UnpackedRecord r;
61789   int nField;
61790   i64 iKey;      /* The rowid we are to seek to */
61791 #endif /* local variables moved into u.az */
61792
61793   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61794   assert( pOp->p2!=0 );
61795   u.az.pC = p->apCsr[pOp->p1];
61796   assert( u.az.pC!=0 );
61797   assert( u.az.pC->pseudoTableReg==0 );
61798   assert( OP_SeekLe == OP_SeekLt+1 );
61799   assert( OP_SeekGe == OP_SeekLt+2 );
61800   assert( OP_SeekGt == OP_SeekLt+3 );
61801   if( u.az.pC->pCursor!=0 ){
61802     u.az.oc = pOp->opcode;
61803     u.az.pC->nullRow = 0;
61804     if( u.az.pC->isTable ){
61805       /* The input value in P3 might be of any type: integer, real, string,
61806       ** blob, or NULL.  But it needs to be an integer before we can do
61807       ** the seek, so covert it. */
61808       pIn3 = &aMem[pOp->p3];
61809       applyNumericAffinity(pIn3);
61810       u.az.iKey = sqlite3VdbeIntValue(pIn3);
61811       u.az.pC->rowidIsValid = 0;
61812
61813       /* If the P3 value could not be converted into an integer without
61814       ** loss of information, then special processing is required... */
61815       if( (pIn3->flags & MEM_Int)==0 ){
61816         if( (pIn3->flags & MEM_Real)==0 ){
61817           /* If the P3 value cannot be converted into any kind of a number,
61818           ** then the seek is not possible, so jump to P2 */
61819           pc = pOp->p2 - 1;
61820           break;
61821         }
61822         /* If we reach this point, then the P3 value must be a floating
61823         ** point number. */
61824         assert( (pIn3->flags & MEM_Real)!=0 );
61825
61826         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
61827           /* The P3 value is too large in magnitude to be expressed as an
61828           ** integer. */
61829           u.az.res = 1;
61830           if( pIn3->r<0 ){
61831             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61832               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
61833               if( rc!=SQLITE_OK ) goto abort_due_to_error;
61834             }
61835           }else{
61836             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61837               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
61838               if( rc!=SQLITE_OK ) goto abort_due_to_error;
61839             }
61840           }
61841           if( u.az.res ){
61842             pc = pOp->p2 - 1;
61843           }
61844           break;
61845         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
61846           /* Use the ceiling() function to convert real->int */
61847           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
61848         }else{
61849           /* Use the floor() function to convert real->int */
61850           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
61851           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
61852         }
61853       }
61854       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
61855       if( rc!=SQLITE_OK ){
61856         goto abort_due_to_error;
61857       }
61858       if( u.az.res==0 ){
61859         u.az.pC->rowidIsValid = 1;
61860         u.az.pC->lastRowid = u.az.iKey;
61861       }
61862     }else{
61863       u.az.nField = pOp->p4.i;
61864       assert( pOp->p4type==P4_INT32 );
61865       assert( u.az.nField>0 );
61866       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
61867       u.az.r.nField = (u16)u.az.nField;
61868
61869       /* The next line of code computes as follows, only faster:
61870       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
61871       **     u.az.r.flags = UNPACKED_INCRKEY;
61872       **   }else{
61873       **     u.az.r.flags = 0;
61874       **   }
61875       */
61876       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
61877       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
61878       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
61879       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
61880       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
61881
61882       u.az.r.aMem = &aMem[pOp->p3];
61883       ExpandBlob(u.az.r.aMem);
61884       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
61885       if( rc!=SQLITE_OK ){
61886         goto abort_due_to_error;
61887       }
61888       u.az.pC->rowidIsValid = 0;
61889     }
61890     u.az.pC->deferredMoveto = 0;
61891     u.az.pC->cacheStatus = CACHE_STALE;
61892 #ifdef SQLITE_TEST
61893     sqlite3_search_count++;
61894 #endif
61895     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61896       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
61897         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
61898         if( rc!=SQLITE_OK ) goto abort_due_to_error;
61899         u.az.pC->rowidIsValid = 0;
61900       }else{
61901         u.az.res = 0;
61902       }
61903     }else{
61904       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61905       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
61906         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
61907         if( rc!=SQLITE_OK ) goto abort_due_to_error;
61908         u.az.pC->rowidIsValid = 0;
61909       }else{
61910         /* u.az.res might be negative because the table is empty.  Check to
61911         ** see if this is the case.
61912         */
61913         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
61914       }
61915     }
61916     assert( pOp->p2>0 );
61917     if( u.az.res ){
61918       pc = pOp->p2 - 1;
61919     }
61920   }else{
61921     /* This happens when attempting to open the sqlite3_master table
61922     ** for read access returns SQLITE_EMPTY. In this case always
61923     ** take the jump (since there are no records in the table).
61924     */
61925     pc = pOp->p2 - 1;
61926   }
61927   break;
61928 }
61929
61930 /* Opcode: Seek P1 P2 * * *
61931 **
61932 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
61933 ** for P1 to move so that it points to the rowid given by P2.
61934 **
61935 ** This is actually a deferred seek.  Nothing actually happens until
61936 ** the cursor is used to read a record.  That way, if no reads
61937 ** occur, no unnecessary I/O happens.
61938 */
61939 case OP_Seek: {    /* in2 */
61940 #if 0  /* local variables moved into u.ba */
61941   VdbeCursor *pC;
61942 #endif /* local variables moved into u.ba */
61943
61944   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61945   u.ba.pC = p->apCsr[pOp->p1];
61946   assert( u.ba.pC!=0 );
61947   if( ALWAYS(u.ba.pC->pCursor!=0) ){
61948     assert( u.ba.pC->isTable );
61949     u.ba.pC->nullRow = 0;
61950     pIn2 = &aMem[pOp->p2];
61951     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
61952     u.ba.pC->rowidIsValid = 0;
61953     u.ba.pC->deferredMoveto = 1;
61954   }
61955   break;
61956 }
61957   
61958
61959 /* Opcode: Found P1 P2 P3 P4 *
61960 **
61961 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61962 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
61963 ** record.
61964 **
61965 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61966 ** is a prefix of any entry in P1 then a jump is made to P2 and
61967 ** P1 is left pointing at the matching entry.
61968 */
61969 /* Opcode: NotFound P1 P2 P3 P4 *
61970 **
61971 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61972 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
61973 ** record.
61974 ** 
61975 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61976 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
61977 ** does contain an entry whose prefix matches the P3/P4 record then control
61978 ** falls through to the next instruction and P1 is left pointing at the
61979 ** matching entry.
61980 **
61981 ** See also: Found, NotExists, IsUnique
61982 */
61983 case OP_NotFound:       /* jump, in3 */
61984 case OP_Found: {        /* jump, in3 */
61985 #if 0  /* local variables moved into u.bb */
61986   int alreadyExists;
61987   VdbeCursor *pC;
61988   int res;
61989   UnpackedRecord *pIdxKey;
61990   UnpackedRecord r;
61991   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
61992 #endif /* local variables moved into u.bb */
61993
61994 #ifdef SQLITE_TEST
61995   sqlite3_found_count++;
61996 #endif
61997
61998   u.bb.alreadyExists = 0;
61999   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62000   assert( pOp->p4type==P4_INT32 );
62001   u.bb.pC = p->apCsr[pOp->p1];
62002   assert( u.bb.pC!=0 );
62003   pIn3 = &aMem[pOp->p3];
62004   if( ALWAYS(u.bb.pC->pCursor!=0) ){
62005
62006     assert( u.bb.pC->isTable==0 );
62007     if( pOp->p4.i>0 ){
62008       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
62009       u.bb.r.nField = (u16)pOp->p4.i;
62010       u.bb.r.aMem = pIn3;
62011       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
62012       u.bb.pIdxKey = &u.bb.r;
62013     }else{
62014       assert( pIn3->flags & MEM_Blob );
62015       ExpandBlob(pIn3);
62016       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
62017                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
62018       if( u.bb.pIdxKey==0 ){
62019         goto no_mem;
62020       }
62021       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
62022     }
62023     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
62024     if( pOp->p4.i==0 ){
62025       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
62026     }
62027     if( rc!=SQLITE_OK ){
62028       break;
62029     }
62030     u.bb.alreadyExists = (u.bb.res==0);
62031     u.bb.pC->deferredMoveto = 0;
62032     u.bb.pC->cacheStatus = CACHE_STALE;
62033   }
62034   if( pOp->opcode==OP_Found ){
62035     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
62036   }else{
62037     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
62038   }
62039   break;
62040 }
62041
62042 /* Opcode: IsUnique P1 P2 P3 P4 *
62043 **
62044 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
62045 ** no data and where the key are records generated by OP_MakeRecord with
62046 ** the list field being the integer ROWID of the entry that the index
62047 ** entry refers to.
62048 **
62049 ** The P3 register contains an integer record number. Call this record 
62050 ** number R. Register P4 is the first in a set of N contiguous registers
62051 ** that make up an unpacked index key that can be used with cursor P1.
62052 ** The value of N can be inferred from the cursor. N includes the rowid
62053 ** value appended to the end of the index record. This rowid value may
62054 ** or may not be the same as R.
62055 **
62056 ** If any of the N registers beginning with register P4 contains a NULL
62057 ** value, jump immediately to P2.
62058 **
62059 ** Otherwise, this instruction checks if cursor P1 contains an entry
62060 ** where the first (N-1) fields match but the rowid value at the end
62061 ** of the index entry is not R. If there is no such entry, control jumps
62062 ** to instruction P2. Otherwise, the rowid of the conflicting index
62063 ** entry is copied to register P3 and control falls through to the next
62064 ** instruction.
62065 **
62066 ** See also: NotFound, NotExists, Found
62067 */
62068 case OP_IsUnique: {        /* jump, in3 */
62069 #if 0  /* local variables moved into u.bc */
62070   u16 ii;
62071   VdbeCursor *pCx;
62072   BtCursor *pCrsr;
62073   u16 nField;
62074   Mem *aMx;
62075   UnpackedRecord r;                  /* B-Tree index search key */
62076   i64 R;                             /* Rowid stored in register P3 */
62077 #endif /* local variables moved into u.bc */
62078
62079   pIn3 = &aMem[pOp->p3];
62080   u.bc.aMx = &aMem[pOp->p4.i];
62081   /* Assert that the values of parameters P1 and P4 are in range. */
62082   assert( pOp->p4type==P4_INT32 );
62083   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
62084   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62085
62086   /* Find the index cursor. */
62087   u.bc.pCx = p->apCsr[pOp->p1];
62088   assert( u.bc.pCx->deferredMoveto==0 );
62089   u.bc.pCx->seekResult = 0;
62090   u.bc.pCx->cacheStatus = CACHE_STALE;
62091   u.bc.pCrsr = u.bc.pCx->pCursor;
62092
62093   /* If any of the values are NULL, take the jump. */
62094   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
62095   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
62096     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
62097       pc = pOp->p2 - 1;
62098       u.bc.pCrsr = 0;
62099       break;
62100     }
62101   }
62102   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
62103
62104   if( u.bc.pCrsr!=0 ){
62105     /* Populate the index search key. */
62106     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
62107     u.bc.r.nField = u.bc.nField + 1;
62108     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
62109     u.bc.r.aMem = u.bc.aMx;
62110
62111     /* Extract the value of u.bc.R from register P3. */
62112     sqlite3VdbeMemIntegerify(pIn3);
62113     u.bc.R = pIn3->u.i;
62114
62115     /* Search the B-Tree index. If no conflicting record is found, jump
62116     ** to P2. Otherwise, copy the rowid of the conflicting record to
62117     ** register P3 and fall through to the next instruction.  */
62118     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
62119     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
62120       pc = pOp->p2 - 1;
62121     }else{
62122       pIn3->u.i = u.bc.r.rowid;
62123     }
62124   }
62125   break;
62126 }
62127
62128 /* Opcode: NotExists P1 P2 P3 * *
62129 **
62130 ** Use the content of register P3 as a integer key.  If a record 
62131 ** with that key does not exist in table of P1, then jump to P2. 
62132 ** If the record does exist, then fall thru.  The cursor is left 
62133 ** pointing to the record if it exists.
62134 **
62135 ** The difference between this operation and NotFound is that this
62136 ** operation assumes the key is an integer and that P1 is a table whereas
62137 ** NotFound assumes key is a blob constructed from MakeRecord and
62138 ** P1 is an index.
62139 **
62140 ** See also: Found, NotFound, IsUnique
62141 */
62142 case OP_NotExists: {        /* jump, in3 */
62143 #if 0  /* local variables moved into u.bd */
62144   VdbeCursor *pC;
62145   BtCursor *pCrsr;
62146   int res;
62147   u64 iKey;
62148 #endif /* local variables moved into u.bd */
62149
62150   pIn3 = &aMem[pOp->p3];
62151   assert( pIn3->flags & MEM_Int );
62152   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62153   u.bd.pC = p->apCsr[pOp->p1];
62154   assert( u.bd.pC!=0 );
62155   assert( u.bd.pC->isTable );
62156   assert( u.bd.pC->pseudoTableReg==0 );
62157   u.bd.pCrsr = u.bd.pC->pCursor;
62158   if( u.bd.pCrsr!=0 ){
62159     u.bd.res = 0;
62160     u.bd.iKey = pIn3->u.i;
62161     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
62162     u.bd.pC->lastRowid = pIn3->u.i;
62163     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
62164     u.bd.pC->nullRow = 0;
62165     u.bd.pC->cacheStatus = CACHE_STALE;
62166     u.bd.pC->deferredMoveto = 0;
62167     if( u.bd.res!=0 ){
62168       pc = pOp->p2 - 1;
62169       assert( u.bd.pC->rowidIsValid==0 );
62170     }
62171     u.bd.pC->seekResult = u.bd.res;
62172   }else{
62173     /* This happens when an attempt to open a read cursor on the
62174     ** sqlite_master table returns SQLITE_EMPTY.
62175     */
62176     pc = pOp->p2 - 1;
62177     assert( u.bd.pC->rowidIsValid==0 );
62178     u.bd.pC->seekResult = 0;
62179   }
62180   break;
62181 }
62182
62183 /* Opcode: Sequence P1 P2 * * *
62184 **
62185 ** Find the next available sequence number for cursor P1.
62186 ** Write the sequence number into register P2.
62187 ** The sequence number on the cursor is incremented after this
62188 ** instruction.  
62189 */
62190 case OP_Sequence: {           /* out2-prerelease */
62191   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62192   assert( p->apCsr[pOp->p1]!=0 );
62193   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
62194   break;
62195 }
62196
62197
62198 /* Opcode: NewRowid P1 P2 P3 * *
62199 **
62200 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
62201 ** The record number is not previously used as a key in the database
62202 ** table that cursor P1 points to.  The new record number is written
62203 ** written to register P2.
62204 **
62205 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
62206 ** the largest previously generated record number. No new record numbers are
62207 ** allowed to be less than this value. When this value reaches its maximum, 
62208 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
62209 ** generated record number. This P3 mechanism is used to help implement the
62210 ** AUTOINCREMENT feature.
62211 */
62212 case OP_NewRowid: {           /* out2-prerelease */
62213 #if 0  /* local variables moved into u.be */
62214   i64 v;                 /* The new rowid */
62215   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
62216   int res;               /* Result of an sqlite3BtreeLast() */
62217   int cnt;               /* Counter to limit the number of searches */
62218   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
62219   VdbeFrame *pFrame;     /* Root frame of VDBE */
62220 #endif /* local variables moved into u.be */
62221
62222   u.be.v = 0;
62223   u.be.res = 0;
62224   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62225   u.be.pC = p->apCsr[pOp->p1];
62226   assert( u.be.pC!=0 );
62227   if( NEVER(u.be.pC->pCursor==0) ){
62228     /* The zero initialization above is all that is needed */
62229   }else{
62230     /* The next rowid or record number (different terms for the same
62231     ** thing) is obtained in a two-step algorithm.
62232     **
62233     ** First we attempt to find the largest existing rowid and add one
62234     ** to that.  But if the largest existing rowid is already the maximum
62235     ** positive integer, we have to fall through to the second
62236     ** probabilistic algorithm
62237     **
62238     ** The second algorithm is to select a rowid at random and see if
62239     ** it already exists in the table.  If it does not exist, we have
62240     ** succeeded.  If the random rowid does exist, we select a new one
62241     ** and try again, up to 100 times.
62242     */
62243     assert( u.be.pC->isTable );
62244     u.be.cnt = 0;
62245
62246 #ifdef SQLITE_32BIT_ROWID
62247 #   define MAX_ROWID 0x7fffffff
62248 #else
62249     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
62250     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
62251     ** to provide the constant while making all compilers happy.
62252     */
62253 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
62254 #endif
62255
62256     if( !u.be.pC->useRandomRowid ){
62257       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
62258       if( u.be.v==0 ){
62259         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
62260         if( rc!=SQLITE_OK ){
62261           goto abort_due_to_error;
62262         }
62263         if( u.be.res ){
62264           u.be.v = 1;   /* IMP: R-61914-48074 */
62265         }else{
62266           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
62267           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
62268           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
62269           if( u.be.v==MAX_ROWID ){
62270             u.be.pC->useRandomRowid = 1;
62271           }else{
62272             u.be.v++;   /* IMP: R-29538-34987 */
62273           }
62274         }
62275       }
62276
62277 #ifndef SQLITE_OMIT_AUTOINCREMENT
62278       if( pOp->p3 ){
62279         /* Assert that P3 is a valid memory cell. */
62280         assert( pOp->p3>0 );
62281         if( p->pFrame ){
62282           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
62283           /* Assert that P3 is a valid memory cell. */
62284           assert( pOp->p3<=u.be.pFrame->nMem );
62285           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
62286         }else{
62287           /* Assert that P3 is a valid memory cell. */
62288           assert( pOp->p3<=p->nMem );
62289           u.be.pMem = &aMem[pOp->p3];
62290         }
62291
62292         REGISTER_TRACE(pOp->p3, u.be.pMem);
62293         sqlite3VdbeMemIntegerify(u.be.pMem);
62294         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
62295         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
62296           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
62297           goto abort_due_to_error;
62298         }
62299         if( u.be.v<u.be.pMem->u.i+1 ){
62300           u.be.v = u.be.pMem->u.i + 1;
62301         }
62302         u.be.pMem->u.i = u.be.v;
62303       }
62304 #endif
62305
62306       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
62307     }
62308     if( u.be.pC->useRandomRowid ){
62309       /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
62310       ** largest possible integer (9223372036854775807) then the database
62311       ** engine starts picking candidate ROWIDs at random until it finds one
62312       ** that is not previously used.
62313       */
62314       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
62315                              ** an AUTOINCREMENT table. */
62316       u.be.v = db->lastRowid;
62317       u.be.cnt = 0;
62318       do{
62319         if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
62320           u.be.v++;
62321         }else{
62322           sqlite3_randomness(sizeof(u.be.v), &u.be.v);
62323           if( u.be.cnt<5 ) u.be.v &= 0xffffff;
62324         }
62325         rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
62326         u.be.cnt++;
62327       }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
62328       if( rc==SQLITE_OK && u.be.res==0 ){
62329         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
62330         goto abort_due_to_error;
62331       }
62332     }
62333     u.be.pC->rowidIsValid = 0;
62334     u.be.pC->deferredMoveto = 0;
62335     u.be.pC->cacheStatus = CACHE_STALE;
62336   }
62337   pOut->u.i = u.be.v;
62338   break;
62339 }
62340
62341 /* Opcode: Insert P1 P2 P3 P4 P5
62342 **
62343 ** Write an entry into the table of cursor P1.  A new entry is
62344 ** created if it doesn't already exist or the data for an existing
62345 ** entry is overwritten.  The data is the value MEM_Blob stored in register
62346 ** number P2. The key is stored in register P3. The key must
62347 ** be a MEM_Int.
62348 **
62349 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
62350 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
62351 ** then rowid is stored for subsequent return by the
62352 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
62353 **
62354 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
62355 ** the last seek operation (OP_NotExists) was a success, then this
62356 ** operation will not attempt to find the appropriate row before doing
62357 ** the insert but will instead overwrite the row that the cursor is
62358 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
62359 ** has already positioned the cursor correctly.  This is an optimization
62360 ** that boosts performance by avoiding redundant seeks.
62361 **
62362 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
62363 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
62364 ** is part of an INSERT operation.  The difference is only important to
62365 ** the update hook.
62366 **
62367 ** Parameter P4 may point to a string containing the table-name, or
62368 ** may be NULL. If it is not NULL, then the update-hook 
62369 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
62370 **
62371 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
62372 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
62373 ** and register P2 becomes ephemeral.  If the cursor is changed, the
62374 ** value of register P2 will then change.  Make sure this does not
62375 ** cause any problems.)
62376 **
62377 ** This instruction only works on tables.  The equivalent instruction
62378 ** for indices is OP_IdxInsert.
62379 */
62380 /* Opcode: InsertInt P1 P2 P3 P4 P5
62381 **
62382 ** This works exactly like OP_Insert except that the key is the
62383 ** integer value P3, not the value of the integer stored in register P3.
62384 */
62385 case OP_Insert: 
62386 case OP_InsertInt: {
62387 #if 0  /* local variables moved into u.bf */
62388   Mem *pData;       /* MEM cell holding data for the record to be inserted */
62389   Mem *pKey;        /* MEM cell holding key  for the record */
62390   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62391   VdbeCursor *pC;   /* Cursor to table into which insert is written */
62392   int nZero;        /* Number of zero-bytes to append */
62393   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62394   const char *zDb;  /* database name - used by the update hook */
62395   const char *zTbl; /* Table name - used by the opdate hook */
62396   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62397 #endif /* local variables moved into u.bf */
62398
62399   u.bf.pData = &aMem[pOp->p2];
62400   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62401   u.bf.pC = p->apCsr[pOp->p1];
62402   assert( u.bf.pC!=0 );
62403   assert( u.bf.pC->pCursor!=0 );
62404   assert( u.bf.pC->pseudoTableReg==0 );
62405   assert( u.bf.pC->isTable );
62406   REGISTER_TRACE(pOp->p2, u.bf.pData);
62407
62408   if( pOp->opcode==OP_Insert ){
62409     u.bf.pKey = &aMem[pOp->p3];
62410     assert( u.bf.pKey->flags & MEM_Int );
62411     REGISTER_TRACE(pOp->p3, u.bf.pKey);
62412     u.bf.iKey = u.bf.pKey->u.i;
62413   }else{
62414     assert( pOp->opcode==OP_InsertInt );
62415     u.bf.iKey = pOp->p3;
62416   }
62417
62418   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
62419   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
62420   if( u.bf.pData->flags & MEM_Null ){
62421     u.bf.pData->z = 0;
62422     u.bf.pData->n = 0;
62423   }else{
62424     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
62425   }
62426   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
62427   if( u.bf.pData->flags & MEM_Zero ){
62428     u.bf.nZero = u.bf.pData->u.nZero;
62429   }else{
62430     u.bf.nZero = 0;
62431   }
62432   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
62433   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
62434                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
62435                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
62436   );
62437   u.bf.pC->rowidIsValid = 0;
62438   u.bf.pC->deferredMoveto = 0;
62439   u.bf.pC->cacheStatus = CACHE_STALE;
62440
62441   /* Invoke the update-hook if required. */
62442   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62443     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
62444     u.bf.zTbl = pOp->p4.z;
62445     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
62446     assert( u.bf.pC->isTable );
62447     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
62448     assert( u.bf.pC->iDb>=0 );
62449   }
62450   break;
62451 }
62452
62453 /* Opcode: Delete P1 P2 * P4 *
62454 **
62455 ** Delete the record at which the P1 cursor is currently pointing.
62456 **
62457 ** The cursor will be left pointing at either the next or the previous
62458 ** record in the table. If it is left pointing at the next record, then
62459 ** the next Next instruction will be a no-op.  Hence it is OK to delete
62460 ** a record from within an Next loop.
62461 **
62462 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
62463 ** incremented (otherwise not).
62464 **
62465 ** P1 must not be pseudo-table.  It has to be a real table with
62466 ** multiple rows.
62467 **
62468 ** If P4 is not NULL, then it is the name of the table that P1 is
62469 ** pointing to.  The update hook will be invoked, if it exists.
62470 ** If P4 is not NULL then the P1 cursor must have been positioned
62471 ** using OP_NotFound prior to invoking this opcode.
62472 */
62473 case OP_Delete: {
62474 #if 0  /* local variables moved into u.bg */
62475   i64 iKey;
62476   VdbeCursor *pC;
62477 #endif /* local variables moved into u.bg */
62478
62479   u.bg.iKey = 0;
62480   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62481   u.bg.pC = p->apCsr[pOp->p1];
62482   assert( u.bg.pC!=0 );
62483   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
62484
62485   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
62486   ** row being deleted.
62487   */
62488   if( db->xUpdateCallback && pOp->p4.z ){
62489     assert( u.bg.pC->isTable );
62490     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
62491     u.bg.iKey = u.bg.pC->lastRowid;
62492   }
62493
62494   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
62495   ** OP_Column on the same table without any intervening operations that
62496   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
62497   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
62498   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
62499   ** to guard against future changes to the code generator.
62500   **/
62501   assert( u.bg.pC->deferredMoveto==0 );
62502   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
62503   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62504
62505   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
62506   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
62507   u.bg.pC->cacheStatus = CACHE_STALE;
62508
62509   /* Invoke the update-hook if required. */
62510   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62511     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
62512     const char *zTbl = pOp->p4.z;
62513     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
62514     assert( u.bg.pC->iDb>=0 );
62515   }
62516   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
62517   break;
62518 }
62519 /* Opcode: ResetCount * * * * *
62520 **
62521 ** The value of the change counter is copied to the database handle
62522 ** change counter (returned by subsequent calls to sqlite3_changes()).
62523 ** Then the VMs internal change counter resets to 0.
62524 ** This is used by trigger programs.
62525 */
62526 case OP_ResetCount: {
62527   sqlite3VdbeSetChanges(db, p->nChange);
62528   p->nChange = 0;
62529   break;
62530 }
62531
62532 /* Opcode: RowData P1 P2 * * *
62533 **
62534 ** Write into register P2 the complete row data for cursor P1.
62535 ** There is no interpretation of the data.  
62536 ** It is just copied onto the P2 register exactly as 
62537 ** it is found in the database file.
62538 **
62539 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
62540 ** of a real table, not a pseudo-table.
62541 */
62542 /* Opcode: RowKey P1 P2 * * *
62543 **
62544 ** Write into register P2 the complete row key for cursor P1.
62545 ** There is no interpretation of the data.  
62546 ** The key is copied onto the P3 register exactly as 
62547 ** it is found in the database file.
62548 **
62549 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
62550 ** of a real table, not a pseudo-table.
62551 */
62552 case OP_RowKey:
62553 case OP_RowData: {
62554 #if 0  /* local variables moved into u.bh */
62555   VdbeCursor *pC;
62556   BtCursor *pCrsr;
62557   u32 n;
62558   i64 n64;
62559 #endif /* local variables moved into u.bh */
62560
62561   pOut = &aMem[pOp->p2];
62562
62563   /* Note that RowKey and RowData are really exactly the same instruction */
62564   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62565   u.bh.pC = p->apCsr[pOp->p1];
62566   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
62567   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
62568   assert( u.bh.pC!=0 );
62569   assert( u.bh.pC->nullRow==0 );
62570   assert( u.bh.pC->pseudoTableReg==0 );
62571   assert( u.bh.pC->pCursor!=0 );
62572   u.bh.pCrsr = u.bh.pC->pCursor;
62573   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
62574
62575   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
62576   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
62577   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
62578   ** a no-op and can never fail.  But we leave it in place as a safety.
62579   */
62580   assert( u.bh.pC->deferredMoveto==0 );
62581   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
62582   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62583
62584   if( u.bh.pC->isIndex ){
62585     assert( !u.bh.pC->isTable );
62586     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
62587     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
62588     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
62589       goto too_big;
62590     }
62591     u.bh.n = (u32)u.bh.n64;
62592   }else{
62593     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
62594     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
62595     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62596       goto too_big;
62597     }
62598   }
62599   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
62600     goto no_mem;
62601   }
62602   pOut->n = u.bh.n;
62603   MemSetTypeFlag(pOut, MEM_Blob);
62604   if( u.bh.pC->isIndex ){
62605     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62606   }else{
62607     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62608   }
62609   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
62610   UPDATE_MAX_BLOBSIZE(pOut);
62611   break;
62612 }
62613
62614 /* Opcode: Rowid P1 P2 * * *
62615 **
62616 ** Store in register P2 an integer which is the key of the table entry that
62617 ** P1 is currently point to.
62618 **
62619 ** P1 can be either an ordinary table or a virtual table.  There used to
62620 ** be a separate OP_VRowid opcode for use with virtual tables, but this
62621 ** one opcode now works for both table types.
62622 */
62623 case OP_Rowid: {                 /* out2-prerelease */
62624 #if 0  /* local variables moved into u.bi */
62625   VdbeCursor *pC;
62626   i64 v;
62627   sqlite3_vtab *pVtab;
62628   const sqlite3_module *pModule;
62629 #endif /* local variables moved into u.bi */
62630
62631   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62632   u.bi.pC = p->apCsr[pOp->p1];
62633   assert( u.bi.pC!=0 );
62634   assert( u.bi.pC->pseudoTableReg==0 );
62635   if( u.bi.pC->nullRow ){
62636     pOut->flags = MEM_Null;
62637     break;
62638   }else if( u.bi.pC->deferredMoveto ){
62639     u.bi.v = u.bi.pC->movetoTarget;
62640 #ifndef SQLITE_OMIT_VIRTUALTABLE
62641   }else if( u.bi.pC->pVtabCursor ){
62642     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
62643     u.bi.pModule = u.bi.pVtab->pModule;
62644     assert( u.bi.pModule->xRowid );
62645     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
62646     sqlite3DbFree(db, p->zErrMsg);
62647     p->zErrMsg = u.bi.pVtab->zErrMsg;
62648     u.bi.pVtab->zErrMsg = 0;
62649 #endif /* SQLITE_OMIT_VIRTUALTABLE */
62650   }else{
62651     assert( u.bi.pC->pCursor!=0 );
62652     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
62653     if( rc ) goto abort_due_to_error;
62654     if( u.bi.pC->rowidIsValid ){
62655       u.bi.v = u.bi.pC->lastRowid;
62656     }else{
62657       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
62658       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
62659     }
62660   }
62661   pOut->u.i = u.bi.v;
62662   break;
62663 }
62664
62665 /* Opcode: NullRow P1 * * * *
62666 **
62667 ** Move the cursor P1 to a null row.  Any OP_Column operations
62668 ** that occur while the cursor is on the null row will always
62669 ** write a NULL.
62670 */
62671 case OP_NullRow: {
62672 #if 0  /* local variables moved into u.bj */
62673   VdbeCursor *pC;
62674 #endif /* local variables moved into u.bj */
62675
62676   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62677   u.bj.pC = p->apCsr[pOp->p1];
62678   assert( u.bj.pC!=0 );
62679   u.bj.pC->nullRow = 1;
62680   u.bj.pC->rowidIsValid = 0;
62681   if( u.bj.pC->pCursor ){
62682     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
62683   }
62684   break;
62685 }
62686
62687 /* Opcode: Last P1 P2 * * *
62688 **
62689 ** The next use of the Rowid or Column or Next instruction for P1 
62690 ** will refer to the last entry in the database table or index.
62691 ** If the table or index is empty and P2>0, then jump immediately to P2.
62692 ** If P2 is 0 or if the table or index is not empty, fall through
62693 ** to the following instruction.
62694 */
62695 case OP_Last: {        /* jump */
62696 #if 0  /* local variables moved into u.bk */
62697   VdbeCursor *pC;
62698   BtCursor *pCrsr;
62699   int res;
62700 #endif /* local variables moved into u.bk */
62701
62702   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62703   u.bk.pC = p->apCsr[pOp->p1];
62704   assert( u.bk.pC!=0 );
62705   u.bk.pCrsr = u.bk.pC->pCursor;
62706   if( u.bk.pCrsr==0 ){
62707     u.bk.res = 1;
62708   }else{
62709     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
62710   }
62711   u.bk.pC->nullRow = (u8)u.bk.res;
62712   u.bk.pC->deferredMoveto = 0;
62713   u.bk.pC->rowidIsValid = 0;
62714   u.bk.pC->cacheStatus = CACHE_STALE;
62715   if( pOp->p2>0 && u.bk.res ){
62716     pc = pOp->p2 - 1;
62717   }
62718   break;
62719 }
62720
62721
62722 /* Opcode: Sort P1 P2 * * *
62723 **
62724 ** This opcode does exactly the same thing as OP_Rewind except that
62725 ** it increments an undocumented global variable used for testing.
62726 **
62727 ** Sorting is accomplished by writing records into a sorting index,
62728 ** then rewinding that index and playing it back from beginning to
62729 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
62730 ** rewinding so that the global variable will be incremented and
62731 ** regression tests can determine whether or not the optimizer is
62732 ** correctly optimizing out sorts.
62733 */
62734 case OP_Sort: {        /* jump */
62735 #ifdef SQLITE_TEST
62736   sqlite3_sort_count++;
62737   sqlite3_search_count--;
62738 #endif
62739   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
62740   /* Fall through into OP_Rewind */
62741 }
62742 /* Opcode: Rewind P1 P2 * * *
62743 **
62744 ** The next use of the Rowid or Column or Next instruction for P1 
62745 ** will refer to the first entry in the database table or index.
62746 ** If the table or index is empty and P2>0, then jump immediately to P2.
62747 ** If P2 is 0 or if the table or index is not empty, fall through
62748 ** to the following instruction.
62749 */
62750 case OP_Rewind: {        /* jump */
62751 #if 0  /* local variables moved into u.bl */
62752   VdbeCursor *pC;
62753   BtCursor *pCrsr;
62754   int res;
62755 #endif /* local variables moved into u.bl */
62756
62757   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62758   u.bl.pC = p->apCsr[pOp->p1];
62759   assert( u.bl.pC!=0 );
62760   u.bl.res = 1;
62761   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
62762     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
62763     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
62764     u.bl.pC->deferredMoveto = 0;
62765     u.bl.pC->cacheStatus = CACHE_STALE;
62766     u.bl.pC->rowidIsValid = 0;
62767   }
62768   u.bl.pC->nullRow = (u8)u.bl.res;
62769   assert( pOp->p2>0 && pOp->p2<p->nOp );
62770   if( u.bl.res ){
62771     pc = pOp->p2 - 1;
62772   }
62773   break;
62774 }
62775
62776 /* Opcode: Next P1 P2 * * P5
62777 **
62778 ** Advance cursor P1 so that it points to the next key/data pair in its
62779 ** table or index.  If there are no more key/value pairs then fall through
62780 ** to the following instruction.  But if the cursor advance was successful,
62781 ** jump immediately to P2.
62782 **
62783 ** The P1 cursor must be for a real table, not a pseudo-table.
62784 **
62785 ** If P5 is positive and the jump is taken, then event counter
62786 ** number P5-1 in the prepared statement is incremented.
62787 **
62788 ** See also: Prev
62789 */
62790 /* Opcode: Prev P1 P2 * * P5
62791 **
62792 ** Back up cursor P1 so that it points to the previous key/data pair in its
62793 ** table or index.  If there is no previous key/value pairs then fall through
62794 ** to the following instruction.  But if the cursor backup was successful,
62795 ** jump immediately to P2.
62796 **
62797 ** The P1 cursor must be for a real table, not a pseudo-table.
62798 **
62799 ** If P5 is positive and the jump is taken, then event counter
62800 ** number P5-1 in the prepared statement is incremented.
62801 */
62802 case OP_Prev:          /* jump */
62803 case OP_Next: {        /* jump */
62804 #if 0  /* local variables moved into u.bm */
62805   VdbeCursor *pC;
62806   BtCursor *pCrsr;
62807   int res;
62808 #endif /* local variables moved into u.bm */
62809
62810   CHECK_FOR_INTERRUPT;
62811   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62812   assert( pOp->p5<=ArraySize(p->aCounter) );
62813   u.bm.pC = p->apCsr[pOp->p1];
62814   if( u.bm.pC==0 ){
62815     break;  /* See ticket #2273 */
62816   }
62817   u.bm.pCrsr = u.bm.pC->pCursor;
62818   if( u.bm.pCrsr==0 ){
62819     u.bm.pC->nullRow = 1;
62820     break;
62821   }
62822   u.bm.res = 1;
62823   assert( u.bm.pC->deferredMoveto==0 );
62824   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
62825                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
62826   u.bm.pC->nullRow = (u8)u.bm.res;
62827   u.bm.pC->cacheStatus = CACHE_STALE;
62828   if( u.bm.res==0 ){
62829     pc = pOp->p2 - 1;
62830     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
62831 #ifdef SQLITE_TEST
62832     sqlite3_search_count++;
62833 #endif
62834   }
62835   u.bm.pC->rowidIsValid = 0;
62836   break;
62837 }
62838
62839 /* Opcode: IdxInsert P1 P2 P3 * P5
62840 **
62841 ** Register P2 holds a SQL index key made using the
62842 ** MakeRecord instructions.  This opcode writes that key
62843 ** into the index P1.  Data for the entry is nil.
62844 **
62845 ** P3 is a flag that provides a hint to the b-tree layer that this
62846 ** insert is likely to be an append.
62847 **
62848 ** This instruction only works for indices.  The equivalent instruction
62849 ** for tables is OP_Insert.
62850 */
62851 case OP_IdxInsert: {        /* in2 */
62852 #if 0  /* local variables moved into u.bn */
62853   VdbeCursor *pC;
62854   BtCursor *pCrsr;
62855   int nKey;
62856   const char *zKey;
62857 #endif /* local variables moved into u.bn */
62858
62859   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62860   u.bn.pC = p->apCsr[pOp->p1];
62861   assert( u.bn.pC!=0 );
62862   pIn2 = &aMem[pOp->p2];
62863   assert( pIn2->flags & MEM_Blob );
62864   u.bn.pCrsr = u.bn.pC->pCursor;
62865   if( ALWAYS(u.bn.pCrsr!=0) ){
62866     assert( u.bn.pC->isTable==0 );
62867     rc = ExpandBlob(pIn2);
62868     if( rc==SQLITE_OK ){
62869       u.bn.nKey = pIn2->n;
62870       u.bn.zKey = pIn2->z;
62871       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
62872           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
62873       );
62874       assert( u.bn.pC->deferredMoveto==0 );
62875       u.bn.pC->cacheStatus = CACHE_STALE;
62876     }
62877   }
62878   break;
62879 }
62880
62881 /* Opcode: IdxDelete P1 P2 P3 * *
62882 **
62883 ** The content of P3 registers starting at register P2 form
62884 ** an unpacked index key. This opcode removes that entry from the 
62885 ** index opened by cursor P1.
62886 */
62887 case OP_IdxDelete: {
62888 #if 0  /* local variables moved into u.bo */
62889   VdbeCursor *pC;
62890   BtCursor *pCrsr;
62891   int res;
62892   UnpackedRecord r;
62893 #endif /* local variables moved into u.bo */
62894
62895   assert( pOp->p3>0 );
62896   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
62897   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62898   u.bo.pC = p->apCsr[pOp->p1];
62899   assert( u.bo.pC!=0 );
62900   u.bo.pCrsr = u.bo.pC->pCursor;
62901   if( ALWAYS(u.bo.pCrsr!=0) ){
62902     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
62903     u.bo.r.nField = (u16)pOp->p3;
62904     u.bo.r.flags = 0;
62905     u.bo.r.aMem = &aMem[pOp->p2];
62906     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
62907     if( rc==SQLITE_OK && u.bo.res==0 ){
62908       rc = sqlite3BtreeDelete(u.bo.pCrsr);
62909     }
62910     assert( u.bo.pC->deferredMoveto==0 );
62911     u.bo.pC->cacheStatus = CACHE_STALE;
62912   }
62913   break;
62914 }
62915
62916 /* Opcode: IdxRowid P1 P2 * * *
62917 **
62918 ** Write into register P2 an integer which is the last entry in the record at
62919 ** the end of the index key pointed to by cursor P1.  This integer should be
62920 ** the rowid of the table entry to which this index entry points.
62921 **
62922 ** See also: Rowid, MakeRecord.
62923 */
62924 case OP_IdxRowid: {              /* out2-prerelease */
62925 #if 0  /* local variables moved into u.bp */
62926   BtCursor *pCrsr;
62927   VdbeCursor *pC;
62928   i64 rowid;
62929 #endif /* local variables moved into u.bp */
62930
62931   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62932   u.bp.pC = p->apCsr[pOp->p1];
62933   assert( u.bp.pC!=0 );
62934   u.bp.pCrsr = u.bp.pC->pCursor;
62935   pOut->flags = MEM_Null;
62936   if( ALWAYS(u.bp.pCrsr!=0) ){
62937     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
62938     if( NEVER(rc) ) goto abort_due_to_error;
62939     assert( u.bp.pC->deferredMoveto==0 );
62940     assert( u.bp.pC->isTable==0 );
62941     if( !u.bp.pC->nullRow ){
62942       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
62943       if( rc!=SQLITE_OK ){
62944         goto abort_due_to_error;
62945       }
62946       pOut->u.i = u.bp.rowid;
62947       pOut->flags = MEM_Int;
62948     }
62949   }
62950   break;
62951 }
62952
62953 /* Opcode: IdxGE P1 P2 P3 P4 P5
62954 **
62955 ** The P4 register values beginning with P3 form an unpacked index 
62956 ** key that omits the ROWID.  Compare this key value against the index 
62957 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62958 **
62959 ** If the P1 index entry is greater than or equal to the key value
62960 ** then jump to P2.  Otherwise fall through to the next instruction.
62961 **
62962 ** If P5 is non-zero then the key value is increased by an epsilon 
62963 ** prior to the comparison.  This make the opcode work like IdxGT except
62964 ** that if the key from register P3 is a prefix of the key in the cursor,
62965 ** the result is false whereas it would be true with IdxGT.
62966 */
62967 /* Opcode: IdxLT P1 P2 P3 * P5
62968 **
62969 ** The P4 register values beginning with P3 form an unpacked index 
62970 ** key that omits the ROWID.  Compare this key value against the index 
62971 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62972 **
62973 ** If the P1 index entry is less than the key value then jump to P2.
62974 ** Otherwise fall through to the next instruction.
62975 **
62976 ** If P5 is non-zero then the key value is increased by an epsilon prior 
62977 ** to the comparison.  This makes the opcode work like IdxLE.
62978 */
62979 case OP_IdxLT:          /* jump */
62980 case OP_IdxGE: {        /* jump */
62981 #if 0  /* local variables moved into u.bq */
62982   VdbeCursor *pC;
62983   int res;
62984   UnpackedRecord r;
62985 #endif /* local variables moved into u.bq */
62986
62987   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62988   u.bq.pC = p->apCsr[pOp->p1];
62989   assert( u.bq.pC!=0 );
62990   if( ALWAYS(u.bq.pC->pCursor!=0) ){
62991     assert( u.bq.pC->deferredMoveto==0 );
62992     assert( pOp->p5==0 || pOp->p5==1 );
62993     assert( pOp->p4type==P4_INT32 );
62994     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
62995     u.bq.r.nField = (u16)pOp->p4.i;
62996     if( pOp->p5 ){
62997       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
62998     }else{
62999       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
63000     }
63001     u.bq.r.aMem = &aMem[pOp->p3];
63002     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
63003     if( pOp->opcode==OP_IdxLT ){
63004       u.bq.res = -u.bq.res;
63005     }else{
63006       assert( pOp->opcode==OP_IdxGE );
63007       u.bq.res++;
63008     }
63009     if( u.bq.res>0 ){
63010       pc = pOp->p2 - 1 ;
63011     }
63012   }
63013   break;
63014 }
63015
63016 /* Opcode: Destroy P1 P2 P3 * *
63017 **
63018 ** Delete an entire database table or index whose root page in the database
63019 ** file is given by P1.
63020 **
63021 ** The table being destroyed is in the main database file if P3==0.  If
63022 ** P3==1 then the table to be clear is in the auxiliary database file
63023 ** that is used to store tables create using CREATE TEMPORARY TABLE.
63024 **
63025 ** If AUTOVACUUM is enabled then it is possible that another root page
63026 ** might be moved into the newly deleted root page in order to keep all
63027 ** root pages contiguous at the beginning of the database.  The former
63028 ** value of the root page that moved - its value before the move occurred -
63029 ** is stored in register P2.  If no page 
63030 ** movement was required (because the table being dropped was already 
63031 ** the last one in the database) then a zero is stored in register P2.
63032 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
63033 **
63034 ** See also: Clear
63035 */
63036 case OP_Destroy: {     /* out2-prerelease */
63037 #if 0  /* local variables moved into u.br */
63038   int iMoved;
63039   int iCnt;
63040   Vdbe *pVdbe;
63041   int iDb;
63042 #endif /* local variables moved into u.br */
63043 #ifndef SQLITE_OMIT_VIRTUALTABLE
63044   u.br.iCnt = 0;
63045   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
63046     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
63047       u.br.iCnt++;
63048     }
63049   }
63050 #else
63051   u.br.iCnt = db->activeVdbeCnt;
63052 #endif
63053   pOut->flags = MEM_Null;
63054   if( u.br.iCnt>1 ){
63055     rc = SQLITE_LOCKED;
63056     p->errorAction = OE_Abort;
63057   }else{
63058     u.br.iDb = pOp->p3;
63059     assert( u.br.iCnt==1 );
63060     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
63061     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
63062     pOut->flags = MEM_Int;
63063     pOut->u.i = u.br.iMoved;
63064 #ifndef SQLITE_OMIT_AUTOVACUUM
63065     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
63066       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
63067       resetSchemaOnFault = 1;
63068     }
63069 #endif
63070   }
63071   break;
63072 }
63073
63074 /* Opcode: Clear P1 P2 P3
63075 **
63076 ** Delete all contents of the database table or index whose root page
63077 ** in the database file is given by P1.  But, unlike Destroy, do not
63078 ** remove the table or index from the database file.
63079 **
63080 ** The table being clear is in the main database file if P2==0.  If
63081 ** P2==1 then the table to be clear is in the auxiliary database file
63082 ** that is used to store tables create using CREATE TEMPORARY TABLE.
63083 **
63084 ** If the P3 value is non-zero, then the table referred to must be an
63085 ** intkey table (an SQL table, not an index). In this case the row change 
63086 ** count is incremented by the number of rows in the table being cleared. 
63087 ** If P3 is greater than zero, then the value stored in register P3 is
63088 ** also incremented by the number of rows in the table being cleared.
63089 **
63090 ** See also: Destroy
63091 */
63092 case OP_Clear: {
63093 #if 0  /* local variables moved into u.bs */
63094   int nChange;
63095 #endif /* local variables moved into u.bs */
63096
63097   u.bs.nChange = 0;
63098   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
63099   rc = sqlite3BtreeClearTable(
63100       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
63101   );
63102   if( pOp->p3 ){
63103     p->nChange += u.bs.nChange;
63104     if( pOp->p3>0 ){
63105       aMem[pOp->p3].u.i += u.bs.nChange;
63106     }
63107   }
63108   break;
63109 }
63110
63111 /* Opcode: CreateTable P1 P2 * * *
63112 **
63113 ** Allocate a new table in the main database file if P1==0 or in the
63114 ** auxiliary database file if P1==1 or in an attached database if
63115 ** P1>1.  Write the root page number of the new table into
63116 ** register P2
63117 **
63118 ** The difference between a table and an index is this:  A table must
63119 ** have a 4-byte integer key and can have arbitrary data.  An index
63120 ** has an arbitrary key but no data.
63121 **
63122 ** See also: CreateIndex
63123 */
63124 /* Opcode: CreateIndex P1 P2 * * *
63125 **
63126 ** Allocate a new index in the main database file if P1==0 or in the
63127 ** auxiliary database file if P1==1 or in an attached database if
63128 ** P1>1.  Write the root page number of the new table into
63129 ** register P2.
63130 **
63131 ** See documentation on OP_CreateTable for additional information.
63132 */
63133 case OP_CreateIndex:            /* out2-prerelease */
63134 case OP_CreateTable: {          /* out2-prerelease */
63135 #if 0  /* local variables moved into u.bt */
63136   int pgno;
63137   int flags;
63138   Db *pDb;
63139 #endif /* local variables moved into u.bt */
63140
63141   u.bt.pgno = 0;
63142   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63143   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63144   u.bt.pDb = &db->aDb[pOp->p1];
63145   assert( u.bt.pDb->pBt!=0 );
63146   if( pOp->opcode==OP_CreateTable ){
63147     /* u.bt.flags = BTREE_INTKEY; */
63148     u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
63149   }else{
63150     u.bt.flags = BTREE_ZERODATA;
63151   }
63152   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
63153   pOut->u.i = u.bt.pgno;
63154   break;
63155 }
63156
63157 /* Opcode: ParseSchema P1 P2 * P4 *
63158 **
63159 ** Read and parse all entries from the SQLITE_MASTER table of database P1
63160 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
63161 ** the parsing if P2 is true.  If P2 is false, then this routine is a
63162 ** no-op if the schema is not currently loaded.  In other words, if P2
63163 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
63164 ** schema is already loaded into the symbol table.
63165 **
63166 ** This opcode invokes the parser to create a new virtual machine,
63167 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
63168 */
63169 case OP_ParseSchema: {
63170 #if 0  /* local variables moved into u.bu */
63171   int iDb;
63172   const char *zMaster;
63173   char *zSql;
63174   InitData initData;
63175 #endif /* local variables moved into u.bu */
63176
63177   u.bu.iDb = pOp->p1;
63178   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
63179
63180   /* If pOp->p2 is 0, then this opcode is being executed to read a
63181   ** single row, for example the row corresponding to a new index
63182   ** created by this VDBE, from the sqlite_master table. It only
63183   ** does this if the corresponding in-memory schema is currently
63184   ** loaded. Otherwise, the new index definition can be loaded along
63185   ** with the rest of the schema when it is required.
63186   **
63187   ** Although the mutex on the BtShared object that corresponds to
63188   ** database u.bu.iDb (the database containing the sqlite_master table
63189   ** read by this instruction) is currently held, it is necessary to
63190   ** obtain the mutexes on all attached databases before checking if
63191   ** the schema of u.bu.iDb is loaded. This is because, at the start of
63192   ** the sqlite3_exec() call below, SQLite will invoke
63193   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
63194   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
63195   ** this happens, then some other thread may delete the in-memory
63196   ** schema of database u.bu.iDb before the SQL statement runs. The schema
63197   ** will not be reloaded becuase the db->init.busy flag is set. This
63198   ** can result in a "no such table: sqlite_master" or "malformed
63199   ** database schema" error being returned to the user.
63200   */
63201   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
63202   sqlite3BtreeEnterAll(db);
63203   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
63204     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
63205     u.bu.initData.db = db;
63206     u.bu.initData.iDb = pOp->p1;
63207     u.bu.initData.pzErrMsg = &p->zErrMsg;
63208     u.bu.zSql = sqlite3MPrintf(db,
63209        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
63210        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
63211     if( u.bu.zSql==0 ){
63212       rc = SQLITE_NOMEM;
63213     }else{
63214       assert( db->init.busy==0 );
63215       db->init.busy = 1;
63216       u.bu.initData.rc = SQLITE_OK;
63217       assert( !db->mallocFailed );
63218       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
63219       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
63220       sqlite3DbFree(db, u.bu.zSql);
63221       db->init.busy = 0;
63222     }
63223   }
63224   sqlite3BtreeLeaveAll(db);
63225   if( rc==SQLITE_NOMEM ){
63226     goto no_mem;
63227   }
63228   break;
63229 }
63230
63231 #if !defined(SQLITE_OMIT_ANALYZE)
63232 /* Opcode: LoadAnalysis P1 * * * *
63233 **
63234 ** Read the sqlite_stat1 table for database P1 and load the content
63235 ** of that table into the internal index hash table.  This will cause
63236 ** the analysis to be used when preparing all subsequent queries.
63237 */
63238 case OP_LoadAnalysis: {
63239   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63240   rc = sqlite3AnalysisLoad(db, pOp->p1);
63241   break;  
63242 }
63243 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
63244
63245 /* Opcode: DropTable P1 * * P4 *
63246 **
63247 ** Remove the internal (in-memory) data structures that describe
63248 ** the table named P4 in database P1.  This is called after a table
63249 ** is dropped in order to keep the internal representation of the
63250 ** schema consistent with what is on disk.
63251 */
63252 case OP_DropTable: {
63253   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
63254   break;
63255 }
63256
63257 /* Opcode: DropIndex P1 * * P4 *
63258 **
63259 ** Remove the internal (in-memory) data structures that describe
63260 ** the index named P4 in database P1.  This is called after an index
63261 ** is dropped in order to keep the internal representation of the
63262 ** schema consistent with what is on disk.
63263 */
63264 case OP_DropIndex: {
63265   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
63266   break;
63267 }
63268
63269 /* Opcode: DropTrigger P1 * * P4 *
63270 **
63271 ** Remove the internal (in-memory) data structures that describe
63272 ** the trigger named P4 in database P1.  This is called after a trigger
63273 ** is dropped in order to keep the internal representation of the
63274 ** schema consistent with what is on disk.
63275 */
63276 case OP_DropTrigger: {
63277   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
63278   break;
63279 }
63280
63281
63282 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
63283 /* Opcode: IntegrityCk P1 P2 P3 * P5
63284 **
63285 ** Do an analysis of the currently open database.  Store in
63286 ** register P1 the text of an error message describing any problems.
63287 ** If no problems are found, store a NULL in register P1.
63288 **
63289 ** The register P3 contains the maximum number of allowed errors.
63290 ** At most reg(P3) errors will be reported.
63291 ** In other words, the analysis stops as soon as reg(P1) errors are 
63292 ** seen.  Reg(P1) is updated with the number of errors remaining.
63293 **
63294 ** The root page numbers of all tables in the database are integer
63295 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
63296 ** total.
63297 **
63298 ** If P5 is not zero, the check is done on the auxiliary database
63299 ** file, not the main database file.
63300 **
63301 ** This opcode is used to implement the integrity_check pragma.
63302 */
63303 case OP_IntegrityCk: {
63304 #if 0  /* local variables moved into u.bv */
63305   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
63306   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
63307   int j;          /* Loop counter */
63308   int nErr;       /* Number of errors reported */
63309   char *z;        /* Text of the error report */
63310   Mem *pnErr;     /* Register keeping track of errors remaining */
63311 #endif /* local variables moved into u.bv */
63312
63313   u.bv.nRoot = pOp->p2;
63314   assert( u.bv.nRoot>0 );
63315   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
63316   if( u.bv.aRoot==0 ) goto no_mem;
63317   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63318   u.bv.pnErr = &aMem[pOp->p3];
63319   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
63320   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
63321   pIn1 = &aMem[pOp->p1];
63322   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
63323     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
63324   }
63325   u.bv.aRoot[u.bv.j] = 0;
63326   assert( pOp->p5<db->nDb );
63327   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
63328   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
63329                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
63330   sqlite3DbFree(db, u.bv.aRoot);
63331   u.bv.pnErr->u.i -= u.bv.nErr;
63332   sqlite3VdbeMemSetNull(pIn1);
63333   if( u.bv.nErr==0 ){
63334     assert( u.bv.z==0 );
63335   }else if( u.bv.z==0 ){
63336     goto no_mem;
63337   }else{
63338     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
63339   }
63340   UPDATE_MAX_BLOBSIZE(pIn1);
63341   sqlite3VdbeChangeEncoding(pIn1, encoding);
63342   break;
63343 }
63344 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63345
63346 /* Opcode: RowSetAdd P1 P2 * * *
63347 **
63348 ** Insert the integer value held by register P2 into a boolean index
63349 ** held in register P1.
63350 **
63351 ** An assertion fails if P2 is not an integer.
63352 */
63353 case OP_RowSetAdd: {       /* in1, in2 */
63354   pIn1 = &aMem[pOp->p1];
63355   pIn2 = &aMem[pOp->p2];
63356   assert( (pIn2->flags & MEM_Int)!=0 );
63357   if( (pIn1->flags & MEM_RowSet)==0 ){
63358     sqlite3VdbeMemSetRowSet(pIn1);
63359     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63360   }
63361   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
63362   break;
63363 }
63364
63365 /* Opcode: RowSetRead P1 P2 P3 * *
63366 **
63367 ** Extract the smallest value from boolean index P1 and put that value into
63368 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
63369 ** unchanged and jump to instruction P2.
63370 */
63371 case OP_RowSetRead: {       /* jump, in1, out3 */
63372 #if 0  /* local variables moved into u.bw */
63373   i64 val;
63374 #endif /* local variables moved into u.bw */
63375   CHECK_FOR_INTERRUPT;
63376   pIn1 = &aMem[pOp->p1];
63377   if( (pIn1->flags & MEM_RowSet)==0
63378    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
63379   ){
63380     /* The boolean index is empty */
63381     sqlite3VdbeMemSetNull(pIn1);
63382     pc = pOp->p2 - 1;
63383   }else{
63384     /* A value was pulled from the index */
63385     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
63386   }
63387   break;
63388 }
63389
63390 /* Opcode: RowSetTest P1 P2 P3 P4
63391 **
63392 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
63393 ** contains a RowSet object and that RowSet object contains
63394 ** the value held in P3, jump to register P2. Otherwise, insert the
63395 ** integer in P3 into the RowSet and continue on to the
63396 ** next opcode.
63397 **
63398 ** The RowSet object is optimized for the case where successive sets
63399 ** of integers, where each set contains no duplicates. Each set
63400 ** of values is identified by a unique P4 value. The first set
63401 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
63402 ** non-negative.  For non-negative values of P4 only the lower 4
63403 ** bits are significant.
63404 **
63405 ** This allows optimizations: (a) when P4==0 there is no need to test
63406 ** the rowset object for P3, as it is guaranteed not to contain it,
63407 ** (b) when P4==-1 there is no need to insert the value, as it will
63408 ** never be tested for, and (c) when a value that is part of set X is
63409 ** inserted, there is no need to search to see if the same value was
63410 ** previously inserted as part of set X (only if it was previously
63411 ** inserted as part of some other set).
63412 */
63413 case OP_RowSetTest: {                     /* jump, in1, in3 */
63414 #if 0  /* local variables moved into u.bx */
63415   int iSet;
63416   int exists;
63417 #endif /* local variables moved into u.bx */
63418
63419   pIn1 = &aMem[pOp->p1];
63420   pIn3 = &aMem[pOp->p3];
63421   u.bx.iSet = pOp->p4.i;
63422   assert( pIn3->flags&MEM_Int );
63423
63424   /* If there is anything other than a rowset object in memory cell P1,
63425   ** delete it now and initialize P1 with an empty rowset
63426   */
63427   if( (pIn1->flags & MEM_RowSet)==0 ){
63428     sqlite3VdbeMemSetRowSet(pIn1);
63429     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63430   }
63431
63432   assert( pOp->p4type==P4_INT32 );
63433   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
63434   if( u.bx.iSet ){
63435     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
63436                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
63437                                pIn3->u.i);
63438     if( u.bx.exists ){
63439       pc = pOp->p2 - 1;
63440       break;
63441     }
63442   }
63443   if( u.bx.iSet>=0 ){
63444     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
63445   }
63446   break;
63447 }
63448
63449
63450 #ifndef SQLITE_OMIT_TRIGGER
63451
63452 /* Opcode: Program P1 P2 P3 P4 *
63453 **
63454 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
63455 **
63456 ** P1 contains the address of the memory cell that contains the first memory 
63457 ** cell in an array of values used as arguments to the sub-program. P2 
63458 ** contains the address to jump to if the sub-program throws an IGNORE 
63459 ** exception using the RAISE() function. Register P3 contains the address 
63460 ** of a memory cell in this (the parent) VM that is used to allocate the 
63461 ** memory required by the sub-vdbe at runtime.
63462 **
63463 ** P4 is a pointer to the VM containing the trigger program.
63464 */
63465 case OP_Program: {        /* jump */
63466 #if 0  /* local variables moved into u.by */
63467   int nMem;               /* Number of memory registers for sub-program */
63468   int nByte;              /* Bytes of runtime space required for sub-program */
63469   Mem *pRt;               /* Register to allocate runtime space */
63470   Mem *pMem;              /* Used to iterate through memory cells */
63471   Mem *pEnd;              /* Last memory cell in new array */
63472   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
63473   SubProgram *pProgram;   /* Sub-program to execute */
63474   void *t;                /* Token identifying trigger */
63475 #endif /* local variables moved into u.by */
63476
63477   u.by.pProgram = pOp->p4.pProgram;
63478   u.by.pRt = &aMem[pOp->p3];
63479   assert( u.by.pProgram->nOp>0 );
63480
63481   /* If the p5 flag is clear, then recursive invocation of triggers is
63482   ** disabled for backwards compatibility (p5 is set if this sub-program
63483   ** is really a trigger, not a foreign key action, and the flag set
63484   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
63485   **
63486   ** It is recursive invocation of triggers, at the SQL level, that is
63487   ** disabled. In some cases a single trigger may generate more than one
63488   ** SubProgram (if the trigger may be executed with more than one different
63489   ** ON CONFLICT algorithm). SubProgram structures associated with a
63490   ** single trigger all have the same value for the SubProgram.token
63491   ** variable.  */
63492   if( pOp->p5 ){
63493     u.by.t = u.by.pProgram->token;
63494     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
63495     if( u.by.pFrame ) break;
63496   }
63497
63498   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
63499     rc = SQLITE_ERROR;
63500     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
63501     break;
63502   }
63503
63504   /* Register u.by.pRt is used to store the memory required to save the state
63505   ** of the current program, and the memory required at runtime to execute
63506   ** the trigger program. If this trigger has been fired before, then u.by.pRt
63507   ** is already allocated. Otherwise, it must be initialized.  */
63508   if( (u.by.pRt->flags&MEM_Frame)==0 ){
63509     /* SubProgram.nMem is set to the number of memory cells used by the
63510     ** program stored in SubProgram.aOp. As well as these, one memory
63511     ** cell is required for each cursor used by the program. Set local
63512     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
63513     */
63514     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
63515     u.by.nByte = ROUND8(sizeof(VdbeFrame))
63516               + u.by.nMem * sizeof(Mem)
63517               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
63518     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
63519     if( !u.by.pFrame ){
63520       goto no_mem;
63521     }
63522     sqlite3VdbeMemRelease(u.by.pRt);
63523     u.by.pRt->flags = MEM_Frame;
63524     u.by.pRt->u.pFrame = u.by.pFrame;
63525
63526     u.by.pFrame->v = p;
63527     u.by.pFrame->nChildMem = u.by.nMem;
63528     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
63529     u.by.pFrame->pc = pc;
63530     u.by.pFrame->aMem = p->aMem;
63531     u.by.pFrame->nMem = p->nMem;
63532     u.by.pFrame->apCsr = p->apCsr;
63533     u.by.pFrame->nCursor = p->nCursor;
63534     u.by.pFrame->aOp = p->aOp;
63535     u.by.pFrame->nOp = p->nOp;
63536     u.by.pFrame->token = u.by.pProgram->token;
63537
63538     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
63539     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
63540       u.by.pMem->flags = MEM_Null;
63541       u.by.pMem->db = db;
63542     }
63543   }else{
63544     u.by.pFrame = u.by.pRt->u.pFrame;
63545     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
63546     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
63547     assert( pc==u.by.pFrame->pc );
63548   }
63549
63550   p->nFrame++;
63551   u.by.pFrame->pParent = p->pFrame;
63552   u.by.pFrame->lastRowid = db->lastRowid;
63553   u.by.pFrame->nChange = p->nChange;
63554   p->nChange = 0;
63555   p->pFrame = u.by.pFrame;
63556   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
63557   p->nMem = u.by.pFrame->nChildMem;
63558   p->nCursor = (u16)u.by.pFrame->nChildCsr;
63559   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
63560   p->aOp = aOp = u.by.pProgram->aOp;
63561   p->nOp = u.by.pProgram->nOp;
63562   pc = -1;
63563
63564   break;
63565 }
63566
63567 /* Opcode: Param P1 P2 * * *
63568 **
63569 ** This opcode is only ever present in sub-programs called via the 
63570 ** OP_Program instruction. Copy a value currently stored in a memory 
63571 ** cell of the calling (parent) frame to cell P2 in the current frames 
63572 ** address space. This is used by trigger programs to access the new.* 
63573 ** and old.* values.
63574 **
63575 ** The address of the cell in the parent frame is determined by adding
63576 ** the value of the P1 argument to the value of the P1 argument to the
63577 ** calling OP_Program instruction.
63578 */
63579 case OP_Param: {           /* out2-prerelease */
63580 #if 0  /* local variables moved into u.bz */
63581   VdbeFrame *pFrame;
63582   Mem *pIn;
63583 #endif /* local variables moved into u.bz */
63584   u.bz.pFrame = p->pFrame;
63585   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
63586   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
63587   break;
63588 }
63589
63590 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
63591
63592 #ifndef SQLITE_OMIT_FOREIGN_KEY
63593 /* Opcode: FkCounter P1 P2 * * *
63594 **
63595 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
63596 ** If P1 is non-zero, the database constraint counter is incremented 
63597 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
63598 ** statement counter is incremented (immediate foreign key constraints).
63599 */
63600 case OP_FkCounter: {
63601   if( pOp->p1 ){
63602     db->nDeferredCons += pOp->p2;
63603   }else{
63604     p->nFkConstraint += pOp->p2;
63605   }
63606   break;
63607 }
63608
63609 /* Opcode: FkIfZero P1 P2 * * *
63610 **
63611 ** This opcode tests if a foreign key constraint-counter is currently zero.
63612 ** If so, jump to instruction P2. Otherwise, fall through to the next 
63613 ** instruction.
63614 **
63615 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
63616 ** is zero (the one that counts deferred constraint violations). If P1 is
63617 ** zero, the jump is taken if the statement constraint-counter is zero
63618 ** (immediate foreign key constraint violations).
63619 */
63620 case OP_FkIfZero: {         /* jump */
63621   if( pOp->p1 ){
63622     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
63623   }else{
63624     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
63625   }
63626   break;
63627 }
63628 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
63629
63630 #ifndef SQLITE_OMIT_AUTOINCREMENT
63631 /* Opcode: MemMax P1 P2 * * *
63632 **
63633 ** P1 is a register in the root frame of this VM (the root frame is
63634 ** different from the current frame if this instruction is being executed
63635 ** within a sub-program). Set the value of register P1 to the maximum of 
63636 ** its current value and the value in register P2.
63637 **
63638 ** This instruction throws an error if the memory cell is not initially
63639 ** an integer.
63640 */
63641 case OP_MemMax: {        /* in2 */
63642 #if 0  /* local variables moved into u.ca */
63643   Mem *pIn1;
63644   VdbeFrame *pFrame;
63645 #endif /* local variables moved into u.ca */
63646   if( p->pFrame ){
63647     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
63648     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
63649   }else{
63650     u.ca.pIn1 = &aMem[pOp->p1];
63651   }
63652   sqlite3VdbeMemIntegerify(u.ca.pIn1);
63653   pIn2 = &aMem[pOp->p2];
63654   sqlite3VdbeMemIntegerify(pIn2);
63655   if( u.ca.pIn1->u.i<pIn2->u.i){
63656     u.ca.pIn1->u.i = pIn2->u.i;
63657   }
63658   break;
63659 }
63660 #endif /* SQLITE_OMIT_AUTOINCREMENT */
63661
63662 /* Opcode: IfPos P1 P2 * * *
63663 **
63664 ** If the value of register P1 is 1 or greater, jump to P2.
63665 **
63666 ** It is illegal to use this instruction on a register that does
63667 ** not contain an integer.  An assertion fault will result if you try.
63668 */
63669 case OP_IfPos: {        /* jump, in1 */
63670   pIn1 = &aMem[pOp->p1];
63671   assert( pIn1->flags&MEM_Int );
63672   if( pIn1->u.i>0 ){
63673      pc = pOp->p2 - 1;
63674   }
63675   break;
63676 }
63677
63678 /* Opcode: IfNeg P1 P2 * * *
63679 **
63680 ** If the value of register P1 is less than zero, jump to P2. 
63681 **
63682 ** It is illegal to use this instruction on a register that does
63683 ** not contain an integer.  An assertion fault will result if you try.
63684 */
63685 case OP_IfNeg: {        /* jump, in1 */
63686   pIn1 = &aMem[pOp->p1];
63687   assert( pIn1->flags&MEM_Int );
63688   if( pIn1->u.i<0 ){
63689      pc = pOp->p2 - 1;
63690   }
63691   break;
63692 }
63693
63694 /* Opcode: IfZero P1 P2 P3 * *
63695 **
63696 ** The register P1 must contain an integer.  Add literal P3 to the
63697 ** value in register P1.  If the result is exactly 0, jump to P2. 
63698 **
63699 ** It is illegal to use this instruction on a register that does
63700 ** not contain an integer.  An assertion fault will result if you try.
63701 */
63702 case OP_IfZero: {        /* jump, in1 */
63703   pIn1 = &aMem[pOp->p1];
63704   assert( pIn1->flags&MEM_Int );
63705   pIn1->u.i += pOp->p3;
63706   if( pIn1->u.i==0 ){
63707      pc = pOp->p2 - 1;
63708   }
63709   break;
63710 }
63711
63712 /* Opcode: AggStep * P2 P3 P4 P5
63713 **
63714 ** Execute the step function for an aggregate.  The
63715 ** function has P5 arguments.   P4 is a pointer to the FuncDef
63716 ** structure that specifies the function.  Use register
63717 ** P3 as the accumulator.
63718 **
63719 ** The P5 arguments are taken from register P2 and its
63720 ** successors.
63721 */
63722 case OP_AggStep: {
63723 #if 0  /* local variables moved into u.cb */
63724   int n;
63725   int i;
63726   Mem *pMem;
63727   Mem *pRec;
63728   sqlite3_context ctx;
63729   sqlite3_value **apVal;
63730 #endif /* local variables moved into u.cb */
63731
63732   u.cb.n = pOp->p5;
63733   assert( u.cb.n>=0 );
63734   u.cb.pRec = &aMem[pOp->p2];
63735   u.cb.apVal = p->apArg;
63736   assert( u.cb.apVal || u.cb.n==0 );
63737   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
63738     u.cb.apVal[u.cb.i] = u.cb.pRec;
63739     sqlite3VdbeMemStoreType(u.cb.pRec);
63740   }
63741   u.cb.ctx.pFunc = pOp->p4.pFunc;
63742   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63743   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
63744   u.cb.pMem->n++;
63745   u.cb.ctx.s.flags = MEM_Null;
63746   u.cb.ctx.s.z = 0;
63747   u.cb.ctx.s.zMalloc = 0;
63748   u.cb.ctx.s.xDel = 0;
63749   u.cb.ctx.s.db = db;
63750   u.cb.ctx.isError = 0;
63751   u.cb.ctx.pColl = 0;
63752   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63753     assert( pOp>p->aOp );
63754     assert( pOp[-1].p4type==P4_COLLSEQ );
63755     assert( pOp[-1].opcode==OP_CollSeq );
63756     u.cb.ctx.pColl = pOp[-1].p4.pColl;
63757   }
63758   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
63759   if( u.cb.ctx.isError ){
63760     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
63761     rc = u.cb.ctx.isError;
63762   }
63763   sqlite3VdbeMemRelease(&u.cb.ctx.s);
63764   break;
63765 }
63766
63767 /* Opcode: AggFinal P1 P2 * P4 *
63768 **
63769 ** Execute the finalizer function for an aggregate.  P1 is
63770 ** the memory location that is the accumulator for the aggregate.
63771 **
63772 ** P2 is the number of arguments that the step function takes and
63773 ** P4 is a pointer to the FuncDef for this function.  The P2
63774 ** argument is not used by this opcode.  It is only there to disambiguate
63775 ** functions that can take varying numbers of arguments.  The
63776 ** P4 argument is only needed for the degenerate case where
63777 ** the step function was not previously called.
63778 */
63779 case OP_AggFinal: {
63780 #if 0  /* local variables moved into u.cc */
63781   Mem *pMem;
63782 #endif /* local variables moved into u.cc */
63783   assert( pOp->p1>0 && pOp->p1<=p->nMem );
63784   u.cc.pMem = &aMem[pOp->p1];
63785   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
63786   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
63787   if( rc ){
63788     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
63789   }
63790   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
63791   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
63792   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
63793     goto too_big;
63794   }
63795   break;
63796 }
63797
63798 #ifndef SQLITE_OMIT_WAL
63799 /* Opcode: Checkpoint P1 * * * *
63800 **
63801 ** Checkpoint database P1. This is a no-op if P1 is not currently in
63802 ** WAL mode.
63803 */
63804 case OP_Checkpoint: {
63805   rc = sqlite3Checkpoint(db, pOp->p1);
63806   break;
63807 };  
63808 #endif
63809
63810 #ifndef SQLITE_OMIT_PRAGMA
63811 /* Opcode: JournalMode P1 P2 P3 * P5
63812 **
63813 ** Change the journal mode of database P1 to P3. P3 must be one of the
63814 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
63815 ** modes (delete, truncate, persist, off and memory), this is a simple
63816 ** operation. No IO is required.
63817 **
63818 ** If changing into or out of WAL mode the procedure is more complicated.
63819 **
63820 ** Write a string containing the final journal-mode to register P2.
63821 */
63822 case OP_JournalMode: {    /* out2-prerelease */
63823 #if 0  /* local variables moved into u.cd */
63824   Btree *pBt;                     /* Btree to change journal mode of */
63825   Pager *pPager;                  /* Pager associated with pBt */
63826   int eNew;                       /* New journal mode */
63827   int eOld;                       /* The old journal mode */
63828   const char *zFilename;          /* Name of database file for pPager */
63829 #endif /* local variables moved into u.cd */
63830
63831   u.cd.eNew = pOp->p3;
63832   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
63833        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
63834        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
63835        || u.cd.eNew==PAGER_JOURNALMODE_OFF
63836        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
63837        || u.cd.eNew==PAGER_JOURNALMODE_WAL
63838        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
63839   );
63840   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63841
63842   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
63843   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
63844   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
63845   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
63846   ** is not called when the statement is prepared because it requires the
63847   ** iDb index of the database as a parameter, and the database has not
63848   ** yet been attached so that index is unavailable.  We have to wait
63849   ** until runtime (now) to get the mutex on the newly attached database.
63850   ** No other mutexes are required by the ATTACH command so this is safe
63851   ** to do.
63852   */
63853   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
63854   if( p->aMutex.nMutex==0 ){
63855     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
63856     ** database. */
63857     sqlite3VdbeUsesBtree(p, pOp->p1);
63858     sqlite3VdbeMutexArrayEnter(p);
63859   }
63860
63861   u.cd.pBt = db->aDb[pOp->p1].pBt;
63862   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
63863   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
63864   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
63865   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
63866
63867 #ifndef SQLITE_OMIT_WAL
63868   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
63869
63870   /* Do not allow a transition to journal_mode=WAL for a database
63871   ** in temporary storage or if the VFS does not support shared memory
63872   */
63873   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
63874    && (u.cd.zFilename[0]==0                         /* Temp file */
63875        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
63876   ){
63877     u.cd.eNew = u.cd.eOld;
63878   }
63879
63880   if( (u.cd.eNew!=u.cd.eOld)
63881    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
63882   ){
63883     if( !db->autoCommit || db->activeVdbeCnt>1 ){
63884       rc = SQLITE_ERROR;
63885       sqlite3SetString(&p->zErrMsg, db,
63886           "cannot change %s wal mode from within a transaction",
63887           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
63888       );
63889       break;
63890     }else{
63891
63892       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
63893         /* If leaving WAL mode, close the log file. If successful, the call
63894         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
63895         ** file. An EXCLUSIVE lock may still be held on the database file
63896         ** after a successful return.
63897         */
63898         rc = sqlite3PagerCloseWal(u.cd.pPager);
63899         if( rc==SQLITE_OK ){
63900           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63901         }
63902       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
63903         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
63904         ** as an intermediate */
63905         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
63906       }
63907
63908       /* Open a transaction on the database file. Regardless of the journal
63909       ** mode, this transaction always uses a rollback journal.
63910       */
63911       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
63912       if( rc==SQLITE_OK ){
63913         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
63914       }
63915     }
63916   }
63917 #endif /* ifndef SQLITE_OMIT_WAL */
63918
63919   if( rc ){
63920     u.cd.eNew = u.cd.eOld;
63921   }
63922   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63923
63924   pOut = &aMem[pOp->p2];
63925   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63926   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
63927   pOut->n = sqlite3Strlen30(pOut->z);
63928   pOut->enc = SQLITE_UTF8;
63929   sqlite3VdbeChangeEncoding(pOut, encoding);
63930   break;
63931 };
63932 #endif /* SQLITE_OMIT_PRAGMA */
63933
63934 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
63935 /* Opcode: Vacuum * * * * *
63936 **
63937 ** Vacuum the entire database.  This opcode will cause other virtual
63938 ** machines to be created and run.  It may not be called from within
63939 ** a transaction.
63940 */
63941 case OP_Vacuum: {
63942   rc = sqlite3RunVacuum(&p->zErrMsg, db);
63943   break;
63944 }
63945 #endif
63946
63947 #if !defined(SQLITE_OMIT_AUTOVACUUM)
63948 /* Opcode: IncrVacuum P1 P2 * * *
63949 **
63950 ** Perform a single step of the incremental vacuum procedure on
63951 ** the P1 database. If the vacuum has finished, jump to instruction
63952 ** P2. Otherwise, fall through to the next instruction.
63953 */
63954 case OP_IncrVacuum: {        /* jump */
63955 #if 0  /* local variables moved into u.ce */
63956   Btree *pBt;
63957 #endif /* local variables moved into u.ce */
63958
63959   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63960   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63961   u.ce.pBt = db->aDb[pOp->p1].pBt;
63962   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
63963   if( rc==SQLITE_DONE ){
63964     pc = pOp->p2 - 1;
63965     rc = SQLITE_OK;
63966   }
63967   break;
63968 }
63969 #endif
63970
63971 /* Opcode: Expire P1 * * * *
63972 **
63973 ** Cause precompiled statements to become expired. An expired statement
63974 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
63975 ** (via sqlite3_step()).
63976 ** 
63977 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
63978 ** then only the currently executing statement is affected. 
63979 */
63980 case OP_Expire: {
63981   if( !pOp->p1 ){
63982     sqlite3ExpirePreparedStatements(db);
63983   }else{
63984     p->expired = 1;
63985   }
63986   break;
63987 }
63988
63989 #ifndef SQLITE_OMIT_SHARED_CACHE
63990 /* Opcode: TableLock P1 P2 P3 P4 *
63991 **
63992 ** Obtain a lock on a particular table. This instruction is only used when
63993 ** the shared-cache feature is enabled. 
63994 **
63995 ** P1 is the index of the database in sqlite3.aDb[] of the database
63996 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
63997 ** a write lock if P3==1.
63998 **
63999 ** P2 contains the root-page of the table to lock.
64000 **
64001 ** P4 contains a pointer to the name of the table being locked. This is only
64002 ** used to generate an error message if the lock cannot be obtained.
64003 */
64004 case OP_TableLock: {
64005   u8 isWriteLock = (u8)pOp->p3;
64006   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
64007     int p1 = pOp->p1; 
64008     assert( p1>=0 && p1<db->nDb );
64009     assert( (p->btreeMask & (1<<p1))!=0 );
64010     assert( isWriteLock==0 || isWriteLock==1 );
64011     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
64012     if( (rc&0xFF)==SQLITE_LOCKED ){
64013       const char *z = pOp->p4.z;
64014       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
64015     }
64016   }
64017   break;
64018 }
64019 #endif /* SQLITE_OMIT_SHARED_CACHE */
64020
64021 #ifndef SQLITE_OMIT_VIRTUALTABLE
64022 /* Opcode: VBegin * * * P4 *
64023 **
64024 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
64025 ** xBegin method for that table.
64026 **
64027 ** Also, whether or not P4 is set, check that this is not being called from
64028 ** within a callback to a virtual table xSync() method. If it is, the error
64029 ** code will be set to SQLITE_LOCKED.
64030 */
64031 case OP_VBegin: {
64032 #if 0  /* local variables moved into u.cf */
64033   VTable *pVTab;
64034 #endif /* local variables moved into u.cf */
64035   u.cf.pVTab = pOp->p4.pVtab;
64036   rc = sqlite3VtabBegin(db, u.cf.pVTab);
64037   if( u.cf.pVTab ){
64038     sqlite3DbFree(db, p->zErrMsg);
64039     p->zErrMsg = u.cf.pVTab->pVtab->zErrMsg;
64040     u.cf.pVTab->pVtab->zErrMsg = 0;
64041   }
64042   break;
64043 }
64044 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64045
64046 #ifndef SQLITE_OMIT_VIRTUALTABLE
64047 /* Opcode: VCreate P1 * * P4 *
64048 **
64049 ** P4 is the name of a virtual table in database P1. Call the xCreate method
64050 ** for that table.
64051 */
64052 case OP_VCreate: {
64053   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
64054   break;
64055 }
64056 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64057
64058 #ifndef SQLITE_OMIT_VIRTUALTABLE
64059 /* Opcode: VDestroy P1 * * P4 *
64060 **
64061 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
64062 ** of that table.
64063 */
64064 case OP_VDestroy: {
64065   p->inVtabMethod = 2;
64066   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
64067   p->inVtabMethod = 0;
64068   break;
64069 }
64070 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64071
64072 #ifndef SQLITE_OMIT_VIRTUALTABLE
64073 /* Opcode: VOpen P1 * * P4 *
64074 **
64075 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64076 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
64077 ** table and stores that cursor in P1.
64078 */
64079 case OP_VOpen: {
64080 #if 0  /* local variables moved into u.cg */
64081   VdbeCursor *pCur;
64082   sqlite3_vtab_cursor *pVtabCursor;
64083   sqlite3_vtab *pVtab;
64084   sqlite3_module *pModule;
64085 #endif /* local variables moved into u.cg */
64086
64087   u.cg.pCur = 0;
64088   u.cg.pVtabCursor = 0;
64089   u.cg.pVtab = pOp->p4.pVtab->pVtab;
64090   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
64091   assert(u.cg.pVtab && u.cg.pModule);
64092   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
64093   sqlite3DbFree(db, p->zErrMsg);
64094   p->zErrMsg = u.cg.pVtab->zErrMsg;
64095   u.cg.pVtab->zErrMsg = 0;
64096   if( SQLITE_OK==rc ){
64097     /* Initialize sqlite3_vtab_cursor base class */
64098     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
64099
64100     /* Initialise vdbe cursor object */
64101     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
64102     if( u.cg.pCur ){
64103       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
64104       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
64105     }else{
64106       db->mallocFailed = 1;
64107       u.cg.pModule->xClose(u.cg.pVtabCursor);
64108     }
64109   }
64110   break;
64111 }
64112 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64113
64114 #ifndef SQLITE_OMIT_VIRTUALTABLE
64115 /* Opcode: VFilter P1 P2 P3 P4 *
64116 **
64117 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
64118 ** the filtered result set is empty.
64119 **
64120 ** P4 is either NULL or a string that was generated by the xBestIndex
64121 ** method of the module.  The interpretation of the P4 string is left
64122 ** to the module implementation.
64123 **
64124 ** This opcode invokes the xFilter method on the virtual table specified
64125 ** by P1.  The integer query plan parameter to xFilter is stored in register
64126 ** P3. Register P3+1 stores the argc parameter to be passed to the
64127 ** xFilter method. Registers P3+2..P3+1+argc are the argc
64128 ** additional parameters which are passed to
64129 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
64130 **
64131 ** A jump is made to P2 if the result set after filtering would be empty.
64132 */
64133 case OP_VFilter: {   /* jump */
64134 #if 0  /* local variables moved into u.ch */
64135   int nArg;
64136   int iQuery;
64137   const sqlite3_module *pModule;
64138   Mem *pQuery;
64139   Mem *pArgc;
64140   sqlite3_vtab_cursor *pVtabCursor;
64141   sqlite3_vtab *pVtab;
64142   VdbeCursor *pCur;
64143   int res;
64144   int i;
64145   Mem **apArg;
64146 #endif /* local variables moved into u.ch */
64147
64148   u.ch.pQuery = &aMem[pOp->p3];
64149   u.ch.pArgc = &u.ch.pQuery[1];
64150   u.ch.pCur = p->apCsr[pOp->p1];
64151   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
64152   assert( u.ch.pCur->pVtabCursor );
64153   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
64154   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
64155   u.ch.pModule = u.ch.pVtab->pModule;
64156
64157   /* Grab the index number and argc parameters */
64158   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
64159   u.ch.nArg = (int)u.ch.pArgc->u.i;
64160   u.ch.iQuery = (int)u.ch.pQuery->u.i;
64161
64162   /* Invoke the xFilter method */
64163   {
64164     u.ch.res = 0;
64165     u.ch.apArg = p->apArg;
64166     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
64167       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
64168       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
64169     }
64170
64171     p->inVtabMethod = 1;
64172     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
64173     p->inVtabMethod = 0;
64174     sqlite3DbFree(db, p->zErrMsg);
64175     p->zErrMsg = u.ch.pVtab->zErrMsg;
64176     u.ch.pVtab->zErrMsg = 0;
64177     if( rc==SQLITE_OK ){
64178       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
64179     }
64180
64181     if( u.ch.res ){
64182       pc = pOp->p2 - 1;
64183     }
64184   }
64185   u.ch.pCur->nullRow = 0;
64186
64187   break;
64188 }
64189 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64190
64191 #ifndef SQLITE_OMIT_VIRTUALTABLE
64192 /* Opcode: VColumn P1 P2 P3 * *
64193 **
64194 ** Store the value of the P2-th column of
64195 ** the row of the virtual-table that the 
64196 ** P1 cursor is pointing to into register P3.
64197 */
64198 case OP_VColumn: {
64199 #if 0  /* local variables moved into u.ci */
64200   sqlite3_vtab *pVtab;
64201   const sqlite3_module *pModule;
64202   Mem *pDest;
64203   sqlite3_context sContext;
64204 #endif /* local variables moved into u.ci */
64205
64206   VdbeCursor *pCur = p->apCsr[pOp->p1];
64207   assert( pCur->pVtabCursor );
64208   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64209   u.ci.pDest = &aMem[pOp->p3];
64210   if( pCur->nullRow ){
64211     sqlite3VdbeMemSetNull(u.ci.pDest);
64212     break;
64213   }
64214   u.ci.pVtab = pCur->pVtabCursor->pVtab;
64215   u.ci.pModule = u.ci.pVtab->pModule;
64216   assert( u.ci.pModule->xColumn );
64217   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
64218
64219   /* The output cell may already have a buffer allocated. Move
64220   ** the current contents to u.ci.sContext.s so in case the user-function
64221   ** can use the already allocated buffer instead of allocating a
64222   ** new one.
64223   */
64224   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
64225   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
64226
64227   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
64228   sqlite3DbFree(db, p->zErrMsg);
64229   p->zErrMsg = u.ci.pVtab->zErrMsg;
64230   u.ci.pVtab->zErrMsg = 0;
64231   if( u.ci.sContext.isError ){
64232     rc = u.ci.sContext.isError;
64233   }
64234
64235   /* Copy the result of the function to the P3 register. We
64236   ** do this regardless of whether or not an error occurred to ensure any
64237   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
64238   */
64239   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
64240   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
64241   REGISTER_TRACE(pOp->p3, u.ci.pDest);
64242   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
64243
64244   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
64245     goto too_big;
64246   }
64247   break;
64248 }
64249 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64250
64251 #ifndef SQLITE_OMIT_VIRTUALTABLE
64252 /* Opcode: VNext P1 P2 * * *
64253 **
64254 ** Advance virtual table P1 to the next row in its result set and
64255 ** jump to instruction P2.  Or, if the virtual table has reached
64256 ** the end of its result set, then fall through to the next instruction.
64257 */
64258 case OP_VNext: {   /* jump */
64259 #if 0  /* local variables moved into u.cj */
64260   sqlite3_vtab *pVtab;
64261   const sqlite3_module *pModule;
64262   int res;
64263   VdbeCursor *pCur;
64264 #endif /* local variables moved into u.cj */
64265
64266   u.cj.res = 0;
64267   u.cj.pCur = p->apCsr[pOp->p1];
64268   assert( u.cj.pCur->pVtabCursor );
64269   if( u.cj.pCur->nullRow ){
64270     break;
64271   }
64272   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
64273   u.cj.pModule = u.cj.pVtab->pModule;
64274   assert( u.cj.pModule->xNext );
64275
64276   /* Invoke the xNext() method of the module. There is no way for the
64277   ** underlying implementation to return an error if one occurs during
64278   ** xNext(). Instead, if an error occurs, true is returned (indicating that
64279   ** data is available) and the error code returned when xColumn or
64280   ** some other method is next invoked on the save virtual table cursor.
64281   */
64282   p->inVtabMethod = 1;
64283   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
64284   p->inVtabMethod = 0;
64285   sqlite3DbFree(db, p->zErrMsg);
64286   p->zErrMsg = u.cj.pVtab->zErrMsg;
64287   u.cj.pVtab->zErrMsg = 0;
64288   if( rc==SQLITE_OK ){
64289     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
64290   }
64291
64292   if( !u.cj.res ){
64293     /* If there is data, jump to P2 */
64294     pc = pOp->p2 - 1;
64295   }
64296   break;
64297 }
64298 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64299
64300 #ifndef SQLITE_OMIT_VIRTUALTABLE
64301 /* Opcode: VRename P1 * * P4 *
64302 **
64303 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64304 ** This opcode invokes the corresponding xRename method. The value
64305 ** in register P1 is passed as the zName argument to the xRename method.
64306 */
64307 case OP_VRename: {
64308 #if 0  /* local variables moved into u.ck */
64309   sqlite3_vtab *pVtab;
64310   Mem *pName;
64311 #endif /* local variables moved into u.ck */
64312
64313   u.ck.pVtab = pOp->p4.pVtab->pVtab;
64314   u.ck.pName = &aMem[pOp->p1];
64315   assert( u.ck.pVtab->pModule->xRename );
64316   REGISTER_TRACE(pOp->p1, u.ck.pName);
64317   assert( u.ck.pName->flags & MEM_Str );
64318   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
64319   sqlite3DbFree(db, p->zErrMsg);
64320   p->zErrMsg = u.ck.pVtab->zErrMsg;
64321   u.ck.pVtab->zErrMsg = 0;
64322
64323   break;
64324 }
64325 #endif
64326
64327 #ifndef SQLITE_OMIT_VIRTUALTABLE
64328 /* Opcode: VUpdate P1 P2 P3 P4 *
64329 **
64330 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64331 ** This opcode invokes the corresponding xUpdate method. P2 values
64332 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
64333 ** invocation. The value in register (P3+P2-1) corresponds to the 
64334 ** p2th element of the argv array passed to xUpdate.
64335 **
64336 ** The xUpdate method will do a DELETE or an INSERT or both.
64337 ** The argv[0] element (which corresponds to memory cell P3)
64338 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
64339 ** deletion occurs.  The argv[1] element is the rowid of the new 
64340 ** row.  This can be NULL to have the virtual table select the new 
64341 ** rowid for itself.  The subsequent elements in the array are 
64342 ** the values of columns in the new row.
64343 **
64344 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
64345 ** a row to delete.
64346 **
64347 ** P1 is a boolean flag. If it is set to true and the xUpdate call
64348 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
64349 ** is set to the value of the rowid for the row just inserted.
64350 */
64351 case OP_VUpdate: {
64352 #if 0  /* local variables moved into u.cl */
64353   sqlite3_vtab *pVtab;
64354   sqlite3_module *pModule;
64355   int nArg;
64356   int i;
64357   sqlite_int64 rowid;
64358   Mem **apArg;
64359   Mem *pX;
64360 #endif /* local variables moved into u.cl */
64361
64362   u.cl.pVtab = pOp->p4.pVtab->pVtab;
64363   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
64364   u.cl.nArg = pOp->p2;
64365   assert( pOp->p4type==P4_VTAB );
64366   if( ALWAYS(u.cl.pModule->xUpdate) ){
64367     u.cl.apArg = p->apArg;
64368     u.cl.pX = &aMem[pOp->p3];
64369     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
64370       sqlite3VdbeMemStoreType(u.cl.pX);
64371       u.cl.apArg[u.cl.i] = u.cl.pX;
64372       u.cl.pX++;
64373     }
64374     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
64375     sqlite3DbFree(db, p->zErrMsg);
64376     p->zErrMsg = u.cl.pVtab->zErrMsg;
64377     u.cl.pVtab->zErrMsg = 0;
64378     if( rc==SQLITE_OK && pOp->p1 ){
64379       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
64380       db->lastRowid = u.cl.rowid;
64381     }
64382     p->nChange++;
64383   }
64384   break;
64385 }
64386 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64387
64388 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
64389 /* Opcode: Pagecount P1 P2 * * *
64390 **
64391 ** Write the current number of pages in database P1 to memory cell P2.
64392 */
64393 case OP_Pagecount: {            /* out2-prerelease */
64394   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
64395   break;
64396 }
64397 #endif
64398
64399 #ifndef SQLITE_OMIT_TRACE
64400 /* Opcode: Trace * * * P4 *
64401 **
64402 ** If tracing is enabled (by the sqlite3_trace()) interface, then
64403 ** the UTF-8 string contained in P4 is emitted on the trace callback.
64404 */
64405 case OP_Trace: {
64406 #if 0  /* local variables moved into u.cm */
64407   char *zTrace;
64408 #endif /* local variables moved into u.cm */
64409
64410   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
64411   if( u.cm.zTrace ){
64412     if( db->xTrace ){
64413       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
64414       db->xTrace(db->pTraceArg, z);
64415       sqlite3DbFree(db, z);
64416     }
64417 #ifdef SQLITE_DEBUG
64418     if( (db->flags & SQLITE_SqlTrace)!=0 ){
64419       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
64420     }
64421 #endif /* SQLITE_DEBUG */
64422   }
64423   break;
64424 }
64425 #endif
64426
64427
64428 /* Opcode: Noop * * * * *
64429 **
64430 ** Do nothing.  This instruction is often useful as a jump
64431 ** destination.
64432 */
64433 /*
64434 ** The magic Explain opcode are only inserted when explain==2 (which
64435 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
64436 ** This opcode records information from the optimizer.  It is the
64437 ** the same as a no-op.  This opcodesnever appears in a real VM program.
64438 */
64439 default: {          /* This is really OP_Noop and OP_Explain */
64440   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
64441   break;
64442 }
64443
64444 /*****************************************************************************
64445 ** The cases of the switch statement above this line should all be indented
64446 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
64447 ** readability.  From this point on down, the normal indentation rules are
64448 ** restored.
64449 *****************************************************************************/
64450     }
64451
64452 #ifdef VDBE_PROFILE
64453     {
64454       u64 elapsed = sqlite3Hwtime() - start;
64455       pOp->cycles += elapsed;
64456       pOp->cnt++;
64457 #if 0
64458         fprintf(stdout, "%10llu ", elapsed);
64459         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
64460 #endif
64461     }
64462 #endif
64463
64464     /* The following code adds nothing to the actual functionality
64465     ** of the program.  It is only here for testing and debugging.
64466     ** On the other hand, it does burn CPU cycles every time through
64467     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
64468     */
64469 #ifndef NDEBUG
64470     assert( pc>=-1 && pc<p->nOp );
64471
64472 #ifdef SQLITE_DEBUG
64473     if( p->trace ){
64474       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
64475       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
64476         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
64477       }
64478       if( pOp->opflags & OPFLG_OUT3 ){
64479         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
64480       }
64481     }
64482 #endif  /* SQLITE_DEBUG */
64483 #endif  /* NDEBUG */
64484   }  /* The end of the for(;;) loop the loops through opcodes */
64485
64486   /* If we reach this point, it means that execution is finished with
64487   ** an error of some kind.
64488   */
64489 vdbe_error_halt:
64490   assert( rc );
64491   p->rc = rc;
64492   testcase( sqlite3GlobalConfig.xLog!=0 );
64493   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
64494                    pc, p->zSql, p->zErrMsg);
64495   sqlite3VdbeHalt(p);
64496   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
64497   rc = SQLITE_ERROR;
64498   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
64499
64500   /* This is the only way out of this procedure.  We have to
64501   ** release the mutexes on btrees that were acquired at the
64502   ** top. */
64503 vdbe_return:
64504   sqlite3BtreeMutexArrayLeave(&p->aMutex);
64505   return rc;
64506
64507   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
64508   ** is encountered.
64509   */
64510 too_big:
64511   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
64512   rc = SQLITE_TOOBIG;
64513   goto vdbe_error_halt;
64514
64515   /* Jump to here if a malloc() fails.
64516   */
64517 no_mem:
64518   db->mallocFailed = 1;
64519   sqlite3SetString(&p->zErrMsg, db, "out of memory");
64520   rc = SQLITE_NOMEM;
64521   goto vdbe_error_halt;
64522
64523   /* Jump to here for any other kind of fatal error.  The "rc" variable
64524   ** should hold the error number.
64525   */
64526 abort_due_to_error:
64527   assert( p->zErrMsg==0 );
64528   if( db->mallocFailed ) rc = SQLITE_NOMEM;
64529   if( rc!=SQLITE_IOERR_NOMEM ){
64530     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64531   }
64532   goto vdbe_error_halt;
64533
64534   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
64535   ** flag.
64536   */
64537 abort_due_to_interrupt:
64538   assert( db->u1.isInterrupted );
64539   rc = SQLITE_INTERRUPT;
64540   p->rc = rc;
64541   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64542   goto vdbe_error_halt;
64543 }
64544
64545 /************** End of vdbe.c ************************************************/
64546 /************** Begin file vdbeblob.c ****************************************/
64547 /*
64548 ** 2007 May 1
64549 **
64550 ** The author disclaims copyright to this source code.  In place of
64551 ** a legal notice, here is a blessing:
64552 **
64553 **    May you do good and not evil.
64554 **    May you find forgiveness for yourself and forgive others.
64555 **    May you share freely, never taking more than you give.
64556 **
64557 *************************************************************************
64558 **
64559 ** This file contains code used to implement incremental BLOB I/O.
64560 */
64561
64562
64563 #ifndef SQLITE_OMIT_INCRBLOB
64564
64565 /*
64566 ** Valid sqlite3_blob* handles point to Incrblob structures.
64567 */
64568 typedef struct Incrblob Incrblob;
64569 struct Incrblob {
64570   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
64571   int nByte;              /* Size of open blob, in bytes */
64572   int iOffset;            /* Byte offset of blob in cursor data */
64573   BtCursor *pCsr;         /* Cursor pointing at blob row */
64574   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
64575   sqlite3 *db;            /* The associated database */
64576 };
64577
64578 /*
64579 ** Open a blob handle.
64580 */
64581 SQLITE_API int sqlite3_blob_open(
64582   sqlite3* db,            /* The database connection */
64583   const char *zDb,        /* The attached database containing the blob */
64584   const char *zTable,     /* The table containing the blob */
64585   const char *zColumn,    /* The column containing the blob */
64586   sqlite_int64 iRow,      /* The row containing the glob */
64587   int flags,              /* True -> read/write access, false -> read-only */
64588   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
64589 ){
64590   int nAttempt = 0;
64591   int iCol;               /* Index of zColumn in row-record */
64592
64593   /* This VDBE program seeks a btree cursor to the identified 
64594   ** db/table/row entry. The reason for using a vdbe program instead
64595   ** of writing code to use the b-tree layer directly is that the
64596   ** vdbe program will take advantage of the various transaction,
64597   ** locking and error handling infrastructure built into the vdbe.
64598   **
64599   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
64600   ** Code external to the Vdbe then "borrows" the b-tree cursor and
64601   ** uses it to implement the blob_read(), blob_write() and 
64602   ** blob_bytes() functions.
64603   **
64604   ** The sqlite3_blob_close() function finalizes the vdbe program,
64605   ** which closes the b-tree cursor and (possibly) commits the 
64606   ** transaction.
64607   */
64608   static const VdbeOpList openBlob[] = {
64609     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
64610     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
64611     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
64612
64613     /* One of the following two instructions is replaced by an OP_Noop. */
64614     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
64615     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
64616
64617     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
64618     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
64619     {OP_Column, 0, 0, 1},          /* 7  */
64620     {OP_ResultRow, 1, 0, 0},       /* 8  */
64621     {OP_Close, 0, 0, 0},           /* 9  */
64622     {OP_Halt, 0, 0, 0},            /* 10 */
64623   };
64624
64625   Vdbe *v = 0;
64626   int rc = SQLITE_OK;
64627   char *zErr = 0;
64628   Table *pTab;
64629   Parse *pParse;
64630
64631   *ppBlob = 0;
64632   sqlite3_mutex_enter(db->mutex);
64633   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
64634   if( pParse==0 ){
64635     rc = SQLITE_NOMEM;
64636     goto blob_open_out;
64637   }
64638   do {
64639     memset(pParse, 0, sizeof(Parse));
64640     pParse->db = db;
64641
64642     sqlite3BtreeEnterAll(db);
64643     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
64644     if( pTab && IsVirtual(pTab) ){
64645       pTab = 0;
64646       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
64647     }
64648 #ifndef SQLITE_OMIT_VIEW
64649     if( pTab && pTab->pSelect ){
64650       pTab = 0;
64651       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
64652     }
64653 #endif
64654     if( !pTab ){
64655       if( pParse->zErrMsg ){
64656         sqlite3DbFree(db, zErr);
64657         zErr = pParse->zErrMsg;
64658         pParse->zErrMsg = 0;
64659       }
64660       rc = SQLITE_ERROR;
64661       sqlite3BtreeLeaveAll(db);
64662       goto blob_open_out;
64663     }
64664
64665     /* Now search pTab for the exact column. */
64666     for(iCol=0; iCol < pTab->nCol; iCol++) {
64667       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
64668         break;
64669       }
64670     }
64671     if( iCol==pTab->nCol ){
64672       sqlite3DbFree(db, zErr);
64673       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
64674       rc = SQLITE_ERROR;
64675       sqlite3BtreeLeaveAll(db);
64676       goto blob_open_out;
64677     }
64678
64679     /* If the value is being opened for writing, check that the
64680     ** column is not indexed, and that it is not part of a foreign key. 
64681     ** It is against the rules to open a column to which either of these
64682     ** descriptions applies for writing.  */
64683     if( flags ){
64684       const char *zFault = 0;
64685       Index *pIdx;
64686 #ifndef SQLITE_OMIT_FOREIGN_KEY
64687       if( db->flags&SQLITE_ForeignKeys ){
64688         /* Check that the column is not part of an FK child key definition. It
64689         ** is not necessary to check if it is part of a parent key, as parent
64690         ** key columns must be indexed. The check below will pick up this 
64691         ** case.  */
64692         FKey *pFKey;
64693         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
64694           int j;
64695           for(j=0; j<pFKey->nCol; j++){
64696             if( pFKey->aCol[j].iFrom==iCol ){
64697               zFault = "foreign key";
64698             }
64699           }
64700         }
64701       }
64702 #endif
64703       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64704         int j;
64705         for(j=0; j<pIdx->nColumn; j++){
64706           if( pIdx->aiColumn[j]==iCol ){
64707             zFault = "indexed";
64708           }
64709         }
64710       }
64711       if( zFault ){
64712         sqlite3DbFree(db, zErr);
64713         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
64714         rc = SQLITE_ERROR;
64715         sqlite3BtreeLeaveAll(db);
64716         goto blob_open_out;
64717       }
64718     }
64719
64720     v = sqlite3VdbeCreate(db);
64721     if( v ){
64722       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64723       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
64724       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
64725
64726       /* Configure the OP_Transaction */
64727       sqlite3VdbeChangeP1(v, 0, iDb);
64728       sqlite3VdbeChangeP2(v, 0, flags);
64729
64730       /* Configure the OP_VerifyCookie */
64731       sqlite3VdbeChangeP1(v, 1, iDb);
64732       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
64733
64734       /* Make sure a mutex is held on the table to be accessed */
64735       sqlite3VdbeUsesBtree(v, iDb); 
64736
64737       /* Configure the OP_TableLock instruction */
64738 #ifdef SQLITE_OMIT_SHARED_CACHE
64739       sqlite3VdbeChangeToNoop(v, 2, 1);
64740 #else
64741       sqlite3VdbeChangeP1(v, 2, iDb);
64742       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
64743       sqlite3VdbeChangeP3(v, 2, flags);
64744       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
64745 #endif
64746
64747       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
64748       ** parameter of the other to pTab->tnum.  */
64749       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
64750       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
64751       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
64752
64753       /* Configure the number of columns. Configure the cursor to
64754       ** think that the table has one more column than it really
64755       ** does. An OP_Column to retrieve this imaginary column will
64756       ** always return an SQL NULL. This is useful because it means
64757       ** we can invoke OP_Column to fill in the vdbe cursors type 
64758       ** and offset cache without causing any IO.
64759       */
64760       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
64761       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
64762       if( !db->mallocFailed ){
64763         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
64764       }
64765     }
64766    
64767     sqlite3BtreeLeaveAll(db);
64768     if( db->mallocFailed ){
64769       goto blob_open_out;
64770     }
64771
64772     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
64773     rc = sqlite3_step((sqlite3_stmt *)v);
64774     if( rc!=SQLITE_ROW ){
64775       nAttempt++;
64776       rc = sqlite3_finalize((sqlite3_stmt *)v);
64777       sqlite3DbFree(db, zErr);
64778       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
64779       v = 0;
64780     }
64781   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
64782
64783   if( rc==SQLITE_ROW ){
64784     /* The row-record has been opened successfully. Check that the
64785     ** column in question contains text or a blob. If it contains
64786     ** text, it is up to the caller to get the encoding right.
64787     */
64788     Incrblob *pBlob;
64789     u32 type = v->apCsr[0]->aType[iCol];
64790
64791     if( type<12 ){
64792       sqlite3DbFree(db, zErr);
64793       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
64794           type==0?"null": type==7?"real": "integer"
64795       );
64796       rc = SQLITE_ERROR;
64797       goto blob_open_out;
64798     }
64799     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
64800     if( db->mallocFailed ){
64801       sqlite3DbFree(db, pBlob);
64802       goto blob_open_out;
64803     }
64804     pBlob->flags = flags;
64805     pBlob->pCsr =  v->apCsr[0]->pCursor;
64806     sqlite3BtreeEnterCursor(pBlob->pCsr);
64807     sqlite3BtreeCacheOverflow(pBlob->pCsr);
64808     sqlite3BtreeLeaveCursor(pBlob->pCsr);
64809     pBlob->pStmt = (sqlite3_stmt *)v;
64810     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
64811     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
64812     pBlob->db = db;
64813     *ppBlob = (sqlite3_blob *)pBlob;
64814     rc = SQLITE_OK;
64815   }else if( rc==SQLITE_OK ){
64816     sqlite3DbFree(db, zErr);
64817     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
64818     rc = SQLITE_ERROR;
64819   }
64820
64821 blob_open_out:
64822   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
64823     sqlite3VdbeFinalize(v);
64824   }
64825   sqlite3Error(db, rc, zErr);
64826   sqlite3DbFree(db, zErr);
64827   sqlite3StackFree(db, pParse);
64828   rc = sqlite3ApiExit(db, rc);
64829   sqlite3_mutex_leave(db->mutex);
64830   return rc;
64831 }
64832
64833 /*
64834 ** Close a blob handle that was previously created using
64835 ** sqlite3_blob_open().
64836 */
64837 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
64838   Incrblob *p = (Incrblob *)pBlob;
64839   int rc;
64840   sqlite3 *db;
64841
64842   if( p ){
64843     db = p->db;
64844     sqlite3_mutex_enter(db->mutex);
64845     rc = sqlite3_finalize(p->pStmt);
64846     sqlite3DbFree(db, p);
64847     sqlite3_mutex_leave(db->mutex);
64848   }else{
64849     rc = SQLITE_OK;
64850   }
64851   return rc;
64852 }
64853
64854 /*
64855 ** Perform a read or write operation on a blob
64856 */
64857 static int blobReadWrite(
64858   sqlite3_blob *pBlob, 
64859   void *z, 
64860   int n, 
64861   int iOffset, 
64862   int (*xCall)(BtCursor*, u32, u32, void*)
64863 ){
64864   int rc;
64865   Incrblob *p = (Incrblob *)pBlob;
64866   Vdbe *v;
64867   sqlite3 *db;
64868
64869   if( p==0 ) return SQLITE_MISUSE_BKPT;
64870   db = p->db;
64871   sqlite3_mutex_enter(db->mutex);
64872   v = (Vdbe*)p->pStmt;
64873
64874   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
64875     /* Request is out of range. Return a transient error. */
64876     rc = SQLITE_ERROR;
64877     sqlite3Error(db, SQLITE_ERROR, 0);
64878   } else if( v==0 ){
64879     /* If there is no statement handle, then the blob-handle has
64880     ** already been invalidated. Return SQLITE_ABORT in this case.
64881     */
64882     rc = SQLITE_ABORT;
64883   }else{
64884     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
64885     ** returned, clean-up the statement handle.
64886     */
64887     assert( db == v->db );
64888     sqlite3BtreeEnterCursor(p->pCsr);
64889     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
64890     sqlite3BtreeLeaveCursor(p->pCsr);
64891     if( rc==SQLITE_ABORT ){
64892       sqlite3VdbeFinalize(v);
64893       p->pStmt = 0;
64894     }else{
64895       db->errCode = rc;
64896       v->rc = rc;
64897     }
64898   }
64899   rc = sqlite3ApiExit(db, rc);
64900   sqlite3_mutex_leave(db->mutex);
64901   return rc;
64902 }
64903
64904 /*
64905 ** Read data from a blob handle.
64906 */
64907 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
64908   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
64909 }
64910
64911 /*
64912 ** Write data to a blob handle.
64913 */
64914 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
64915   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
64916 }
64917
64918 /*
64919 ** Query a blob handle for the size of the data.
64920 **
64921 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
64922 ** so no mutex is required for access.
64923 */
64924 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
64925   Incrblob *p = (Incrblob *)pBlob;
64926   return p ? p->nByte : 0;
64927 }
64928
64929 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
64930
64931 /************** End of vdbeblob.c ********************************************/
64932 /************** Begin file journal.c *****************************************/
64933 /*
64934 ** 2007 August 22
64935 **
64936 ** The author disclaims copyright to this source code.  In place of
64937 ** a legal notice, here is a blessing:
64938 **
64939 **    May you do good and not evil.
64940 **    May you find forgiveness for yourself and forgive others.
64941 **    May you share freely, never taking more than you give.
64942 **
64943 *************************************************************************
64944 **
64945 ** This file implements a special kind of sqlite3_file object used
64946 ** by SQLite to create journal files if the atomic-write optimization
64947 ** is enabled.
64948 **
64949 ** The distinctive characteristic of this sqlite3_file is that the
64950 ** actual on disk file is created lazily. When the file is created,
64951 ** the caller specifies a buffer size for an in-memory buffer to
64952 ** be used to service read() and write() requests. The actual file
64953 ** on disk is not created or populated until either:
64954 **
64955 **   1) The in-memory representation grows too large for the allocated 
64956 **      buffer, or
64957 **   2) The sqlite3JournalCreate() function is called.
64958 */
64959 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
64960
64961
64962 /*
64963 ** A JournalFile object is a subclass of sqlite3_file used by
64964 ** as an open file handle for journal files.
64965 */
64966 struct JournalFile {
64967   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
64968   int nBuf;                       /* Size of zBuf[] in bytes */
64969   char *zBuf;                     /* Space to buffer journal writes */
64970   int iSize;                      /* Amount of zBuf[] currently used */
64971   int flags;                      /* xOpen flags */
64972   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
64973   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
64974   const char *zJournal;           /* Name of the journal file */
64975 };
64976 typedef struct JournalFile JournalFile;
64977
64978 /*
64979 ** If it does not already exists, create and populate the on-disk file 
64980 ** for JournalFile p.
64981 */
64982 static int createFile(JournalFile *p){
64983   int rc = SQLITE_OK;
64984   if( !p->pReal ){
64985     sqlite3_file *pReal = (sqlite3_file *)&p[1];
64986     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
64987     if( rc==SQLITE_OK ){
64988       p->pReal = pReal;
64989       if( p->iSize>0 ){
64990         assert(p->iSize<=p->nBuf);
64991         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
64992       }
64993     }
64994   }
64995   return rc;
64996 }
64997
64998 /*
64999 ** Close the file.
65000 */
65001 static int jrnlClose(sqlite3_file *pJfd){
65002   JournalFile *p = (JournalFile *)pJfd;
65003   if( p->pReal ){
65004     sqlite3OsClose(p->pReal);
65005   }
65006   sqlite3_free(p->zBuf);
65007   return SQLITE_OK;
65008 }
65009
65010 /*
65011 ** Read data from the file.
65012 */
65013 static int jrnlRead(
65014   sqlite3_file *pJfd,    /* The journal file from which to read */
65015   void *zBuf,            /* Put the results here */
65016   int iAmt,              /* Number of bytes to read */
65017   sqlite_int64 iOfst     /* Begin reading at this offset */
65018 ){
65019   int rc = SQLITE_OK;
65020   JournalFile *p = (JournalFile *)pJfd;
65021   if( p->pReal ){
65022     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
65023   }else if( (iAmt+iOfst)>p->iSize ){
65024     rc = SQLITE_IOERR_SHORT_READ;
65025   }else{
65026     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
65027   }
65028   return rc;
65029 }
65030
65031 /*
65032 ** Write data to the file.
65033 */
65034 static int jrnlWrite(
65035   sqlite3_file *pJfd,    /* The journal file into which to write */
65036   const void *zBuf,      /* Take data to be written from here */
65037   int iAmt,              /* Number of bytes to write */
65038   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
65039 ){
65040   int rc = SQLITE_OK;
65041   JournalFile *p = (JournalFile *)pJfd;
65042   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
65043     rc = createFile(p);
65044   }
65045   if( rc==SQLITE_OK ){
65046     if( p->pReal ){
65047       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
65048     }else{
65049       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
65050       if( p->iSize<(iOfst+iAmt) ){
65051         p->iSize = (iOfst+iAmt);
65052       }
65053     }
65054   }
65055   return rc;
65056 }
65057
65058 /*
65059 ** Truncate the file.
65060 */
65061 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
65062   int rc = SQLITE_OK;
65063   JournalFile *p = (JournalFile *)pJfd;
65064   if( p->pReal ){
65065     rc = sqlite3OsTruncate(p->pReal, size);
65066   }else if( size<p->iSize ){
65067     p->iSize = size;
65068   }
65069   return rc;
65070 }
65071
65072 /*
65073 ** Sync the file.
65074 */
65075 static int jrnlSync(sqlite3_file *pJfd, int flags){
65076   int rc;
65077   JournalFile *p = (JournalFile *)pJfd;
65078   if( p->pReal ){
65079     rc = sqlite3OsSync(p->pReal, flags);
65080   }else{
65081     rc = SQLITE_OK;
65082   }
65083   return rc;
65084 }
65085
65086 /*
65087 ** Query the size of the file in bytes.
65088 */
65089 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
65090   int rc = SQLITE_OK;
65091   JournalFile *p = (JournalFile *)pJfd;
65092   if( p->pReal ){
65093     rc = sqlite3OsFileSize(p->pReal, pSize);
65094   }else{
65095     *pSize = (sqlite_int64) p->iSize;
65096   }
65097   return rc;
65098 }
65099
65100 /*
65101 ** Table of methods for JournalFile sqlite3_file object.
65102 */
65103 static struct sqlite3_io_methods JournalFileMethods = {
65104   1,             /* iVersion */
65105   jrnlClose,     /* xClose */
65106   jrnlRead,      /* xRead */
65107   jrnlWrite,     /* xWrite */
65108   jrnlTruncate,  /* xTruncate */
65109   jrnlSync,      /* xSync */
65110   jrnlFileSize,  /* xFileSize */
65111   0,             /* xLock */
65112   0,             /* xUnlock */
65113   0,             /* xCheckReservedLock */
65114   0,             /* xFileControl */
65115   0,             /* xSectorSize */
65116   0,             /* xDeviceCharacteristics */
65117   0,             /* xShmMap */
65118   0,             /* xShmLock */
65119   0,             /* xShmBarrier */
65120   0              /* xShmUnmap */
65121 };
65122
65123 /* 
65124 ** Open a journal file.
65125 */
65126 SQLITE_PRIVATE int sqlite3JournalOpen(
65127   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
65128   const char *zName,         /* Name of the journal file */
65129   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
65130   int flags,                 /* Opening flags */
65131   int nBuf                   /* Bytes buffered before opening the file */
65132 ){
65133   JournalFile *p = (JournalFile *)pJfd;
65134   memset(p, 0, sqlite3JournalSize(pVfs));
65135   if( nBuf>0 ){
65136     p->zBuf = sqlite3MallocZero(nBuf);
65137     if( !p->zBuf ){
65138       return SQLITE_NOMEM;
65139     }
65140   }else{
65141     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
65142   }
65143   p->pMethod = &JournalFileMethods;
65144   p->nBuf = nBuf;
65145   p->flags = flags;
65146   p->zJournal = zName;
65147   p->pVfs = pVfs;
65148   return SQLITE_OK;
65149 }
65150
65151 /*
65152 ** If the argument p points to a JournalFile structure, and the underlying
65153 ** file has not yet been created, create it now.
65154 */
65155 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
65156   if( p->pMethods!=&JournalFileMethods ){
65157     return SQLITE_OK;
65158   }
65159   return createFile((JournalFile *)p);
65160 }
65161
65162 /* 
65163 ** Return the number of bytes required to store a JournalFile that uses vfs
65164 ** pVfs to create the underlying on-disk files.
65165 */
65166 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
65167   return (pVfs->szOsFile+sizeof(JournalFile));
65168 }
65169 #endif
65170
65171 /************** End of journal.c *********************************************/
65172 /************** Begin file memjournal.c **************************************/
65173 /*
65174 ** 2008 October 7
65175 **
65176 ** The author disclaims copyright to this source code.  In place of
65177 ** a legal notice, here is a blessing:
65178 **
65179 **    May you do good and not evil.
65180 **    May you find forgiveness for yourself and forgive others.
65181 **    May you share freely, never taking more than you give.
65182 **
65183 *************************************************************************
65184 **
65185 ** This file contains code use to implement an in-memory rollback journal.
65186 ** The in-memory rollback journal is used to journal transactions for
65187 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
65188 */
65189
65190 /* Forward references to internal structures */
65191 typedef struct MemJournal MemJournal;
65192 typedef struct FilePoint FilePoint;
65193 typedef struct FileChunk FileChunk;
65194
65195 /* Space to hold the rollback journal is allocated in increments of
65196 ** this many bytes.
65197 **
65198 ** The size chosen is a little less than a power of two.  That way,
65199 ** the FileChunk object will have a size that almost exactly fills
65200 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
65201 ** memory allocators.
65202 */
65203 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
65204
65205 /* Macro to find the minimum of two numeric values.
65206 */
65207 #ifndef MIN
65208 # define MIN(x,y) ((x)<(y)?(x):(y))
65209 #endif
65210
65211 /*
65212 ** The rollback journal is composed of a linked list of these structures.
65213 */
65214 struct FileChunk {
65215   FileChunk *pNext;               /* Next chunk in the journal */
65216   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
65217 };
65218
65219 /*
65220 ** An instance of this object serves as a cursor into the rollback journal.
65221 ** The cursor can be either for reading or writing.
65222 */
65223 struct FilePoint {
65224   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
65225   FileChunk *pChunk;              /* Specific chunk into which cursor points */
65226 };
65227
65228 /*
65229 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
65230 ** is an instance of this class.
65231 */
65232 struct MemJournal {
65233   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
65234   FileChunk *pFirst;              /* Head of in-memory chunk-list */
65235   FilePoint endpoint;             /* Pointer to the end of the file */
65236   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
65237 };
65238
65239 /*
65240 ** Read data from the in-memory journal file.  This is the implementation
65241 ** of the sqlite3_vfs.xRead method.
65242 */
65243 static int memjrnlRead(
65244   sqlite3_file *pJfd,    /* The journal file from which to read */
65245   void *zBuf,            /* Put the results here */
65246   int iAmt,              /* Number of bytes to read */
65247   sqlite_int64 iOfst     /* Begin reading at this offset */
65248 ){
65249   MemJournal *p = (MemJournal *)pJfd;
65250   u8 *zOut = zBuf;
65251   int nRead = iAmt;
65252   int iChunkOffset;
65253   FileChunk *pChunk;
65254
65255   /* SQLite never tries to read past the end of a rollback journal file */
65256   assert( iOfst+iAmt<=p->endpoint.iOffset );
65257
65258   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
65259     sqlite3_int64 iOff = 0;
65260     for(pChunk=p->pFirst; 
65261         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
65262         pChunk=pChunk->pNext
65263     ){
65264       iOff += JOURNAL_CHUNKSIZE;
65265     }
65266   }else{
65267     pChunk = p->readpoint.pChunk;
65268   }
65269
65270   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
65271   do {
65272     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
65273     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
65274     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
65275     zOut += nCopy;
65276     nRead -= iSpace;
65277     iChunkOffset = 0;
65278   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
65279   p->readpoint.iOffset = iOfst+iAmt;
65280   p->readpoint.pChunk = pChunk;
65281
65282   return SQLITE_OK;
65283 }
65284
65285 /*
65286 ** Write data to the file.
65287 */
65288 static int memjrnlWrite(
65289   sqlite3_file *pJfd,    /* The journal file into which to write */
65290   const void *zBuf,      /* Take data to be written from here */
65291   int iAmt,              /* Number of bytes to write */
65292   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
65293 ){
65294   MemJournal *p = (MemJournal *)pJfd;
65295   int nWrite = iAmt;
65296   u8 *zWrite = (u8 *)zBuf;
65297
65298   /* An in-memory journal file should only ever be appended to. Random
65299   ** access writes are not required by sqlite.
65300   */
65301   assert( iOfst==p->endpoint.iOffset );
65302   UNUSED_PARAMETER(iOfst);
65303
65304   while( nWrite>0 ){
65305     FileChunk *pChunk = p->endpoint.pChunk;
65306     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
65307     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
65308
65309     if( iChunkOffset==0 ){
65310       /* New chunk is required to extend the file. */
65311       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
65312       if( !pNew ){
65313         return SQLITE_IOERR_NOMEM;
65314       }
65315       pNew->pNext = 0;
65316       if( pChunk ){
65317         assert( p->pFirst );
65318         pChunk->pNext = pNew;
65319       }else{
65320         assert( !p->pFirst );
65321         p->pFirst = pNew;
65322       }
65323       p->endpoint.pChunk = pNew;
65324     }
65325
65326     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
65327     zWrite += iSpace;
65328     nWrite -= iSpace;
65329     p->endpoint.iOffset += iSpace;
65330   }
65331
65332   return SQLITE_OK;
65333 }
65334
65335 /*
65336 ** Truncate the file.
65337 */
65338 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
65339   MemJournal *p = (MemJournal *)pJfd;
65340   FileChunk *pChunk;
65341   assert(size==0);
65342   UNUSED_PARAMETER(size);
65343   pChunk = p->pFirst;
65344   while( pChunk ){
65345     FileChunk *pTmp = pChunk;
65346     pChunk = pChunk->pNext;
65347     sqlite3_free(pTmp);
65348   }
65349   sqlite3MemJournalOpen(pJfd);
65350   return SQLITE_OK;
65351 }
65352
65353 /*
65354 ** Close the file.
65355 */
65356 static int memjrnlClose(sqlite3_file *pJfd){
65357   memjrnlTruncate(pJfd, 0);
65358   return SQLITE_OK;
65359 }
65360
65361
65362 /*
65363 ** Sync the file.
65364 **
65365 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
65366 ** is never called in a working implementation.  This implementation
65367 ** exists purely as a contingency, in case some malfunction in some other
65368 ** part of SQLite causes Sync to be called by mistake.
65369 */
65370 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
65371   UNUSED_PARAMETER2(NotUsed, NotUsed2);
65372   return SQLITE_OK;
65373 }
65374
65375 /*
65376 ** Query the size of the file in bytes.
65377 */
65378 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
65379   MemJournal *p = (MemJournal *)pJfd;
65380   *pSize = (sqlite_int64) p->endpoint.iOffset;
65381   return SQLITE_OK;
65382 }
65383
65384 /*
65385 ** Table of methods for MemJournal sqlite3_file object.
65386 */
65387 static const struct sqlite3_io_methods MemJournalMethods = {
65388   1,                /* iVersion */
65389   memjrnlClose,     /* xClose */
65390   memjrnlRead,      /* xRead */
65391   memjrnlWrite,     /* xWrite */
65392   memjrnlTruncate,  /* xTruncate */
65393   memjrnlSync,      /* xSync */
65394   memjrnlFileSize,  /* xFileSize */
65395   0,                /* xLock */
65396   0,                /* xUnlock */
65397   0,                /* xCheckReservedLock */
65398   0,                /* xFileControl */
65399   0,                /* xSectorSize */
65400   0,                /* xDeviceCharacteristics */
65401   0,                /* xShmMap */
65402   0,                /* xShmLock */
65403   0,                /* xShmBarrier */
65404   0                 /* xShmUnlock */
65405 };
65406
65407 /* 
65408 ** Open a journal file.
65409 */
65410 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
65411   MemJournal *p = (MemJournal *)pJfd;
65412   assert( EIGHT_BYTE_ALIGNMENT(p) );
65413   memset(p, 0, sqlite3MemJournalSize());
65414   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
65415 }
65416
65417 /*
65418 ** Return true if the file-handle passed as an argument is 
65419 ** an in-memory journal 
65420 */
65421 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
65422   return pJfd->pMethods==&MemJournalMethods;
65423 }
65424
65425 /* 
65426 ** Return the number of bytes required to store a MemJournal that uses vfs
65427 ** pVfs to create the underlying on-disk files.
65428 */
65429 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
65430   return sizeof(MemJournal);
65431 }
65432
65433 /************** End of memjournal.c ******************************************/
65434 /************** Begin file walker.c ******************************************/
65435 /*
65436 ** 2008 August 16
65437 **
65438 ** The author disclaims copyright to this source code.  In place of
65439 ** a legal notice, here is a blessing:
65440 **
65441 **    May you do good and not evil.
65442 **    May you find forgiveness for yourself and forgive others.
65443 **    May you share freely, never taking more than you give.
65444 **
65445 *************************************************************************
65446 ** This file contains routines used for walking the parser tree for
65447 ** an SQL statement.
65448 */
65449
65450
65451 /*
65452 ** Walk an expression tree.  Invoke the callback once for each node
65453 ** of the expression, while decending.  (In other words, the callback
65454 ** is invoked before visiting children.)
65455 **
65456 ** The return value from the callback should be one of the WRC_*
65457 ** constants to specify how to proceed with the walk.
65458 **
65459 **    WRC_Continue      Continue descending down the tree.
65460 **
65461 **    WRC_Prune         Do not descend into child nodes.  But allow
65462 **                      the walk to continue with sibling nodes.
65463 **
65464 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
65465 **                      return the top-level walk call.
65466 **
65467 ** The return value from this routine is WRC_Abort to abandon the tree walk
65468 ** and WRC_Continue to continue.
65469 */
65470 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
65471   int rc;
65472   if( pExpr==0 ) return WRC_Continue;
65473   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
65474   testcase( ExprHasProperty(pExpr, EP_Reduced) );
65475   rc = pWalker->xExprCallback(pWalker, pExpr);
65476   if( rc==WRC_Continue
65477               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
65478     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
65479     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
65480     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65481       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
65482     }else{
65483       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
65484     }
65485   }
65486   return rc & WRC_Abort;
65487 }
65488
65489 /*
65490 ** Call sqlite3WalkExpr() for every expression in list p or until
65491 ** an abort request is seen.
65492 */
65493 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
65494   int i;
65495   struct ExprList_item *pItem;
65496   if( p ){
65497     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
65498       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
65499     }
65500   }
65501   return WRC_Continue;
65502 }
65503
65504 /*
65505 ** Walk all expressions associated with SELECT statement p.  Do
65506 ** not invoke the SELECT callback on p, but do (of course) invoke
65507 ** any expr callbacks and SELECT callbacks that come from subqueries.
65508 ** Return WRC_Abort or WRC_Continue.
65509 */
65510 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
65511   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
65512   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
65513   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
65514   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
65515   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
65516   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
65517   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
65518   return WRC_Continue;
65519 }
65520
65521 /*
65522 ** Walk the parse trees associated with all subqueries in the
65523 ** FROM clause of SELECT statement p.  Do not invoke the select
65524 ** callback on p, but do invoke it on each FROM clause subquery
65525 ** and on any subqueries further down in the tree.  Return 
65526 ** WRC_Abort or WRC_Continue;
65527 */
65528 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
65529   SrcList *pSrc;
65530   int i;
65531   struct SrcList_item *pItem;
65532
65533   pSrc = p->pSrc;
65534   if( ALWAYS(pSrc) ){
65535     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
65536       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
65537         return WRC_Abort;
65538       }
65539     }
65540   }
65541   return WRC_Continue;
65542
65543
65544 /*
65545 ** Call sqlite3WalkExpr() for every expression in Select statement p.
65546 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
65547 ** on the compound select chain, p->pPrior.
65548 **
65549 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
65550 ** there is an abort request.
65551 **
65552 ** If the Walker does not have an xSelectCallback() then this routine
65553 ** is a no-op returning WRC_Continue.
65554 */
65555 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
65556   int rc;
65557   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
65558   rc = WRC_Continue;
65559   while( p  ){
65560     rc = pWalker->xSelectCallback(pWalker, p);
65561     if( rc ) break;
65562     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
65563     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
65564     p = p->pPrior;
65565   }
65566   return rc & WRC_Abort;
65567 }
65568
65569 /************** End of walker.c **********************************************/
65570 /************** Begin file resolve.c *****************************************/
65571 /*
65572 ** 2008 August 18
65573 **
65574 ** The author disclaims copyright to this source code.  In place of
65575 ** a legal notice, here is a blessing:
65576 **
65577 **    May you do good and not evil.
65578 **    May you find forgiveness for yourself and forgive others.
65579 **    May you share freely, never taking more than you give.
65580 **
65581 *************************************************************************
65582 **
65583 ** This file contains routines used for walking the parser tree and
65584 ** resolve all identifiers by associating them with a particular
65585 ** table and column.
65586 */
65587
65588 /*
65589 ** Turn the pExpr expression into an alias for the iCol-th column of the
65590 ** result set in pEList.
65591 **
65592 ** If the result set column is a simple column reference, then this routine
65593 ** makes an exact copy.  But for any other kind of expression, this
65594 ** routine make a copy of the result set column as the argument to the
65595 ** TK_AS operator.  The TK_AS operator causes the expression to be
65596 ** evaluated just once and then reused for each alias.
65597 **
65598 ** The reason for suppressing the TK_AS term when the expression is a simple
65599 ** column reference is so that the column reference will be recognized as
65600 ** usable by indices within the WHERE clause processing logic. 
65601 **
65602 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
65603 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
65604 **
65605 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
65606 **
65607 ** Is equivalent to:
65608 **
65609 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
65610 **
65611 ** The result of random()%5 in the GROUP BY clause is probably different
65612 ** from the result in the result-set.  We might fix this someday.  Or
65613 ** then again, we might not...
65614 */
65615 static void resolveAlias(
65616   Parse *pParse,         /* Parsing context */
65617   ExprList *pEList,      /* A result set */
65618   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
65619   Expr *pExpr,           /* Transform this into an alias to the result set */
65620   const char *zType      /* "GROUP" or "ORDER" or "" */
65621 ){
65622   Expr *pOrig;           /* The iCol-th column of the result set */
65623   Expr *pDup;            /* Copy of pOrig */
65624   sqlite3 *db;           /* The database connection */
65625
65626   assert( iCol>=0 && iCol<pEList->nExpr );
65627   pOrig = pEList->a[iCol].pExpr;
65628   assert( pOrig!=0 );
65629   assert( pOrig->flags & EP_Resolved );
65630   db = pParse->db;
65631   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
65632     pDup = sqlite3ExprDup(db, pOrig, 0);
65633     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
65634     if( pDup==0 ) return;
65635     if( pEList->a[iCol].iAlias==0 ){
65636       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
65637     }
65638     pDup->iTable = pEList->a[iCol].iAlias;
65639   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
65640     pDup = sqlite3ExprDup(db, pOrig, 0);
65641     if( pDup==0 ) return;
65642   }else{
65643     char *zToken = pOrig->u.zToken;
65644     assert( zToken!=0 );
65645     pOrig->u.zToken = 0;
65646     pDup = sqlite3ExprDup(db, pOrig, 0);
65647     pOrig->u.zToken = zToken;
65648     if( pDup==0 ) return;
65649     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
65650     pDup->flags2 |= EP2_MallocedToken;
65651     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
65652   }
65653   if( pExpr->flags & EP_ExpCollate ){
65654     pDup->pColl = pExpr->pColl;
65655     pDup->flags |= EP_ExpCollate;
65656   }
65657
65658   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
65659   ** prevents ExprDelete() from deleting the Expr structure itself,
65660   ** allowing it to be repopulated by the memcpy() on the following line.
65661   */
65662   ExprSetProperty(pExpr, EP_Static);
65663   sqlite3ExprDelete(db, pExpr);
65664   memcpy(pExpr, pDup, sizeof(*pExpr));
65665   sqlite3DbFree(db, pDup);
65666 }
65667
65668 /*
65669 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
65670 ** that name in the set of source tables in pSrcList and make the pExpr 
65671 ** expression node refer back to that source column.  The following changes
65672 ** are made to pExpr:
65673 **
65674 **    pExpr->iDb           Set the index in db->aDb[] of the database X
65675 **                         (even if X is implied).
65676 **    pExpr->iTable        Set to the cursor number for the table obtained
65677 **                         from pSrcList.
65678 **    pExpr->pTab          Points to the Table structure of X.Y (even if
65679 **                         X and/or Y are implied.)
65680 **    pExpr->iColumn       Set to the column number within the table.
65681 **    pExpr->op            Set to TK_COLUMN.
65682 **    pExpr->pLeft         Any expression this points to is deleted
65683 **    pExpr->pRight        Any expression this points to is deleted.
65684 **
65685 ** The zDb variable is the name of the database (the "X").  This value may be
65686 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
65687 ** can be used.  The zTable variable is the name of the table (the "Y").  This
65688 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
65689 ** means that the form of the name is Z and that columns from any table
65690 ** can be used.
65691 **
65692 ** If the name cannot be resolved unambiguously, leave an error message
65693 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
65694 */
65695 static int lookupName(
65696   Parse *pParse,       /* The parsing context */
65697   const char *zDb,     /* Name of the database containing table, or NULL */
65698   const char *zTab,    /* Name of table containing column, or NULL */
65699   const char *zCol,    /* Name of the column. */
65700   NameContext *pNC,    /* The name context used to resolve the name */
65701   Expr *pExpr          /* Make this EXPR node point to the selected column */
65702 ){
65703   int i, j;            /* Loop counters */
65704   int cnt = 0;                      /* Number of matching column names */
65705   int cntTab = 0;                   /* Number of matching table names */
65706   sqlite3 *db = pParse->db;         /* The database connection */
65707   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
65708   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
65709   NameContext *pTopNC = pNC;        /* First namecontext in the list */
65710   Schema *pSchema = 0;              /* Schema of the expression */
65711   int isTrigger = 0;
65712
65713   assert( pNC );     /* the name context cannot be NULL. */
65714   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
65715   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
65716
65717   /* Initialize the node to no-match */
65718   pExpr->iTable = -1;
65719   pExpr->pTab = 0;
65720   ExprSetIrreducible(pExpr);
65721
65722   /* Start at the inner-most context and move outward until a match is found */
65723   while( pNC && cnt==0 ){
65724     ExprList *pEList;
65725     SrcList *pSrcList = pNC->pSrcList;
65726
65727     if( pSrcList ){
65728       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
65729         Table *pTab;
65730         int iDb;
65731         Column *pCol;
65732   
65733         pTab = pItem->pTab;
65734         assert( pTab!=0 && pTab->zName!=0 );
65735         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65736         assert( pTab->nCol>0 );
65737         if( zTab ){
65738           if( pItem->zAlias ){
65739             char *zTabName = pItem->zAlias;
65740             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
65741           }else{
65742             char *zTabName = pTab->zName;
65743             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
65744               continue;
65745             }
65746             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
65747               continue;
65748             }
65749           }
65750         }
65751         if( 0==(cntTab++) ){
65752           pExpr->iTable = pItem->iCursor;
65753           pExpr->pTab = pTab;
65754           pSchema = pTab->pSchema;
65755           pMatch = pItem;
65756         }
65757         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
65758           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65759             IdList *pUsing;
65760             cnt++;
65761             pExpr->iTable = pItem->iCursor;
65762             pExpr->pTab = pTab;
65763             pMatch = pItem;
65764             pSchema = pTab->pSchema;
65765             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
65766             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
65767             if( i<pSrcList->nSrc-1 ){
65768               if( pItem[1].jointype & JT_NATURAL ){
65769                 /* If this match occurred in the left table of a natural join,
65770                 ** then skip the right table to avoid a duplicate match */
65771                 pItem++;
65772                 i++;
65773               }else if( (pUsing = pItem[1].pUsing)!=0 ){
65774                 /* If this match occurs on a column that is in the USING clause
65775                 ** of a join, skip the search of the right table of the join
65776                 ** to avoid a duplicate match there. */
65777                 int k;
65778                 for(k=0; k<pUsing->nId; k++){
65779                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
65780                     pItem++;
65781                     i++;
65782                     break;
65783                   }
65784                 }
65785               }
65786             }
65787             break;
65788           }
65789         }
65790       }
65791     }
65792
65793 #ifndef SQLITE_OMIT_TRIGGER
65794     /* If we have not already resolved the name, then maybe 
65795     ** it is a new.* or old.* trigger argument reference
65796     */
65797     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
65798       int op = pParse->eTriggerOp;
65799       Table *pTab = 0;
65800       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
65801       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
65802         pExpr->iTable = 1;
65803         pTab = pParse->pTriggerTab;
65804       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
65805         pExpr->iTable = 0;
65806         pTab = pParse->pTriggerTab;
65807       }
65808
65809       if( pTab ){ 
65810         int iCol;
65811         pSchema = pTab->pSchema;
65812         cntTab++;
65813         for(iCol=0; iCol<pTab->nCol; iCol++){
65814           Column *pCol = &pTab->aCol[iCol];
65815           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65816             if( iCol==pTab->iPKey ){
65817               iCol = -1;
65818             }
65819             break;
65820           }
65821         }
65822         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
65823           iCol = -1;        /* IMP: R-44911-55124 */
65824         }
65825         if( iCol<pTab->nCol ){
65826           cnt++;
65827           if( iCol<0 ){
65828             pExpr->affinity = SQLITE_AFF_INTEGER;
65829           }else if( pExpr->iTable==0 ){
65830             testcase( iCol==31 );
65831             testcase( iCol==32 );
65832             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65833           }else{
65834             testcase( iCol==31 );
65835             testcase( iCol==32 );
65836             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65837           }
65838           pExpr->iColumn = (i16)iCol;
65839           pExpr->pTab = pTab;
65840           isTrigger = 1;
65841         }
65842       }
65843     }
65844 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
65845
65846     /*
65847     ** Perhaps the name is a reference to the ROWID
65848     */
65849     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
65850       cnt = 1;
65851       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
65852       pExpr->affinity = SQLITE_AFF_INTEGER;
65853     }
65854
65855     /*
65856     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
65857     ** might refer to an result-set alias.  This happens, for example, when
65858     ** we are resolving names in the WHERE clause of the following command:
65859     **
65860     **     SELECT a+b AS x FROM table WHERE x<10;
65861     **
65862     ** In cases like this, replace pExpr with a copy of the expression that
65863     ** forms the result set entry ("a+b" in the example) and return immediately.
65864     ** Note that the expression in the result set should have already been
65865     ** resolved by the time the WHERE clause is resolved.
65866     */
65867     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
65868       for(j=0; j<pEList->nExpr; j++){
65869         char *zAs = pEList->a[j].zName;
65870         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
65871           Expr *pOrig;
65872           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
65873           assert( pExpr->x.pList==0 );
65874           assert( pExpr->x.pSelect==0 );
65875           pOrig = pEList->a[j].pExpr;
65876           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
65877             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
65878             return WRC_Abort;
65879           }
65880           resolveAlias(pParse, pEList, j, pExpr, "");
65881           cnt = 1;
65882           pMatch = 0;
65883           assert( zTab==0 && zDb==0 );
65884           goto lookupname_end;
65885         }
65886       } 
65887     }
65888
65889     /* Advance to the next name context.  The loop will exit when either
65890     ** we have a match (cnt>0) or when we run out of name contexts.
65891     */
65892     if( cnt==0 ){
65893       pNC = pNC->pNext;
65894     }
65895   }
65896
65897   /*
65898   ** If X and Y are NULL (in other words if only the column name Z is
65899   ** supplied) and the value of Z is enclosed in double-quotes, then
65900   ** Z is a string literal if it doesn't match any column names.  In that
65901   ** case, we need to return right away and not make any changes to
65902   ** pExpr.
65903   **
65904   ** Because no reference was made to outer contexts, the pNC->nRef
65905   ** fields are not changed in any context.
65906   */
65907   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
65908     pExpr->op = TK_STRING;
65909     pExpr->pTab = 0;
65910     return WRC_Prune;
65911   }
65912
65913   /*
65914   ** cnt==0 means there was not match.  cnt>1 means there were two or
65915   ** more matches.  Either way, we have an error.
65916   */
65917   if( cnt!=1 ){
65918     const char *zErr;
65919     zErr = cnt==0 ? "no such column" : "ambiguous column name";
65920     if( zDb ){
65921       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
65922     }else if( zTab ){
65923       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
65924     }else{
65925       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
65926     }
65927     pParse->checkSchema = 1;
65928     pTopNC->nErr++;
65929   }
65930
65931   /* If a column from a table in pSrcList is referenced, then record
65932   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
65933   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
65934   ** column number is greater than the number of bits in the bitmask
65935   ** then set the high-order bit of the bitmask.
65936   */
65937   if( pExpr->iColumn>=0 && pMatch!=0 ){
65938     int n = pExpr->iColumn;
65939     testcase( n==BMS-1 );
65940     if( n>=BMS ){
65941       n = BMS-1;
65942     }
65943     assert( pMatch->iCursor==pExpr->iTable );
65944     pMatch->colUsed |= ((Bitmask)1)<<n;
65945   }
65946
65947   /* Clean up and return
65948   */
65949   sqlite3ExprDelete(db, pExpr->pLeft);
65950   pExpr->pLeft = 0;
65951   sqlite3ExprDelete(db, pExpr->pRight);
65952   pExpr->pRight = 0;
65953   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
65954 lookupname_end:
65955   if( cnt==1 ){
65956     assert( pNC!=0 );
65957     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
65958     /* Increment the nRef value on all name contexts from TopNC up to
65959     ** the point where the name matched. */
65960     for(;;){
65961       assert( pTopNC!=0 );
65962       pTopNC->nRef++;
65963       if( pTopNC==pNC ) break;
65964       pTopNC = pTopNC->pNext;
65965     }
65966     return WRC_Prune;
65967   } else {
65968     return WRC_Abort;
65969   }
65970 }
65971
65972 /*
65973 ** Allocate and return a pointer to an expression to load the column iCol
65974 ** from datasource iSrc in SrcList pSrc.
65975 */
65976 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
65977   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
65978   if( p ){
65979     struct SrcList_item *pItem = &pSrc->a[iSrc];
65980     p->pTab = pItem->pTab;
65981     p->iTable = pItem->iCursor;
65982     if( p->pTab->iPKey==iCol ){
65983       p->iColumn = -1;
65984     }else{
65985       p->iColumn = (ynVar)iCol;
65986       testcase( iCol==BMS );
65987       testcase( iCol==BMS-1 );
65988       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
65989     }
65990     ExprSetProperty(p, EP_Resolved);
65991   }
65992   return p;
65993 }
65994
65995 /*
65996 ** This routine is callback for sqlite3WalkExpr().
65997 **
65998 ** Resolve symbolic names into TK_COLUMN operators for the current
65999 ** node in the expression tree.  Return 0 to continue the search down
66000 ** the tree or 2 to abort the tree walk.
66001 **
66002 ** This routine also does error checking and name resolution for
66003 ** function names.  The operator for aggregate functions is changed
66004 ** to TK_AGG_FUNCTION.
66005 */
66006 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
66007   NameContext *pNC;
66008   Parse *pParse;
66009
66010   pNC = pWalker->u.pNC;
66011   assert( pNC!=0 );
66012   pParse = pNC->pParse;
66013   assert( pParse==pWalker->pParse );
66014
66015   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
66016   ExprSetProperty(pExpr, EP_Resolved);
66017 #ifndef NDEBUG
66018   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
66019     SrcList *pSrcList = pNC->pSrcList;
66020     int i;
66021     for(i=0; i<pNC->pSrcList->nSrc; i++){
66022       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
66023     }
66024   }
66025 #endif
66026   switch( pExpr->op ){
66027
66028 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
66029     /* The special operator TK_ROW means use the rowid for the first
66030     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
66031     ** clause processing on UPDATE and DELETE statements.
66032     */
66033     case TK_ROW: {
66034       SrcList *pSrcList = pNC->pSrcList;
66035       struct SrcList_item *pItem;
66036       assert( pSrcList && pSrcList->nSrc==1 );
66037       pItem = pSrcList->a; 
66038       pExpr->op = TK_COLUMN;
66039       pExpr->pTab = pItem->pTab;
66040       pExpr->iTable = pItem->iCursor;
66041       pExpr->iColumn = -1;
66042       pExpr->affinity = SQLITE_AFF_INTEGER;
66043       break;
66044     }
66045 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
66046
66047     /* A lone identifier is the name of a column.
66048     */
66049     case TK_ID: {
66050       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
66051     }
66052   
66053     /* A table name and column name:     ID.ID
66054     ** Or a database, table and column:  ID.ID.ID
66055     */
66056     case TK_DOT: {
66057       const char *zColumn;
66058       const char *zTable;
66059       const char *zDb;
66060       Expr *pRight;
66061
66062       /* if( pSrcList==0 ) break; */
66063       pRight = pExpr->pRight;
66064       if( pRight->op==TK_ID ){
66065         zDb = 0;
66066         zTable = pExpr->pLeft->u.zToken;
66067         zColumn = pRight->u.zToken;
66068       }else{
66069         assert( pRight->op==TK_DOT );
66070         zDb = pExpr->pLeft->u.zToken;
66071         zTable = pRight->pLeft->u.zToken;
66072         zColumn = pRight->pRight->u.zToken;
66073       }
66074       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
66075     }
66076
66077     /* Resolve function names
66078     */
66079     case TK_CONST_FUNC:
66080     case TK_FUNCTION: {
66081       ExprList *pList = pExpr->x.pList;    /* The argument list */
66082       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
66083       int no_such_func = 0;       /* True if no such function exists */
66084       int wrong_num_args = 0;     /* True if wrong number of arguments */
66085       int is_agg = 0;             /* True if is an aggregate function */
66086       int auth;                   /* Authorization to use the function */
66087       int nId;                    /* Number of characters in function name */
66088       const char *zId;            /* The function name. */
66089       FuncDef *pDef;              /* Information about the function */
66090       u8 enc = ENC(pParse->db);   /* The database encoding */
66091
66092       testcase( pExpr->op==TK_CONST_FUNC );
66093       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
66094       zId = pExpr->u.zToken;
66095       nId = sqlite3Strlen30(zId);
66096       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
66097       if( pDef==0 ){
66098         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
66099         if( pDef==0 ){
66100           no_such_func = 1;
66101         }else{
66102           wrong_num_args = 1;
66103         }
66104       }else{
66105         is_agg = pDef->xFunc==0;
66106       }
66107 #ifndef SQLITE_OMIT_AUTHORIZATION
66108       if( pDef ){
66109         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
66110         if( auth!=SQLITE_OK ){
66111           if( auth==SQLITE_DENY ){
66112             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
66113                                     pDef->zName);
66114             pNC->nErr++;
66115           }
66116           pExpr->op = TK_NULL;
66117           return WRC_Prune;
66118         }
66119       }
66120 #endif
66121       if( is_agg && !pNC->allowAgg ){
66122         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
66123         pNC->nErr++;
66124         is_agg = 0;
66125       }else if( no_such_func ){
66126         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
66127         pNC->nErr++;
66128       }else if( wrong_num_args ){
66129         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
66130              nId, zId);
66131         pNC->nErr++;
66132       }
66133       if( is_agg ){
66134         pExpr->op = TK_AGG_FUNCTION;
66135         pNC->hasAgg = 1;
66136       }
66137       if( is_agg ) pNC->allowAgg = 0;
66138       sqlite3WalkExprList(pWalker, pList);
66139       if( is_agg ) pNC->allowAgg = 1;
66140       /* FIX ME:  Compute pExpr->affinity based on the expected return
66141       ** type of the function 
66142       */
66143       return WRC_Prune;
66144     }
66145 #ifndef SQLITE_OMIT_SUBQUERY
66146     case TK_SELECT:
66147     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
66148 #endif
66149     case TK_IN: {
66150       testcase( pExpr->op==TK_IN );
66151       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66152         int nRef = pNC->nRef;
66153 #ifndef SQLITE_OMIT_CHECK
66154         if( pNC->isCheck ){
66155           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
66156         }
66157 #endif
66158         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
66159         assert( pNC->nRef>=nRef );
66160         if( nRef!=pNC->nRef ){
66161           ExprSetProperty(pExpr, EP_VarSelect);
66162         }
66163       }
66164       break;
66165     }
66166 #ifndef SQLITE_OMIT_CHECK
66167     case TK_VARIABLE: {
66168       if( pNC->isCheck ){
66169         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
66170       }
66171       break;
66172     }
66173 #endif
66174   }
66175   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
66176 }
66177
66178 /*
66179 ** pEList is a list of expressions which are really the result set of the
66180 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
66181 ** This routine checks to see if pE is a simple identifier which corresponds
66182 ** to the AS-name of one of the terms of the expression list.  If it is,
66183 ** this routine return an integer between 1 and N where N is the number of
66184 ** elements in pEList, corresponding to the matching entry.  If there is
66185 ** no match, or if pE is not a simple identifier, then this routine
66186 ** return 0.
66187 **
66188 ** pEList has been resolved.  pE has not.
66189 */
66190 static int resolveAsName(
66191   Parse *pParse,     /* Parsing context for error messages */
66192   ExprList *pEList,  /* List of expressions to scan */
66193   Expr *pE           /* Expression we are trying to match */
66194 ){
66195   int i;             /* Loop counter */
66196
66197   UNUSED_PARAMETER(pParse);
66198
66199   if( pE->op==TK_ID ){
66200     char *zCol = pE->u.zToken;
66201     for(i=0; i<pEList->nExpr; i++){
66202       char *zAs = pEList->a[i].zName;
66203       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
66204         return i+1;
66205       }
66206     }
66207   }
66208   return 0;
66209 }
66210
66211 /*
66212 ** pE is a pointer to an expression which is a single term in the
66213 ** ORDER BY of a compound SELECT.  The expression has not been
66214 ** name resolved.
66215 **
66216 ** At the point this routine is called, we already know that the
66217 ** ORDER BY term is not an integer index into the result set.  That
66218 ** case is handled by the calling routine.
66219 **
66220 ** Attempt to match pE against result set columns in the left-most
66221 ** SELECT statement.  Return the index i of the matching column,
66222 ** as an indication to the caller that it should sort by the i-th column.
66223 ** The left-most column is 1.  In other words, the value returned is the
66224 ** same integer value that would be used in the SQL statement to indicate
66225 ** the column.
66226 **
66227 ** If there is no match, return 0.  Return -1 if an error occurs.
66228 */
66229 static int resolveOrderByTermToExprList(
66230   Parse *pParse,     /* Parsing context for error messages */
66231   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
66232   Expr *pE           /* The specific ORDER BY term */
66233 ){
66234   int i;             /* Loop counter */
66235   ExprList *pEList;  /* The columns of the result set */
66236   NameContext nc;    /* Name context for resolving pE */
66237   sqlite3 *db;       /* Database connection */
66238   int rc;            /* Return code from subprocedures */
66239   u8 savedSuppErr;   /* Saved value of db->suppressErr */
66240
66241   assert( sqlite3ExprIsInteger(pE, &i)==0 );
66242   pEList = pSelect->pEList;
66243
66244   /* Resolve all names in the ORDER BY term expression
66245   */
66246   memset(&nc, 0, sizeof(nc));
66247   nc.pParse = pParse;
66248   nc.pSrcList = pSelect->pSrc;
66249   nc.pEList = pEList;
66250   nc.allowAgg = 1;
66251   nc.nErr = 0;
66252   db = pParse->db;
66253   savedSuppErr = db->suppressErr;
66254   db->suppressErr = 1;
66255   rc = sqlite3ResolveExprNames(&nc, pE);
66256   db->suppressErr = savedSuppErr;
66257   if( rc ) return 0;
66258
66259   /* Try to match the ORDER BY expression against an expression
66260   ** in the result set.  Return an 1-based index of the matching
66261   ** result-set entry.
66262   */
66263   for(i=0; i<pEList->nExpr; i++){
66264     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
66265       return i+1;
66266     }
66267   }
66268
66269   /* If no match, return 0. */
66270   return 0;
66271 }
66272
66273 /*
66274 ** Generate an ORDER BY or GROUP BY term out-of-range error.
66275 */
66276 static void resolveOutOfRangeError(
66277   Parse *pParse,         /* The error context into which to write the error */
66278   const char *zType,     /* "ORDER" or "GROUP" */
66279   int i,                 /* The index (1-based) of the term out of range */
66280   int mx                 /* Largest permissible value of i */
66281 ){
66282   sqlite3ErrorMsg(pParse, 
66283     "%r %s BY term out of range - should be "
66284     "between 1 and %d", i, zType, mx);
66285 }
66286
66287 /*
66288 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
66289 ** each term of the ORDER BY clause is a constant integer between 1
66290 ** and N where N is the number of columns in the compound SELECT.
66291 **
66292 ** ORDER BY terms that are already an integer between 1 and N are
66293 ** unmodified.  ORDER BY terms that are integers outside the range of
66294 ** 1 through N generate an error.  ORDER BY terms that are expressions
66295 ** are matched against result set expressions of compound SELECT
66296 ** beginning with the left-most SELECT and working toward the right.
66297 ** At the first match, the ORDER BY expression is transformed into
66298 ** the integer column number.
66299 **
66300 ** Return the number of errors seen.
66301 */
66302 static int resolveCompoundOrderBy(
66303   Parse *pParse,        /* Parsing context.  Leave error messages here */
66304   Select *pSelect       /* The SELECT statement containing the ORDER BY */
66305 ){
66306   int i;
66307   ExprList *pOrderBy;
66308   ExprList *pEList;
66309   sqlite3 *db;
66310   int moreToDo = 1;
66311
66312   pOrderBy = pSelect->pOrderBy;
66313   if( pOrderBy==0 ) return 0;
66314   db = pParse->db;
66315 #if SQLITE_MAX_COLUMN
66316   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
66317     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
66318     return 1;
66319   }
66320 #endif
66321   for(i=0; i<pOrderBy->nExpr; i++){
66322     pOrderBy->a[i].done = 0;
66323   }
66324   pSelect->pNext = 0;
66325   while( pSelect->pPrior ){
66326     pSelect->pPrior->pNext = pSelect;
66327     pSelect = pSelect->pPrior;
66328   }
66329   while( pSelect && moreToDo ){
66330     struct ExprList_item *pItem;
66331     moreToDo = 0;
66332     pEList = pSelect->pEList;
66333     assert( pEList!=0 );
66334     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66335       int iCol = -1;
66336       Expr *pE, *pDup;
66337       if( pItem->done ) continue;
66338       pE = pItem->pExpr;
66339       if( sqlite3ExprIsInteger(pE, &iCol) ){
66340         if( iCol<=0 || iCol>pEList->nExpr ){
66341           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
66342           return 1;
66343         }
66344       }else{
66345         iCol = resolveAsName(pParse, pEList, pE);
66346         if( iCol==0 ){
66347           pDup = sqlite3ExprDup(db, pE, 0);
66348           if( !db->mallocFailed ){
66349             assert(pDup);
66350             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
66351           }
66352           sqlite3ExprDelete(db, pDup);
66353         }
66354       }
66355       if( iCol>0 ){
66356         CollSeq *pColl = pE->pColl;
66357         int flags = pE->flags & EP_ExpCollate;
66358         sqlite3ExprDelete(db, pE);
66359         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
66360         if( pE==0 ) return 1;
66361         pE->pColl = pColl;
66362         pE->flags |= EP_IntValue | flags;
66363         pE->u.iValue = iCol;
66364         pItem->iCol = (u16)iCol;
66365         pItem->done = 1;
66366       }else{
66367         moreToDo = 1;
66368       }
66369     }
66370     pSelect = pSelect->pNext;
66371   }
66372   for(i=0; i<pOrderBy->nExpr; i++){
66373     if( pOrderBy->a[i].done==0 ){
66374       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
66375             "column in the result set", i+1);
66376       return 1;
66377     }
66378   }
66379   return 0;
66380 }
66381
66382 /*
66383 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
66384 ** the SELECT statement pSelect.  If any term is reference to a
66385 ** result set expression (as determined by the ExprList.a.iCol field)
66386 ** then convert that term into a copy of the corresponding result set
66387 ** column.
66388 **
66389 ** If any errors are detected, add an error message to pParse and
66390 ** return non-zero.  Return zero if no errors are seen.
66391 */
66392 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
66393   Parse *pParse,        /* Parsing context.  Leave error messages here */
66394   Select *pSelect,      /* The SELECT statement containing the clause */
66395   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
66396   const char *zType     /* "ORDER" or "GROUP" */
66397 ){
66398   int i;
66399   sqlite3 *db = pParse->db;
66400   ExprList *pEList;
66401   struct ExprList_item *pItem;
66402
66403   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
66404 #if SQLITE_MAX_COLUMN
66405   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
66406     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
66407     return 1;
66408   }
66409 #endif
66410   pEList = pSelect->pEList;
66411   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
66412   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66413     if( pItem->iCol ){
66414       if( pItem->iCol>pEList->nExpr ){
66415         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
66416         return 1;
66417       }
66418       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
66419     }
66420   }
66421   return 0;
66422 }
66423
66424 /*
66425 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
66426 ** The Name context of the SELECT statement is pNC.  zType is either
66427 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
66428 **
66429 ** This routine resolves each term of the clause into an expression.
66430 ** If the order-by term is an integer I between 1 and N (where N is the
66431 ** number of columns in the result set of the SELECT) then the expression
66432 ** in the resolution is a copy of the I-th result-set expression.  If
66433 ** the order-by term is an identify that corresponds to the AS-name of
66434 ** a result-set expression, then the term resolves to a copy of the
66435 ** result-set expression.  Otherwise, the expression is resolved in
66436 ** the usual way - using sqlite3ResolveExprNames().
66437 **
66438 ** This routine returns the number of errors.  If errors occur, then
66439 ** an appropriate error message might be left in pParse.  (OOM errors
66440 ** excepted.)
66441 */
66442 static int resolveOrderGroupBy(
66443   NameContext *pNC,     /* The name context of the SELECT statement */
66444   Select *pSelect,      /* The SELECT statement holding pOrderBy */
66445   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
66446   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
66447 ){
66448   int i;                         /* Loop counter */
66449   int iCol;                      /* Column number */
66450   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
66451   Parse *pParse;                 /* Parsing context */
66452   int nResult;                   /* Number of terms in the result set */
66453
66454   if( pOrderBy==0 ) return 0;
66455   nResult = pSelect->pEList->nExpr;
66456   pParse = pNC->pParse;
66457   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66458     Expr *pE = pItem->pExpr;
66459     iCol = resolveAsName(pParse, pSelect->pEList, pE);
66460     if( iCol>0 ){
66461       /* If an AS-name match is found, mark this ORDER BY column as being
66462       ** a copy of the iCol-th result-set column.  The subsequent call to
66463       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
66464       ** copy of the iCol-th result-set expression. */
66465       pItem->iCol = (u16)iCol;
66466       continue;
66467     }
66468     if( sqlite3ExprIsInteger(pE, &iCol) ){
66469       /* The ORDER BY term is an integer constant.  Again, set the column
66470       ** number so that sqlite3ResolveOrderGroupBy() will convert the
66471       ** order-by term to a copy of the result-set expression */
66472       if( iCol<1 ){
66473         resolveOutOfRangeError(pParse, zType, i+1, nResult);
66474         return 1;
66475       }
66476       pItem->iCol = (u16)iCol;
66477       continue;
66478     }
66479
66480     /* Otherwise, treat the ORDER BY term as an ordinary expression */
66481     pItem->iCol = 0;
66482     if( sqlite3ResolveExprNames(pNC, pE) ){
66483       return 1;
66484     }
66485   }
66486   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
66487 }
66488
66489 /*
66490 ** Resolve names in the SELECT statement p and all of its descendents.
66491 */
66492 static int resolveSelectStep(Walker *pWalker, Select *p){
66493   NameContext *pOuterNC;  /* Context that contains this SELECT */
66494   NameContext sNC;        /* Name context of this SELECT */
66495   int isCompound;         /* True if p is a compound select */
66496   int nCompound;          /* Number of compound terms processed so far */
66497   Parse *pParse;          /* Parsing context */
66498   ExprList *pEList;       /* Result set expression list */
66499   int i;                  /* Loop counter */
66500   ExprList *pGroupBy;     /* The GROUP BY clause */
66501   Select *pLeftmost;      /* Left-most of SELECT of a compound */
66502   sqlite3 *db;            /* Database connection */
66503   
66504
66505   assert( p!=0 );
66506   if( p->selFlags & SF_Resolved ){
66507     return WRC_Prune;
66508   }
66509   pOuterNC = pWalker->u.pNC;
66510   pParse = pWalker->pParse;
66511   db = pParse->db;
66512
66513   /* Normally sqlite3SelectExpand() will be called first and will have
66514   ** already expanded this SELECT.  However, if this is a subquery within
66515   ** an expression, sqlite3ResolveExprNames() will be called without a
66516   ** prior call to sqlite3SelectExpand().  When that happens, let
66517   ** sqlite3SelectPrep() do all of the processing for this SELECT.
66518   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
66519   ** this routine in the correct order.
66520   */
66521   if( (p->selFlags & SF_Expanded)==0 ){
66522     sqlite3SelectPrep(pParse, p, pOuterNC);
66523     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
66524   }
66525
66526   isCompound = p->pPrior!=0;
66527   nCompound = 0;
66528   pLeftmost = p;
66529   while( p ){
66530     assert( (p->selFlags & SF_Expanded)!=0 );
66531     assert( (p->selFlags & SF_Resolved)==0 );
66532     p->selFlags |= SF_Resolved;
66533
66534     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
66535     ** are not allowed to refer to any names, so pass an empty NameContext.
66536     */
66537     memset(&sNC, 0, sizeof(sNC));
66538     sNC.pParse = pParse;
66539     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
66540         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
66541       return WRC_Abort;
66542     }
66543   
66544     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
66545     ** resolve the result-set expression list.
66546     */
66547     sNC.allowAgg = 1;
66548     sNC.pSrcList = p->pSrc;
66549     sNC.pNext = pOuterNC;
66550   
66551     /* Resolve names in the result set. */
66552     pEList = p->pEList;
66553     assert( pEList!=0 );
66554     for(i=0; i<pEList->nExpr; i++){
66555       Expr *pX = pEList->a[i].pExpr;
66556       if( sqlite3ResolveExprNames(&sNC, pX) ){
66557         return WRC_Abort;
66558       }
66559     }
66560   
66561     /* Recursively resolve names in all subqueries
66562     */
66563     for(i=0; i<p->pSrc->nSrc; i++){
66564       struct SrcList_item *pItem = &p->pSrc->a[i];
66565       if( pItem->pSelect ){
66566         const char *zSavedContext = pParse->zAuthContext;
66567         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
66568         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
66569         pParse->zAuthContext = zSavedContext;
66570         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
66571       }
66572     }
66573   
66574     /* If there are no aggregate functions in the result-set, and no GROUP BY 
66575     ** expression, do not allow aggregates in any of the other expressions.
66576     */
66577     assert( (p->selFlags & SF_Aggregate)==0 );
66578     pGroupBy = p->pGroupBy;
66579     if( pGroupBy || sNC.hasAgg ){
66580       p->selFlags |= SF_Aggregate;
66581     }else{
66582       sNC.allowAgg = 0;
66583     }
66584   
66585     /* If a HAVING clause is present, then there must be a GROUP BY clause.
66586     */
66587     if( p->pHaving && !pGroupBy ){
66588       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
66589       return WRC_Abort;
66590     }
66591   
66592     /* Add the expression list to the name-context before parsing the
66593     ** other expressions in the SELECT statement. This is so that
66594     ** expressions in the WHERE clause (etc.) can refer to expressions by
66595     ** aliases in the result set.
66596     **
66597     ** Minor point: If this is the case, then the expression will be
66598     ** re-evaluated for each reference to it.
66599     */
66600     sNC.pEList = p->pEList;
66601     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
66602        sqlite3ResolveExprNames(&sNC, p->pHaving)
66603     ){
66604       return WRC_Abort;
66605     }
66606
66607     /* The ORDER BY and GROUP BY clauses may not refer to terms in
66608     ** outer queries 
66609     */
66610     sNC.pNext = 0;
66611     sNC.allowAgg = 1;
66612
66613     /* Process the ORDER BY clause for singleton SELECT statements.
66614     ** The ORDER BY clause for compounds SELECT statements is handled
66615     ** below, after all of the result-sets for all of the elements of
66616     ** the compound have been resolved.
66617     */
66618     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
66619       return WRC_Abort;
66620     }
66621     if( db->mallocFailed ){
66622       return WRC_Abort;
66623     }
66624   
66625     /* Resolve the GROUP BY clause.  At the same time, make sure 
66626     ** the GROUP BY clause does not contain aggregate functions.
66627     */
66628     if( pGroupBy ){
66629       struct ExprList_item *pItem;
66630     
66631       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
66632         return WRC_Abort;
66633       }
66634       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
66635         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
66636           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
66637               "the GROUP BY clause");
66638           return WRC_Abort;
66639         }
66640       }
66641     }
66642
66643     /* Advance to the next term of the compound
66644     */
66645     p = p->pPrior;
66646     nCompound++;
66647   }
66648
66649   /* Resolve the ORDER BY on a compound SELECT after all terms of
66650   ** the compound have been resolved.
66651   */
66652   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
66653     return WRC_Abort;
66654   }
66655
66656   return WRC_Prune;
66657 }
66658
66659 /*
66660 ** This routine walks an expression tree and resolves references to
66661 ** table columns and result-set columns.  At the same time, do error
66662 ** checking on function usage and set a flag if any aggregate functions
66663 ** are seen.
66664 **
66665 ** To resolve table columns references we look for nodes (or subtrees) of the 
66666 ** form X.Y.Z or Y.Z or just Z where
66667 **
66668 **      X:   The name of a database.  Ex:  "main" or "temp" or
66669 **           the symbolic name assigned to an ATTACH-ed database.
66670 **
66671 **      Y:   The name of a table in a FROM clause.  Or in a trigger
66672 **           one of the special names "old" or "new".
66673 **
66674 **      Z:   The name of a column in table Y.
66675 **
66676 ** The node at the root of the subtree is modified as follows:
66677 **
66678 **    Expr.op        Changed to TK_COLUMN
66679 **    Expr.pTab      Points to the Table object for X.Y
66680 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
66681 **    Expr.iTable    The VDBE cursor number for X.Y
66682 **
66683 **
66684 ** To resolve result-set references, look for expression nodes of the
66685 ** form Z (with no X and Y prefix) where the Z matches the right-hand
66686 ** size of an AS clause in the result-set of a SELECT.  The Z expression
66687 ** is replaced by a copy of the left-hand side of the result-set expression.
66688 ** Table-name and function resolution occurs on the substituted expression
66689 ** tree.  For example, in:
66690 **
66691 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
66692 **
66693 ** The "x" term of the order by is replaced by "a+b" to render:
66694 **
66695 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
66696 **
66697 ** Function calls are checked to make sure that the function is 
66698 ** defined and that the correct number of arguments are specified.
66699 ** If the function is an aggregate function, then the pNC->hasAgg is
66700 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
66701 ** If an expression contains aggregate functions then the EP_Agg
66702 ** property on the expression is set.
66703 **
66704 ** An error message is left in pParse if anything is amiss.  The number
66705 ** if errors is returned.
66706 */
66707 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
66708   NameContext *pNC,       /* Namespace to resolve expressions in. */
66709   Expr *pExpr             /* The expression to be analyzed. */
66710 ){
66711   int savedHasAgg;
66712   Walker w;
66713
66714   if( pExpr==0 ) return 0;
66715 #if SQLITE_MAX_EXPR_DEPTH>0
66716   {
66717     Parse *pParse = pNC->pParse;
66718     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
66719       return 1;
66720     }
66721     pParse->nHeight += pExpr->nHeight;
66722   }
66723 #endif
66724   savedHasAgg = pNC->hasAgg;
66725   pNC->hasAgg = 0;
66726   w.xExprCallback = resolveExprStep;
66727   w.xSelectCallback = resolveSelectStep;
66728   w.pParse = pNC->pParse;
66729   w.u.pNC = pNC;
66730   sqlite3WalkExpr(&w, pExpr);
66731 #if SQLITE_MAX_EXPR_DEPTH>0
66732   pNC->pParse->nHeight -= pExpr->nHeight;
66733 #endif
66734   if( pNC->nErr>0 || w.pParse->nErr>0 ){
66735     ExprSetProperty(pExpr, EP_Error);
66736   }
66737   if( pNC->hasAgg ){
66738     ExprSetProperty(pExpr, EP_Agg);
66739   }else if( savedHasAgg ){
66740     pNC->hasAgg = 1;
66741   }
66742   return ExprHasProperty(pExpr, EP_Error);
66743 }
66744
66745
66746 /*
66747 ** Resolve all names in all expressions of a SELECT and in all
66748 ** decendents of the SELECT, including compounds off of p->pPrior,
66749 ** subqueries in expressions, and subqueries used as FROM clause
66750 ** terms.
66751 **
66752 ** See sqlite3ResolveExprNames() for a description of the kinds of
66753 ** transformations that occur.
66754 **
66755 ** All SELECT statements should have been expanded using
66756 ** sqlite3SelectExpand() prior to invoking this routine.
66757 */
66758 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
66759   Parse *pParse,         /* The parser context */
66760   Select *p,             /* The SELECT statement being coded. */
66761   NameContext *pOuterNC  /* Name context for parent SELECT statement */
66762 ){
66763   Walker w;
66764
66765   assert( p!=0 );
66766   w.xExprCallback = resolveExprStep;
66767   w.xSelectCallback = resolveSelectStep;
66768   w.pParse = pParse;
66769   w.u.pNC = pOuterNC;
66770   sqlite3WalkSelect(&w, p);
66771 }
66772
66773 /************** End of resolve.c *********************************************/
66774 /************** Begin file expr.c ********************************************/
66775 /*
66776 ** 2001 September 15
66777 **
66778 ** The author disclaims copyright to this source code.  In place of
66779 ** a legal notice, here is a blessing:
66780 **
66781 **    May you do good and not evil.
66782 **    May you find forgiveness for yourself and forgive others.
66783 **    May you share freely, never taking more than you give.
66784 **
66785 *************************************************************************
66786 ** This file contains routines used for analyzing expressions and
66787 ** for generating VDBE code that evaluates expressions in SQLite.
66788 */
66789
66790 /*
66791 ** Return the 'affinity' of the expression pExpr if any.
66792 **
66793 ** If pExpr is a column, a reference to a column via an 'AS' alias,
66794 ** or a sub-select with a column as the return value, then the 
66795 ** affinity of that column is returned. Otherwise, 0x00 is returned,
66796 ** indicating no affinity for the expression.
66797 **
66798 ** i.e. the WHERE clause expresssions in the following statements all
66799 ** have an affinity:
66800 **
66801 ** CREATE TABLE t1(a);
66802 ** SELECT * FROM t1 WHERE a;
66803 ** SELECT a AS b FROM t1 WHERE b;
66804 ** SELECT * FROM t1 WHERE (select a from t1);
66805 */
66806 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
66807   int op = pExpr->op;
66808   if( op==TK_SELECT ){
66809     assert( pExpr->flags&EP_xIsSelect );
66810     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
66811   }
66812 #ifndef SQLITE_OMIT_CAST
66813   if( op==TK_CAST ){
66814     assert( !ExprHasProperty(pExpr, EP_IntValue) );
66815     return sqlite3AffinityType(pExpr->u.zToken);
66816   }
66817 #endif
66818   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
66819    && pExpr->pTab!=0
66820   ){
66821     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
66822     ** a TK_COLUMN but was previously evaluated and cached in a register */
66823     int j = pExpr->iColumn;
66824     if( j<0 ) return SQLITE_AFF_INTEGER;
66825     assert( pExpr->pTab && j<pExpr->pTab->nCol );
66826     return pExpr->pTab->aCol[j].affinity;
66827   }
66828   return pExpr->affinity;
66829 }
66830
66831 /*
66832 ** Set the collating sequence for expression pExpr to be the collating
66833 ** sequence named by pToken.   Return a pointer to the revised expression.
66834 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
66835 ** flag.  An explicit collating sequence will override implicit
66836 ** collating sequences.
66837 */
66838 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
66839   char *zColl = 0;            /* Dequoted name of collation sequence */
66840   CollSeq *pColl;
66841   sqlite3 *db = pParse->db;
66842   zColl = sqlite3NameFromToken(db, pCollName);
66843   if( pExpr && zColl ){
66844     pColl = sqlite3LocateCollSeq(pParse, zColl);
66845     if( pColl ){
66846       pExpr->pColl = pColl;
66847       pExpr->flags |= EP_ExpCollate;
66848     }
66849   }
66850   sqlite3DbFree(db, zColl);
66851   return pExpr;
66852 }
66853
66854 /*
66855 ** Return the default collation sequence for the expression pExpr. If
66856 ** there is no default collation type, return 0.
66857 */
66858 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
66859   CollSeq *pColl = 0;
66860   Expr *p = pExpr;
66861   while( ALWAYS(p) ){
66862     int op;
66863     pColl = p->pColl;
66864     if( pColl ) break;
66865     op = p->op;
66866     if( p->pTab!=0 && (
66867         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
66868     )){
66869       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
66870       ** a TK_COLUMN but was previously evaluated and cached in a register */
66871       const char *zColl;
66872       int j = p->iColumn;
66873       if( j>=0 ){
66874         sqlite3 *db = pParse->db;
66875         zColl = p->pTab->aCol[j].zColl;
66876         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
66877         pExpr->pColl = pColl;
66878       }
66879       break;
66880     }
66881     if( op!=TK_CAST && op!=TK_UPLUS ){
66882       break;
66883     }
66884     p = p->pLeft;
66885   }
66886   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
66887     pColl = 0;
66888   }
66889   return pColl;
66890 }
66891
66892 /*
66893 ** pExpr is an operand of a comparison operator.  aff2 is the
66894 ** type affinity of the other operand.  This routine returns the
66895 ** type affinity that should be used for the comparison operator.
66896 */
66897 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
66898   char aff1 = sqlite3ExprAffinity(pExpr);
66899   if( aff1 && aff2 ){
66900     /* Both sides of the comparison are columns. If one has numeric
66901     ** affinity, use that. Otherwise use no affinity.
66902     */
66903     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
66904       return SQLITE_AFF_NUMERIC;
66905     }else{
66906       return SQLITE_AFF_NONE;
66907     }
66908   }else if( !aff1 && !aff2 ){
66909     /* Neither side of the comparison is a column.  Compare the
66910     ** results directly.
66911     */
66912     return SQLITE_AFF_NONE;
66913   }else{
66914     /* One side is a column, the other is not. Use the columns affinity. */
66915     assert( aff1==0 || aff2==0 );
66916     return (aff1 + aff2);
66917   }
66918 }
66919
66920 /*
66921 ** pExpr is a comparison operator.  Return the type affinity that should
66922 ** be applied to both operands prior to doing the comparison.
66923 */
66924 static char comparisonAffinity(Expr *pExpr){
66925   char aff;
66926   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
66927           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
66928           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
66929   assert( pExpr->pLeft );
66930   aff = sqlite3ExprAffinity(pExpr->pLeft);
66931   if( pExpr->pRight ){
66932     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
66933   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66934     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
66935   }else if( !aff ){
66936     aff = SQLITE_AFF_NONE;
66937   }
66938   return aff;
66939 }
66940
66941 /*
66942 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
66943 ** idx_affinity is the affinity of an indexed column. Return true
66944 ** if the index with affinity idx_affinity may be used to implement
66945 ** the comparison in pExpr.
66946 */
66947 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
66948   char aff = comparisonAffinity(pExpr);
66949   switch( aff ){
66950     case SQLITE_AFF_NONE:
66951       return 1;
66952     case SQLITE_AFF_TEXT:
66953       return idx_affinity==SQLITE_AFF_TEXT;
66954     default:
66955       return sqlite3IsNumericAffinity(idx_affinity);
66956   }
66957 }
66958
66959 /*
66960 ** Return the P5 value that should be used for a binary comparison
66961 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
66962 */
66963 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
66964   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
66965   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
66966   return aff;
66967 }
66968
66969 /*
66970 ** Return a pointer to the collation sequence that should be used by
66971 ** a binary comparison operator comparing pLeft and pRight.
66972 **
66973 ** If the left hand expression has a collating sequence type, then it is
66974 ** used. Otherwise the collation sequence for the right hand expression
66975 ** is used, or the default (BINARY) if neither expression has a collating
66976 ** type.
66977 **
66978 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
66979 ** it is not considered.
66980 */
66981 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
66982   Parse *pParse, 
66983   Expr *pLeft, 
66984   Expr *pRight
66985 ){
66986   CollSeq *pColl;
66987   assert( pLeft );
66988   if( pLeft->flags & EP_ExpCollate ){
66989     assert( pLeft->pColl );
66990     pColl = pLeft->pColl;
66991   }else if( pRight && pRight->flags & EP_ExpCollate ){
66992     assert( pRight->pColl );
66993     pColl = pRight->pColl;
66994   }else{
66995     pColl = sqlite3ExprCollSeq(pParse, pLeft);
66996     if( !pColl ){
66997       pColl = sqlite3ExprCollSeq(pParse, pRight);
66998     }
66999   }
67000   return pColl;
67001 }
67002
67003 /*
67004 ** Generate code for a comparison operator.
67005 */
67006 static int codeCompare(
67007   Parse *pParse,    /* The parsing (and code generating) context */
67008   Expr *pLeft,      /* The left operand */
67009   Expr *pRight,     /* The right operand */
67010   int opcode,       /* The comparison opcode */
67011   int in1, int in2, /* Register holding operands */
67012   int dest,         /* Jump here if true.  */
67013   int jumpIfNull    /* If true, jump if either operand is NULL */
67014 ){
67015   int p5;
67016   int addr;
67017   CollSeq *p4;
67018
67019   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
67020   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
67021   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
67022                            (void*)p4, P4_COLLSEQ);
67023   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
67024   return addr;
67025 }
67026
67027 #if SQLITE_MAX_EXPR_DEPTH>0
67028 /*
67029 ** Check that argument nHeight is less than or equal to the maximum
67030 ** expression depth allowed. If it is not, leave an error message in
67031 ** pParse.
67032 */
67033 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
67034   int rc = SQLITE_OK;
67035   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
67036   if( nHeight>mxHeight ){
67037     sqlite3ErrorMsg(pParse, 
67038        "Expression tree is too large (maximum depth %d)", mxHeight
67039     );
67040     rc = SQLITE_ERROR;
67041   }
67042   return rc;
67043 }
67044
67045 /* The following three functions, heightOfExpr(), heightOfExprList()
67046 ** and heightOfSelect(), are used to determine the maximum height
67047 ** of any expression tree referenced by the structure passed as the
67048 ** first argument.
67049 **
67050 ** If this maximum height is greater than the current value pointed
67051 ** to by pnHeight, the second parameter, then set *pnHeight to that
67052 ** value.
67053 */
67054 static void heightOfExpr(Expr *p, int *pnHeight){
67055   if( p ){
67056     if( p->nHeight>*pnHeight ){
67057       *pnHeight = p->nHeight;
67058     }
67059   }
67060 }
67061 static void heightOfExprList(ExprList *p, int *pnHeight){
67062   if( p ){
67063     int i;
67064     for(i=0; i<p->nExpr; i++){
67065       heightOfExpr(p->a[i].pExpr, pnHeight);
67066     }
67067   }
67068 }
67069 static void heightOfSelect(Select *p, int *pnHeight){
67070   if( p ){
67071     heightOfExpr(p->pWhere, pnHeight);
67072     heightOfExpr(p->pHaving, pnHeight);
67073     heightOfExpr(p->pLimit, pnHeight);
67074     heightOfExpr(p->pOffset, pnHeight);
67075     heightOfExprList(p->pEList, pnHeight);
67076     heightOfExprList(p->pGroupBy, pnHeight);
67077     heightOfExprList(p->pOrderBy, pnHeight);
67078     heightOfSelect(p->pPrior, pnHeight);
67079   }
67080 }
67081
67082 /*
67083 ** Set the Expr.nHeight variable in the structure passed as an 
67084 ** argument. An expression with no children, Expr.pList or 
67085 ** Expr.pSelect member has a height of 1. Any other expression
67086 ** has a height equal to the maximum height of any other 
67087 ** referenced Expr plus one.
67088 */
67089 static void exprSetHeight(Expr *p){
67090   int nHeight = 0;
67091   heightOfExpr(p->pLeft, &nHeight);
67092   heightOfExpr(p->pRight, &nHeight);
67093   if( ExprHasProperty(p, EP_xIsSelect) ){
67094     heightOfSelect(p->x.pSelect, &nHeight);
67095   }else{
67096     heightOfExprList(p->x.pList, &nHeight);
67097   }
67098   p->nHeight = nHeight + 1;
67099 }
67100
67101 /*
67102 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
67103 ** the height is greater than the maximum allowed expression depth,
67104 ** leave an error in pParse.
67105 */
67106 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
67107   exprSetHeight(p);
67108   sqlite3ExprCheckHeight(pParse, p->nHeight);
67109 }
67110
67111 /*
67112 ** Return the maximum height of any expression tree referenced
67113 ** by the select statement passed as an argument.
67114 */
67115 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
67116   int nHeight = 0;
67117   heightOfSelect(p, &nHeight);
67118   return nHeight;
67119 }
67120 #else
67121   #define exprSetHeight(y)
67122 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
67123
67124 /*
67125 ** This routine is the core allocator for Expr nodes.
67126 **
67127 ** Construct a new expression node and return a pointer to it.  Memory
67128 ** for this node and for the pToken argument is a single allocation
67129 ** obtained from sqlite3DbMalloc().  The calling function
67130 ** is responsible for making sure the node eventually gets freed.
67131 **
67132 ** If dequote is true, then the token (if it exists) is dequoted.
67133 ** If dequote is false, no dequoting is performance.  The deQuote
67134 ** parameter is ignored if pToken is NULL or if the token does not
67135 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
67136 ** then the EP_DblQuoted flag is set on the expression node.
67137 **
67138 ** Special case:  If op==TK_INTEGER and pToken points to a string that
67139 ** can be translated into a 32-bit integer, then the token is not
67140 ** stored in u.zToken.  Instead, the integer values is written
67141 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
67142 ** is allocated to hold the integer text and the dequote flag is ignored.
67143 */
67144 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
67145   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
67146   int op,                 /* Expression opcode */
67147   const Token *pToken,    /* Token argument.  Might be NULL */
67148   int dequote             /* True to dequote */
67149 ){
67150   Expr *pNew;
67151   int nExtra = 0;
67152   int iValue = 0;
67153
67154   if( pToken ){
67155     if( op!=TK_INTEGER || pToken->z==0
67156           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
67157       nExtra = pToken->n+1;
67158     }
67159   }
67160   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
67161   if( pNew ){
67162     pNew->op = (u8)op;
67163     pNew->iAgg = -1;
67164     if( pToken ){
67165       if( nExtra==0 ){
67166         pNew->flags |= EP_IntValue;
67167         pNew->u.iValue = iValue;
67168       }else{
67169         int c;
67170         pNew->u.zToken = (char*)&pNew[1];
67171         memcpy(pNew->u.zToken, pToken->z, pToken->n);
67172         pNew->u.zToken[pToken->n] = 0;
67173         if( dequote && nExtra>=3 
67174              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
67175           sqlite3Dequote(pNew->u.zToken);
67176           if( c=='"' ) pNew->flags |= EP_DblQuoted;
67177         }
67178       }
67179     }
67180 #if SQLITE_MAX_EXPR_DEPTH>0
67181     pNew->nHeight = 1;
67182 #endif  
67183   }
67184   return pNew;
67185 }
67186
67187 /*
67188 ** Allocate a new expression node from a zero-terminated token that has
67189 ** already been dequoted.
67190 */
67191 SQLITE_PRIVATE Expr *sqlite3Expr(
67192   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
67193   int op,                 /* Expression opcode */
67194   const char *zToken      /* Token argument.  Might be NULL */
67195 ){
67196   Token x;
67197   x.z = zToken;
67198   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
67199   return sqlite3ExprAlloc(db, op, &x, 0);
67200 }
67201
67202 /*
67203 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
67204 **
67205 ** If pRoot==NULL that means that a memory allocation error has occurred.
67206 ** In that case, delete the subtrees pLeft and pRight.
67207 */
67208 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
67209   sqlite3 *db,
67210   Expr *pRoot,
67211   Expr *pLeft,
67212   Expr *pRight
67213 ){
67214   if( pRoot==0 ){
67215     assert( db->mallocFailed );
67216     sqlite3ExprDelete(db, pLeft);
67217     sqlite3ExprDelete(db, pRight);
67218   }else{
67219     if( pRight ){
67220       pRoot->pRight = pRight;
67221       if( pRight->flags & EP_ExpCollate ){
67222         pRoot->flags |= EP_ExpCollate;
67223         pRoot->pColl = pRight->pColl;
67224       }
67225     }
67226     if( pLeft ){
67227       pRoot->pLeft = pLeft;
67228       if( pLeft->flags & EP_ExpCollate ){
67229         pRoot->flags |= EP_ExpCollate;
67230         pRoot->pColl = pLeft->pColl;
67231       }
67232     }
67233     exprSetHeight(pRoot);
67234   }
67235 }
67236
67237 /*
67238 ** Allocate a Expr node which joins as many as two subtrees.
67239 **
67240 ** One or both of the subtrees can be NULL.  Return a pointer to the new
67241 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
67242 ** free the subtrees and return NULL.
67243 */
67244 SQLITE_PRIVATE Expr *sqlite3PExpr(
67245   Parse *pParse,          /* Parsing context */
67246   int op,                 /* Expression opcode */
67247   Expr *pLeft,            /* Left operand */
67248   Expr *pRight,           /* Right operand */
67249   const Token *pToken     /* Argument token */
67250 ){
67251   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
67252   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
67253   return p;
67254 }
67255
67256 /*
67257 ** Join two expressions using an AND operator.  If either expression is
67258 ** NULL, then just return the other expression.
67259 */
67260 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
67261   if( pLeft==0 ){
67262     return pRight;
67263   }else if( pRight==0 ){
67264     return pLeft;
67265   }else{
67266     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
67267     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
67268     return pNew;
67269   }
67270 }
67271
67272 /*
67273 ** Construct a new expression node for a function with multiple
67274 ** arguments.
67275 */
67276 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
67277   Expr *pNew;
67278   sqlite3 *db = pParse->db;
67279   assert( pToken );
67280   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
67281   if( pNew==0 ){
67282     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
67283     return 0;
67284   }
67285   pNew->x.pList = pList;
67286   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
67287   sqlite3ExprSetHeight(pParse, pNew);
67288   return pNew;
67289 }
67290
67291 /*
67292 ** Assign a variable number to an expression that encodes a wildcard
67293 ** in the original SQL statement.  
67294 **
67295 ** Wildcards consisting of a single "?" are assigned the next sequential
67296 ** variable number.
67297 **
67298 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
67299 ** sure "nnn" is not too be to avoid a denial of service attack when
67300 ** the SQL statement comes from an external source.
67301 **
67302 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
67303 ** as the previous instance of the same wildcard.  Or if this is the first
67304 ** instance of the wildcard, the next sequenial variable number is
67305 ** assigned.
67306 */
67307 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
67308   sqlite3 *db = pParse->db;
67309   const char *z;
67310
67311   if( pExpr==0 ) return;
67312   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
67313   z = pExpr->u.zToken;
67314   assert( z!=0 );
67315   assert( z[0]!=0 );
67316   if( z[1]==0 ){
67317     /* Wildcard of the form "?".  Assign the next variable number */
67318     assert( z[0]=='?' );
67319     pExpr->iColumn = (ynVar)(++pParse->nVar);
67320   }else if( z[0]=='?' ){
67321     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
67322     ** use it as the variable number */
67323     int i = atoi((char*)&z[1]);
67324     pExpr->iColumn = (ynVar)i;
67325     testcase( i==0 );
67326     testcase( i==1 );
67327     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
67328     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
67329     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
67330       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
67331           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
67332     }
67333     if( i>pParse->nVar ){
67334       pParse->nVar = i;
67335     }
67336   }else{
67337     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
67338     ** number as the prior appearance of the same name, or if the name
67339     ** has never appeared before, reuse the same variable number
67340     */
67341     int i;
67342     u32 n;
67343     n = sqlite3Strlen30(z);
67344     for(i=0; i<pParse->nVarExpr; i++){
67345       Expr *pE = pParse->apVarExpr[i];
67346       assert( pE!=0 );
67347       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
67348         pExpr->iColumn = pE->iColumn;
67349         break;
67350       }
67351     }
67352     if( i>=pParse->nVarExpr ){
67353       pExpr->iColumn = (ynVar)(++pParse->nVar);
67354       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
67355         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
67356         pParse->apVarExpr =
67357             sqlite3DbReallocOrFree(
67358               db,
67359               pParse->apVarExpr,
67360               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
67361             );
67362       }
67363       if( !db->mallocFailed ){
67364         assert( pParse->apVarExpr!=0 );
67365         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
67366       }
67367     }
67368   } 
67369   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
67370     sqlite3ErrorMsg(pParse, "too many SQL variables");
67371   }
67372 }
67373
67374 /*
67375 ** Recursively delete an expression tree.
67376 */
67377 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
67378   if( p==0 ) return;
67379   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67380     sqlite3ExprDelete(db, p->pLeft);
67381     sqlite3ExprDelete(db, p->pRight);
67382     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
67383       sqlite3DbFree(db, p->u.zToken);
67384     }
67385     if( ExprHasProperty(p, EP_xIsSelect) ){
67386       sqlite3SelectDelete(db, p->x.pSelect);
67387     }else{
67388       sqlite3ExprListDelete(db, p->x.pList);
67389     }
67390   }
67391   if( !ExprHasProperty(p, EP_Static) ){
67392     sqlite3DbFree(db, p);
67393   }
67394 }
67395
67396 /*
67397 ** Return the number of bytes allocated for the expression structure 
67398 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
67399 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
67400 */
67401 static int exprStructSize(Expr *p){
67402   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
67403   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
67404   return EXPR_FULLSIZE;
67405 }
67406
67407 /*
67408 ** The dupedExpr*Size() routines each return the number of bytes required
67409 ** to store a copy of an expression or expression tree.  They differ in
67410 ** how much of the tree is measured.
67411 **
67412 **     dupedExprStructSize()     Size of only the Expr structure 
67413 **     dupedExprNodeSize()       Size of Expr + space for token
67414 **     dupedExprSize()           Expr + token + subtree components
67415 **
67416 ***************************************************************************
67417 **
67418 ** The dupedExprStructSize() function returns two values OR-ed together:  
67419 ** (1) the space required for a copy of the Expr structure only and 
67420 ** (2) the EP_xxx flags that indicate what the structure size should be.
67421 ** The return values is always one of:
67422 **
67423 **      EXPR_FULLSIZE
67424 **      EXPR_REDUCEDSIZE   | EP_Reduced
67425 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
67426 **
67427 ** The size of the structure can be found by masking the return value
67428 ** of this routine with 0xfff.  The flags can be found by masking the
67429 ** return value with EP_Reduced|EP_TokenOnly.
67430 **
67431 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
67432 ** (unreduced) Expr objects as they or originally constructed by the parser.
67433 ** During expression analysis, extra information is computed and moved into
67434 ** later parts of teh Expr object and that extra information might get chopped
67435 ** off if the expression is reduced.  Note also that it does not work to
67436 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
67437 ** to reduce a pristine expression tree from the parser.  The implementation
67438 ** of dupedExprStructSize() contain multiple assert() statements that attempt
67439 ** to enforce this constraint.
67440 */
67441 static int dupedExprStructSize(Expr *p, int flags){
67442   int nSize;
67443   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
67444   if( 0==(flags&EXPRDUP_REDUCE) ){
67445     nSize = EXPR_FULLSIZE;
67446   }else{
67447     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
67448     assert( !ExprHasProperty(p, EP_FromJoin) ); 
67449     assert( (p->flags2 & EP2_MallocedToken)==0 );
67450     assert( (p->flags2 & EP2_Irreducible)==0 );
67451     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
67452       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
67453     }else{
67454       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
67455     }
67456   }
67457   return nSize;
67458 }
67459
67460 /*
67461 ** This function returns the space in bytes required to store the copy 
67462 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
67463 ** string is defined.)
67464 */
67465 static int dupedExprNodeSize(Expr *p, int flags){
67466   int nByte = dupedExprStructSize(p, flags) & 0xfff;
67467   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67468     nByte += sqlite3Strlen30(p->u.zToken)+1;
67469   }
67470   return ROUND8(nByte);
67471 }
67472
67473 /*
67474 ** Return the number of bytes required to create a duplicate of the 
67475 ** expression passed as the first argument. The second argument is a
67476 ** mask containing EXPRDUP_XXX flags.
67477 **
67478 ** The value returned includes space to create a copy of the Expr struct
67479 ** itself and the buffer referred to by Expr.u.zToken, if any.
67480 **
67481 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
67482 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
67483 ** and Expr.pRight variables (but not for any structures pointed to or 
67484 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
67485 */
67486 static int dupedExprSize(Expr *p, int flags){
67487   int nByte = 0;
67488   if( p ){
67489     nByte = dupedExprNodeSize(p, flags);
67490     if( flags&EXPRDUP_REDUCE ){
67491       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
67492     }
67493   }
67494   return nByte;
67495 }
67496
67497 /*
67498 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
67499 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
67500 ** to store the copy of expression p, the copies of p->u.zToken
67501 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
67502 ** if any. Before returning, *pzBuffer is set to the first byte passed the
67503 ** portion of the buffer copied into by this function.
67504 */
67505 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
67506   Expr *pNew = 0;                      /* Value to return */
67507   if( p ){
67508     const int isReduced = (flags&EXPRDUP_REDUCE);
67509     u8 *zAlloc;
67510     u32 staticFlag = 0;
67511
67512     assert( pzBuffer==0 || isReduced );
67513
67514     /* Figure out where to write the new Expr structure. */
67515     if( pzBuffer ){
67516       zAlloc = *pzBuffer;
67517       staticFlag = EP_Static;
67518     }else{
67519       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
67520     }
67521     pNew = (Expr *)zAlloc;
67522
67523     if( pNew ){
67524       /* Set nNewSize to the size allocated for the structure pointed to
67525       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
67526       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
67527       ** by the copy of the p->u.zToken string (if any).
67528       */
67529       const unsigned nStructSize = dupedExprStructSize(p, flags);
67530       const int nNewSize = nStructSize & 0xfff;
67531       int nToken;
67532       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67533         nToken = sqlite3Strlen30(p->u.zToken) + 1;
67534       }else{
67535         nToken = 0;
67536       }
67537       if( isReduced ){
67538         assert( ExprHasProperty(p, EP_Reduced)==0 );
67539         memcpy(zAlloc, p, nNewSize);
67540       }else{
67541         int nSize = exprStructSize(p);
67542         memcpy(zAlloc, p, nSize);
67543         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
67544       }
67545
67546       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
67547       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
67548       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
67549       pNew->flags |= staticFlag;
67550
67551       /* Copy the p->u.zToken string, if any. */
67552       if( nToken ){
67553         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
67554         memcpy(zToken, p->u.zToken, nToken);
67555       }
67556
67557       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
67558         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
67559         if( ExprHasProperty(p, EP_xIsSelect) ){
67560           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
67561         }else{
67562           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
67563         }
67564       }
67565
67566       /* Fill in pNew->pLeft and pNew->pRight. */
67567       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
67568         zAlloc += dupedExprNodeSize(p, flags);
67569         if( ExprHasProperty(pNew, EP_Reduced) ){
67570           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
67571           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
67572         }
67573         if( pzBuffer ){
67574           *pzBuffer = zAlloc;
67575         }
67576       }else{
67577         pNew->flags2 = 0;
67578         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67579           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
67580           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
67581         }
67582       }
67583
67584     }
67585   }
67586   return pNew;
67587 }
67588
67589 /*
67590 ** The following group of routines make deep copies of expressions,
67591 ** expression lists, ID lists, and select statements.  The copies can
67592 ** be deleted (by being passed to their respective ...Delete() routines)
67593 ** without effecting the originals.
67594 **
67595 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
67596 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
67597 ** by subsequent calls to sqlite*ListAppend() routines.
67598 **
67599 ** Any tables that the SrcList might point to are not duplicated.
67600 **
67601 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
67602 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
67603 ** truncated version of the usual Expr structure that will be stored as
67604 ** part of the in-memory representation of the database schema.
67605 */
67606 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
67607   return exprDup(db, p, flags, 0);
67608 }
67609 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
67610   ExprList *pNew;
67611   struct ExprList_item *pItem, *pOldItem;
67612   int i;
67613   if( p==0 ) return 0;
67614   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67615   if( pNew==0 ) return 0;
67616   pNew->iECursor = 0;
67617   pNew->nExpr = pNew->nAlloc = p->nExpr;
67618   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
67619   if( pItem==0 ){
67620     sqlite3DbFree(db, pNew);
67621     return 0;
67622   } 
67623   pOldItem = p->a;
67624   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
67625     Expr *pOldExpr = pOldItem->pExpr;
67626     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
67627     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67628     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
67629     pItem->sortOrder = pOldItem->sortOrder;
67630     pItem->done = 0;
67631     pItem->iCol = pOldItem->iCol;
67632     pItem->iAlias = pOldItem->iAlias;
67633   }
67634   return pNew;
67635 }
67636
67637 /*
67638 ** If cursors, triggers, views and subqueries are all omitted from
67639 ** the build, then none of the following routines, except for 
67640 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
67641 ** called with a NULL argument.
67642 */
67643 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
67644  || !defined(SQLITE_OMIT_SUBQUERY)
67645 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
67646   SrcList *pNew;
67647   int i;
67648   int nByte;
67649   if( p==0 ) return 0;
67650   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
67651   pNew = sqlite3DbMallocRaw(db, nByte );
67652   if( pNew==0 ) return 0;
67653   pNew->nSrc = pNew->nAlloc = p->nSrc;
67654   for(i=0; i<p->nSrc; i++){
67655     struct SrcList_item *pNewItem = &pNew->a[i];
67656     struct SrcList_item *pOldItem = &p->a[i];
67657     Table *pTab;
67658     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
67659     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67660     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
67661     pNewItem->jointype = pOldItem->jointype;
67662     pNewItem->iCursor = pOldItem->iCursor;
67663     pNewItem->isPopulated = pOldItem->isPopulated;
67664     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
67665     pNewItem->notIndexed = pOldItem->notIndexed;
67666     pNewItem->pIndex = pOldItem->pIndex;
67667     pTab = pNewItem->pTab = pOldItem->pTab;
67668     if( pTab ){
67669       pTab->nRef++;
67670     }
67671     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
67672     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
67673     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
67674     pNewItem->colUsed = pOldItem->colUsed;
67675   }
67676   return pNew;
67677 }
67678 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
67679   IdList *pNew;
67680   int i;
67681   if( p==0 ) return 0;
67682   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67683   if( pNew==0 ) return 0;
67684   pNew->nId = pNew->nAlloc = p->nId;
67685   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
67686   if( pNew->a==0 ){
67687     sqlite3DbFree(db, pNew);
67688     return 0;
67689   }
67690   for(i=0; i<p->nId; i++){
67691     struct IdList_item *pNewItem = &pNew->a[i];
67692     struct IdList_item *pOldItem = &p->a[i];
67693     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67694     pNewItem->idx = pOldItem->idx;
67695   }
67696   return pNew;
67697 }
67698 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67699   Select *pNew;
67700   if( p==0 ) return 0;
67701   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
67702   if( pNew==0 ) return 0;
67703   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
67704   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
67705   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
67706   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
67707   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
67708   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
67709   pNew->op = p->op;
67710   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
67711   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
67712   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
67713   pNew->iLimit = 0;
67714   pNew->iOffset = 0;
67715   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
67716   pNew->pRightmost = 0;
67717   pNew->addrOpenEphm[0] = -1;
67718   pNew->addrOpenEphm[1] = -1;
67719   pNew->addrOpenEphm[2] = -1;
67720   return pNew;
67721 }
67722 #else
67723 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67724   assert( p==0 );
67725   return 0;
67726 }
67727 #endif
67728
67729
67730 /*
67731 ** Add a new element to the end of an expression list.  If pList is
67732 ** initially NULL, then create a new expression list.
67733 **
67734 ** If a memory allocation error occurs, the entire list is freed and
67735 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
67736 ** that the new entry was successfully appended.
67737 */
67738 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
67739   Parse *pParse,          /* Parsing context */
67740   ExprList *pList,        /* List to which to append. Might be NULL */
67741   Expr *pExpr             /* Expression to be appended. Might be NULL */
67742 ){
67743   sqlite3 *db = pParse->db;
67744   if( pList==0 ){
67745     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
67746     if( pList==0 ){
67747       goto no_mem;
67748     }
67749     assert( pList->nAlloc==0 );
67750   }
67751   if( pList->nAlloc<=pList->nExpr ){
67752     struct ExprList_item *a;
67753     int n = pList->nAlloc*2 + 4;
67754     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
67755     if( a==0 ){
67756       goto no_mem;
67757     }
67758     pList->a = a;
67759     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
67760   }
67761   assert( pList->a!=0 );
67762   if( 1 ){
67763     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
67764     memset(pItem, 0, sizeof(*pItem));
67765     pItem->pExpr = pExpr;
67766   }
67767   return pList;
67768
67769 no_mem:     
67770   /* Avoid leaking memory if malloc has failed. */
67771   sqlite3ExprDelete(db, pExpr);
67772   sqlite3ExprListDelete(db, pList);
67773   return 0;
67774 }
67775
67776 /*
67777 ** Set the ExprList.a[].zName element of the most recently added item
67778 ** on the expression list.
67779 **
67780 ** pList might be NULL following an OOM error.  But pName should never be
67781 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67782 ** is set.
67783 */
67784 SQLITE_PRIVATE void sqlite3ExprListSetName(
67785   Parse *pParse,          /* Parsing context */
67786   ExprList *pList,        /* List to which to add the span. */
67787   Token *pName,           /* Name to be added */
67788   int dequote             /* True to cause the name to be dequoted */
67789 ){
67790   assert( pList!=0 || pParse->db->mallocFailed!=0 );
67791   if( pList ){
67792     struct ExprList_item *pItem;
67793     assert( pList->nExpr>0 );
67794     pItem = &pList->a[pList->nExpr-1];
67795     assert( pItem->zName==0 );
67796     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
67797     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
67798   }
67799 }
67800
67801 /*
67802 ** Set the ExprList.a[].zSpan element of the most recently added item
67803 ** on the expression list.
67804 **
67805 ** pList might be NULL following an OOM error.  But pSpan should never be
67806 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67807 ** is set.
67808 */
67809 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
67810   Parse *pParse,          /* Parsing context */
67811   ExprList *pList,        /* List to which to add the span. */
67812   ExprSpan *pSpan         /* The span to be added */
67813 ){
67814   sqlite3 *db = pParse->db;
67815   assert( pList!=0 || db->mallocFailed!=0 );
67816   if( pList ){
67817     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
67818     assert( pList->nExpr>0 );
67819     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
67820     sqlite3DbFree(db, pItem->zSpan);
67821     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67822                                     (int)(pSpan->zEnd - pSpan->zStart));
67823   }
67824 }
67825
67826 /*
67827 ** If the expression list pEList contains more than iLimit elements,
67828 ** leave an error message in pParse.
67829 */
67830 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
67831   Parse *pParse,
67832   ExprList *pEList,
67833   const char *zObject
67834 ){
67835   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
67836   testcase( pEList && pEList->nExpr==mx );
67837   testcase( pEList && pEList->nExpr==mx+1 );
67838   if( pEList && pEList->nExpr>mx ){
67839     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
67840   }
67841 }
67842
67843 /*
67844 ** Delete an entire expression list.
67845 */
67846 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
67847   int i;
67848   struct ExprList_item *pItem;
67849   if( pList==0 ) return;
67850   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
67851   assert( pList->nExpr<=pList->nAlloc );
67852   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
67853     sqlite3ExprDelete(db, pItem->pExpr);
67854     sqlite3DbFree(db, pItem->zName);
67855     sqlite3DbFree(db, pItem->zSpan);
67856   }
67857   sqlite3DbFree(db, pList->a);
67858   sqlite3DbFree(db, pList);
67859 }
67860
67861 /*
67862 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
67863 ** to an integer.  These routines are checking an expression to see
67864 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
67865 ** not constant.
67866 **
67867 ** These callback routines are used to implement the following:
67868 **
67869 **     sqlite3ExprIsConstant()
67870 **     sqlite3ExprIsConstantNotJoin()
67871 **     sqlite3ExprIsConstantOrFunction()
67872 **
67873 */
67874 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
67875
67876   /* If pWalker->u.i is 3 then any term of the expression that comes from
67877   ** the ON or USING clauses of a join disqualifies the expression
67878   ** from being considered constant. */
67879   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
67880     pWalker->u.i = 0;
67881     return WRC_Abort;
67882   }
67883
67884   switch( pExpr->op ){
67885     /* Consider functions to be constant if all their arguments are constant
67886     ** and pWalker->u.i==2 */
67887     case TK_FUNCTION:
67888       if( pWalker->u.i==2 ) return 0;
67889       /* Fall through */
67890     case TK_ID:
67891     case TK_COLUMN:
67892     case TK_AGG_FUNCTION:
67893     case TK_AGG_COLUMN:
67894       testcase( pExpr->op==TK_ID );
67895       testcase( pExpr->op==TK_COLUMN );
67896       testcase( pExpr->op==TK_AGG_FUNCTION );
67897       testcase( pExpr->op==TK_AGG_COLUMN );
67898       pWalker->u.i = 0;
67899       return WRC_Abort;
67900     default:
67901       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
67902       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
67903       return WRC_Continue;
67904   }
67905 }
67906 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
67907   UNUSED_PARAMETER(NotUsed);
67908   pWalker->u.i = 0;
67909   return WRC_Abort;
67910 }
67911 static int exprIsConst(Expr *p, int initFlag){
67912   Walker w;
67913   w.u.i = initFlag;
67914   w.xExprCallback = exprNodeIsConstant;
67915   w.xSelectCallback = selectNodeIsConstant;
67916   sqlite3WalkExpr(&w, p);
67917   return w.u.i;
67918 }
67919
67920 /*
67921 ** Walk an expression tree.  Return 1 if the expression is constant
67922 ** and 0 if it involves variables or function calls.
67923 **
67924 ** For the purposes of this function, a double-quoted string (ex: "abc")
67925 ** is considered a variable but a single-quoted string (ex: 'abc') is
67926 ** a constant.
67927 */
67928 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
67929   return exprIsConst(p, 1);
67930 }
67931
67932 /*
67933 ** Walk an expression tree.  Return 1 if the expression is constant
67934 ** that does no originate from the ON or USING clauses of a join.
67935 ** Return 0 if it involves variables or function calls or terms from
67936 ** an ON or USING clause.
67937 */
67938 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
67939   return exprIsConst(p, 3);
67940 }
67941
67942 /*
67943 ** Walk an expression tree.  Return 1 if the expression is constant
67944 ** or a function call with constant arguments.  Return and 0 if there
67945 ** are any variables.
67946 **
67947 ** For the purposes of this function, a double-quoted string (ex: "abc")
67948 ** is considered a variable but a single-quoted string (ex: 'abc') is
67949 ** a constant.
67950 */
67951 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
67952   return exprIsConst(p, 2);
67953 }
67954
67955 /*
67956 ** If the expression p codes a constant integer that is small enough
67957 ** to fit in a 32-bit integer, return 1 and put the value of the integer
67958 ** in *pValue.  If the expression is not an integer or if it is too big
67959 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
67960 */
67961 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
67962   int rc = 0;
67963   if( p->flags & EP_IntValue ){
67964     *pValue = p->u.iValue;
67965     return 1;
67966   }
67967   switch( p->op ){
67968     case TK_INTEGER: {
67969       rc = sqlite3GetInt32(p->u.zToken, pValue);
67970       assert( rc==0 );
67971       break;
67972     }
67973     case TK_UPLUS: {
67974       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
67975       break;
67976     }
67977     case TK_UMINUS: {
67978       int v;
67979       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
67980         *pValue = -v;
67981         rc = 1;
67982       }
67983       break;
67984     }
67985     default: break;
67986   }
67987   if( rc ){
67988     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
67989                || (p->flags2 & EP2_MallocedToken)==0 );
67990     p->op = TK_INTEGER;
67991     p->flags |= EP_IntValue;
67992     p->u.iValue = *pValue;
67993   }
67994   return rc;
67995 }
67996
67997 /*
67998 ** Return FALSE if there is no chance that the expression can be NULL.
67999 **
68000 ** If the expression might be NULL or if the expression is too complex
68001 ** to tell return TRUE.  
68002 **
68003 ** This routine is used as an optimization, to skip OP_IsNull opcodes
68004 ** when we know that a value cannot be NULL.  Hence, a false positive
68005 ** (returning TRUE when in fact the expression can never be NULL) might
68006 ** be a small performance hit but is otherwise harmless.  On the other
68007 ** hand, a false negative (returning FALSE when the result could be NULL)
68008 ** will likely result in an incorrect answer.  So when in doubt, return
68009 ** TRUE.
68010 */
68011 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
68012   u8 op;
68013   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68014   op = p->op;
68015   if( op==TK_REGISTER ) op = p->op2;
68016   switch( op ){
68017     case TK_INTEGER:
68018     case TK_STRING:
68019     case TK_FLOAT:
68020     case TK_BLOB:
68021       return 0;
68022     default:
68023       return 1;
68024   }
68025 }
68026
68027 /*
68028 ** Generate an OP_IsNull instruction that tests register iReg and jumps
68029 ** to location iDest if the value in iReg is NULL.  The value in iReg 
68030 ** was computed by pExpr.  If we can look at pExpr at compile-time and
68031 ** determine that it can never generate a NULL, then the OP_IsNull operation
68032 ** can be omitted.
68033 */
68034 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
68035   Vdbe *v,            /* The VDBE under construction */
68036   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
68037   int iReg,           /* Test the value in this register for NULL */
68038   int iDest           /* Jump here if the value is null */
68039 ){
68040   if( sqlite3ExprCanBeNull(pExpr) ){
68041     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
68042   }
68043 }
68044
68045 /*
68046 ** Return TRUE if the given expression is a constant which would be
68047 ** unchanged by OP_Affinity with the affinity given in the second
68048 ** argument.
68049 **
68050 ** This routine is used to determine if the OP_Affinity operation
68051 ** can be omitted.  When in doubt return FALSE.  A false negative
68052 ** is harmless.  A false positive, however, can result in the wrong
68053 ** answer.
68054 */
68055 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
68056   u8 op;
68057   if( aff==SQLITE_AFF_NONE ) return 1;
68058   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68059   op = p->op;
68060   if( op==TK_REGISTER ) op = p->op2;
68061   switch( op ){
68062     case TK_INTEGER: {
68063       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
68064     }
68065     case TK_FLOAT: {
68066       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
68067     }
68068     case TK_STRING: {
68069       return aff==SQLITE_AFF_TEXT;
68070     }
68071     case TK_BLOB: {
68072       return 1;
68073     }
68074     case TK_COLUMN: {
68075       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
68076       return p->iColumn<0
68077           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
68078     }
68079     default: {
68080       return 0;
68081     }
68082   }
68083 }
68084
68085 /*
68086 ** Return TRUE if the given string is a row-id column name.
68087 */
68088 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
68089   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
68090   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
68091   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
68092   return 0;
68093 }
68094
68095 /*
68096 ** Return true if we are able to the IN operator optimization on a
68097 ** query of the form
68098 **
68099 **       x IN (SELECT ...)
68100 **
68101 ** Where the SELECT... clause is as specified by the parameter to this
68102 ** routine.
68103 **
68104 ** The Select object passed in has already been preprocessed and no
68105 ** errors have been found.
68106 */
68107 #ifndef SQLITE_OMIT_SUBQUERY
68108 static int isCandidateForInOpt(Select *p){
68109   SrcList *pSrc;
68110   ExprList *pEList;
68111   Table *pTab;
68112   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
68113   if( p->pPrior ) return 0;              /* Not a compound SELECT */
68114   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
68115     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
68116     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
68117     return 0; /* No DISTINCT keyword and no aggregate functions */
68118   }
68119   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
68120   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
68121   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
68122   if( p->pWhere ) return 0;              /* Has no WHERE clause */
68123   pSrc = p->pSrc;
68124   assert( pSrc!=0 );
68125   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
68126   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
68127   pTab = pSrc->a[0].pTab;
68128   if( NEVER(pTab==0) ) return 0;
68129   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
68130   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
68131   pEList = p->pEList;
68132   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
68133   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
68134   return 1;
68135 }
68136 #endif /* SQLITE_OMIT_SUBQUERY */
68137
68138 /*
68139 ** This function is used by the implementation of the IN (...) operator.
68140 ** It's job is to find or create a b-tree structure that may be used
68141 ** either to test for membership of the (...) set or to iterate through
68142 ** its members, skipping duplicates.
68143 **
68144 ** The index of the cursor opened on the b-tree (database table, database index 
68145 ** or ephermal table) is stored in pX->iTable before this function returns.
68146 ** The returned value of this function indicates the b-tree type, as follows:
68147 **
68148 **   IN_INDEX_ROWID - The cursor was opened on a database table.
68149 **   IN_INDEX_INDEX - The cursor was opened on a database index.
68150 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
68151 **                    populated epheremal table.
68152 **
68153 ** An existing b-tree may only be used if the SELECT is of the simple
68154 ** form:
68155 **
68156 **     SELECT <column> FROM <table>
68157 **
68158 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
68159 ** through the set members, skipping any duplicates. In this case an
68160 ** epheremal table must be used unless the selected <column> is guaranteed
68161 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
68162 ** has a UNIQUE constraint or UNIQUE index.
68163 **
68164 ** If the prNotFound parameter is not 0, then the b-tree will be used 
68165 ** for fast set membership tests. In this case an epheremal table must 
68166 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
68167 ** be found with <column> as its left-most column.
68168 **
68169 ** When the b-tree is being used for membership tests, the calling function
68170 ** needs to know whether or not the structure contains an SQL NULL 
68171 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
68172 ** If there is any chance that the (...) might contain a NULL value at
68173 ** runtime, then a register is allocated and the register number written
68174 ** to *prNotFound. If there is no chance that the (...) contains a
68175 ** NULL value, then *prNotFound is left unchanged.
68176 **
68177 ** If a register is allocated and its location stored in *prNotFound, then
68178 ** its initial value is NULL.  If the (...) does not remain constant
68179 ** for the duration of the query (i.e. the SELECT within the (...)
68180 ** is a correlated subquery) then the value of the allocated register is
68181 ** reset to NULL each time the subquery is rerun. This allows the
68182 ** caller to use vdbe code equivalent to the following:
68183 **
68184 **   if( register==NULL ){
68185 **     has_null = <test if data structure contains null>
68186 **     register = 1
68187 **   }
68188 **
68189 ** in order to avoid running the <test if data structure contains null>
68190 ** test more often than is necessary.
68191 */
68192 #ifndef SQLITE_OMIT_SUBQUERY
68193 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
68194   Select *p;                            /* SELECT to the right of IN operator */
68195   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
68196   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
68197   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
68198
68199   assert( pX->op==TK_IN );
68200
68201   /* Check to see if an existing table or index can be used to
68202   ** satisfy the query.  This is preferable to generating a new 
68203   ** ephemeral table.
68204   */
68205   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
68206   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
68207     sqlite3 *db = pParse->db;              /* Database connection */
68208     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
68209     int iCol = pExpr->iColumn;             /* Index of column <column> */
68210     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
68211     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
68212     int iDb;                               /* Database idx for pTab */
68213    
68214     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
68215     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68216     sqlite3CodeVerifySchema(pParse, iDb);
68217     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
68218
68219     /* This function is only called from two places. In both cases the vdbe
68220     ** has already been allocated. So assume sqlite3GetVdbe() is always
68221     ** successful here.
68222     */
68223     assert(v);
68224     if( iCol<0 ){
68225       int iMem = ++pParse->nMem;
68226       int iAddr;
68227
68228       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
68229       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
68230
68231       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68232       eType = IN_INDEX_ROWID;
68233
68234       sqlite3VdbeJumpHere(v, iAddr);
68235     }else{
68236       Index *pIdx;                         /* Iterator variable */
68237
68238       /* The collation sequence used by the comparison. If an index is to
68239       ** be used in place of a temp-table, it must be ordered according
68240       ** to this collation sequence.  */
68241       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
68242
68243       /* Check that the affinity that will be used to perform the 
68244       ** comparison is the same as the affinity of the column. If
68245       ** it is not, it is not possible to use any index.
68246       */
68247       char aff = comparisonAffinity(pX);
68248       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
68249
68250       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
68251         if( (pIdx->aiColumn[0]==iCol)
68252          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
68253          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
68254         ){
68255           int iMem = ++pParse->nMem;
68256           int iAddr;
68257           char *pKey;
68258   
68259           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
68260           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
68261           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
68262   
68263           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
68264                                pKey,P4_KEYINFO_HANDOFF);
68265           VdbeComment((v, "%s", pIdx->zName));
68266           eType = IN_INDEX_INDEX;
68267
68268           sqlite3VdbeJumpHere(v, iAddr);
68269           if( prNotFound && !pTab->aCol[iCol].notNull ){
68270             *prNotFound = ++pParse->nMem;
68271           }
68272         }
68273       }
68274     }
68275   }
68276
68277   if( eType==0 ){
68278     /* Could not found an existing table or index to use as the RHS b-tree.
68279     ** We will have to generate an ephemeral table to do the job.
68280     */
68281     double savedNQueryLoop = pParse->nQueryLoop;
68282     int rMayHaveNull = 0;
68283     eType = IN_INDEX_EPH;
68284     if( prNotFound ){
68285       *prNotFound = rMayHaveNull = ++pParse->nMem;
68286     }else{
68287       testcase( pParse->nQueryLoop>(double)1 );
68288       pParse->nQueryLoop = (double)1;
68289       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
68290         eType = IN_INDEX_ROWID;
68291       }
68292     }
68293     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
68294     pParse->nQueryLoop = savedNQueryLoop;
68295   }else{
68296     pX->iTable = iTab;
68297   }
68298   return eType;
68299 }
68300 #endif
68301
68302 /*
68303 ** Generate code for scalar subqueries used as an expression
68304 ** and IN operators.  Examples:
68305 **
68306 **     (SELECT a FROM b)          -- subquery
68307 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
68308 **     x IN (4,5,11)              -- IN operator with list on right-hand side
68309 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
68310 **
68311 ** The pExpr parameter describes the expression that contains the IN
68312 ** operator or subquery.
68313 **
68314 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
68315 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
68316 ** to some integer key column of a table B-Tree. In this case, use an
68317 ** intkey B-Tree to store the set of IN(...) values instead of the usual
68318 ** (slower) variable length keys B-Tree.
68319 **
68320 ** If rMayHaveNull is non-zero, that means that the operation is an IN
68321 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
68322 ** Furthermore, the IN is in a WHERE clause and that we really want
68323 ** to iterate over the RHS of the IN operator in order to quickly locate
68324 ** all corresponding LHS elements.  All this routine does is initialize
68325 ** the register given by rMayHaveNull to NULL.  Calling routines will take
68326 ** care of changing this register value to non-NULL if the RHS is NULL-free.
68327 **
68328 ** If rMayHaveNull is zero, that means that the subquery is being used
68329 ** for membership testing only.  There is no need to initialize any
68330 ** registers to indicate the presense or absence of NULLs on the RHS.
68331 **
68332 ** For a SELECT or EXISTS operator, return the register that holds the
68333 ** result.  For IN operators or if an error occurs, the return value is 0.
68334 */
68335 #ifndef SQLITE_OMIT_SUBQUERY
68336 SQLITE_PRIVATE int sqlite3CodeSubselect(
68337   Parse *pParse,          /* Parsing context */
68338   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
68339   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
68340   int isRowid             /* If true, LHS of IN operator is a rowid */
68341 ){
68342   int testAddr = 0;                       /* One-time test address */
68343   int rReg = 0;                           /* Register storing resulting */
68344   Vdbe *v = sqlite3GetVdbe(pParse);
68345   if( NEVER(v==0) ) return 0;
68346   sqlite3ExprCachePush(pParse);
68347
68348   /* This code must be run in its entirety every time it is encountered
68349   ** if any of the following is true:
68350   **
68351   **    *  The right-hand side is a correlated subquery
68352   **    *  The right-hand side is an expression list containing variables
68353   **    *  We are inside a trigger
68354   **
68355   ** If all of the above are false, then we can run this code just once
68356   ** save the results, and reuse the same result on subsequent invocations.
68357   */
68358   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
68359     int mem = ++pParse->nMem;
68360     sqlite3VdbeAddOp1(v, OP_If, mem);
68361     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
68362     assert( testAddr>0 || pParse->db->mallocFailed );
68363   }
68364
68365   switch( pExpr->op ){
68366     case TK_IN: {
68367       char affinity;
68368       KeyInfo keyInfo;
68369       int addr;        /* Address of OP_OpenEphemeral instruction */
68370       Expr *pLeft = pExpr->pLeft;
68371
68372       if( rMayHaveNull ){
68373         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
68374       }
68375
68376       affinity = sqlite3ExprAffinity(pLeft);
68377
68378       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
68379       ** expression it is handled the same way.  An ephemeral table is 
68380       ** filled with single-field index keys representing the results
68381       ** from the SELECT or the <exprlist>.
68382       **
68383       ** If the 'x' expression is a column value, or the SELECT...
68384       ** statement returns a column value, then the affinity of that
68385       ** column is used to build the index keys. If both 'x' and the
68386       ** SELECT... statement are columns, then numeric affinity is used
68387       ** if either column has NUMERIC or INTEGER affinity. If neither
68388       ** 'x' nor the SELECT... statement are columns, then numeric affinity
68389       ** is used.
68390       */
68391       pExpr->iTable = pParse->nTab++;
68392       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
68393       memset(&keyInfo, 0, sizeof(keyInfo));
68394       keyInfo.nField = 1;
68395
68396       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68397         /* Case 1:     expr IN (SELECT ...)
68398         **
68399         ** Generate code to write the results of the select into the temporary
68400         ** table allocated and opened above.
68401         */
68402         SelectDest dest;
68403         ExprList *pEList;
68404
68405         assert( !isRowid );
68406         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
68407         dest.affinity = (u8)affinity;
68408         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
68409         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
68410           return 0;
68411         }
68412         pEList = pExpr->x.pSelect->pEList;
68413         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
68414           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
68415               pEList->a[0].pExpr);
68416         }
68417       }else if( ALWAYS(pExpr->x.pList!=0) ){
68418         /* Case 2:     expr IN (exprlist)
68419         **
68420         ** For each expression, build an index key from the evaluation and
68421         ** store it in the temporary table. If <expr> is a column, then use
68422         ** that columns affinity when building index keys. If <expr> is not
68423         ** a column, use numeric affinity.
68424         */
68425         int i;
68426         ExprList *pList = pExpr->x.pList;
68427         struct ExprList_item *pItem;
68428         int r1, r2, r3;
68429
68430         if( !affinity ){
68431           affinity = SQLITE_AFF_NONE;
68432         }
68433         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
68434
68435         /* Loop through each expression in <exprlist>. */
68436         r1 = sqlite3GetTempReg(pParse);
68437         r2 = sqlite3GetTempReg(pParse);
68438         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
68439         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
68440           Expr *pE2 = pItem->pExpr;
68441           int iValToIns;
68442
68443           /* If the expression is not constant then we will need to
68444           ** disable the test that was generated above that makes sure
68445           ** this code only executes once.  Because for a non-constant
68446           ** expression we need to rerun this code each time.
68447           */
68448           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
68449             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
68450             testAddr = 0;
68451           }
68452
68453           /* Evaluate the expression and insert it into the temp table */
68454           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
68455             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
68456           }else{
68457             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
68458             if( isRowid ){
68459               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
68460                                 sqlite3VdbeCurrentAddr(v)+2);
68461               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
68462             }else{
68463               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
68464               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
68465               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
68466             }
68467           }
68468         }
68469         sqlite3ReleaseTempReg(pParse, r1);
68470         sqlite3ReleaseTempReg(pParse, r2);
68471       }
68472       if( !isRowid ){
68473         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
68474       }
68475       break;
68476     }
68477
68478     case TK_EXISTS:
68479     case TK_SELECT:
68480     default: {
68481       /* If this has to be a scalar SELECT.  Generate code to put the
68482       ** value of this select in a memory cell and record the number
68483       ** of the memory cell in iColumn.  If this is an EXISTS, write
68484       ** an integer 0 (not exists) or 1 (exists) into a memory cell
68485       ** and record that memory cell in iColumn.
68486       */
68487       Select *pSel;                         /* SELECT statement to encode */
68488       SelectDest dest;                      /* How to deal with SELECt result */
68489
68490       testcase( pExpr->op==TK_EXISTS );
68491       testcase( pExpr->op==TK_SELECT );
68492       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
68493
68494       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
68495       pSel = pExpr->x.pSelect;
68496       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
68497       if( pExpr->op==TK_SELECT ){
68498         dest.eDest = SRT_Mem;
68499         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
68500         VdbeComment((v, "Init subquery result"));
68501       }else{
68502         dest.eDest = SRT_Exists;
68503         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
68504         VdbeComment((v, "Init EXISTS result"));
68505       }
68506       sqlite3ExprDelete(pParse->db, pSel->pLimit);
68507       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
68508                                   &sqlite3IntTokens[1]);
68509       if( sqlite3Select(pParse, pSel, &dest) ){
68510         return 0;
68511       }
68512       rReg = dest.iParm;
68513       ExprSetIrreducible(pExpr);
68514       break;
68515     }
68516   }
68517
68518   if( testAddr ){
68519     sqlite3VdbeJumpHere(v, testAddr-1);
68520   }
68521   sqlite3ExprCachePop(pParse, 1);
68522
68523   return rReg;
68524 }
68525 #endif /* SQLITE_OMIT_SUBQUERY */
68526
68527 #ifndef SQLITE_OMIT_SUBQUERY
68528 /*
68529 ** Generate code for an IN expression.
68530 **
68531 **      x IN (SELECT ...)
68532 **      x IN (value, value, ...)
68533 **
68534 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
68535 ** is an array of zero or more values.  The expression is true if the LHS is
68536 ** contained within the RHS.  The value of the expression is unknown (NULL)
68537 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
68538 ** RHS contains one or more NULL values.
68539 **
68540 ** This routine generates code will jump to destIfFalse if the LHS is not 
68541 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
68542 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
68543 ** within the RHS then fall through.
68544 */
68545 static void sqlite3ExprCodeIN(
68546   Parse *pParse,        /* Parsing and code generating context */
68547   Expr *pExpr,          /* The IN expression */
68548   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
68549   int destIfNull        /* Jump here if the results are unknown due to NULLs */
68550 ){
68551   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
68552   char affinity;        /* Comparison affinity to use */
68553   int eType;            /* Type of the RHS */
68554   int r1;               /* Temporary use register */
68555   Vdbe *v;              /* Statement under construction */
68556
68557   /* Compute the RHS.   After this step, the table with cursor
68558   ** pExpr->iTable will contains the values that make up the RHS.
68559   */
68560   v = pParse->pVdbe;
68561   assert( v!=0 );       /* OOM detected prior to this routine */
68562   VdbeNoopComment((v, "begin IN expr"));
68563   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
68564
68565   /* Figure out the affinity to use to create a key from the results
68566   ** of the expression. affinityStr stores a static string suitable for
68567   ** P4 of OP_MakeRecord.
68568   */
68569   affinity = comparisonAffinity(pExpr);
68570
68571   /* Code the LHS, the <expr> from "<expr> IN (...)".
68572   */
68573   sqlite3ExprCachePush(pParse);
68574   r1 = sqlite3GetTempReg(pParse);
68575   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
68576
68577   /* If the LHS is NULL, then the result is either false or NULL depending
68578   ** on whether the RHS is empty or not, respectively.
68579   */
68580   if( destIfNull==destIfFalse ){
68581     /* Shortcut for the common case where the false and NULL outcomes are
68582     ** the same. */
68583     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
68584   }else{
68585     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
68586     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
68587     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
68588     sqlite3VdbeJumpHere(v, addr1);
68589   }
68590
68591   if( eType==IN_INDEX_ROWID ){
68592     /* In this case, the RHS is the ROWID of table b-tree
68593     */
68594     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
68595     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
68596   }else{
68597     /* In this case, the RHS is an index b-tree.
68598     */
68599     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
68600
68601     /* If the set membership test fails, then the result of the 
68602     ** "x IN (...)" expression must be either 0 or NULL. If the set
68603     ** contains no NULL values, then the result is 0. If the set 
68604     ** contains one or more NULL values, then the result of the
68605     ** expression is also NULL.
68606     */
68607     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
68608       /* This branch runs if it is known at compile time that the RHS
68609       ** cannot contain NULL values. This happens as the result
68610       ** of a "NOT NULL" constraint in the database schema.
68611       **
68612       ** Also run this branch if NULL is equivalent to FALSE
68613       ** for this particular IN operator.
68614       */
68615       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
68616
68617     }else{
68618       /* In this branch, the RHS of the IN might contain a NULL and
68619       ** the presence of a NULL on the RHS makes a difference in the
68620       ** outcome.
68621       */
68622       int j1, j2, j3;
68623
68624       /* First check to see if the LHS is contained in the RHS.  If so,
68625       ** then the presence of NULLs in the RHS does not matter, so jump
68626       ** over all of the code that follows.
68627       */
68628       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
68629
68630       /* Here we begin generating code that runs if the LHS is not
68631       ** contained within the RHS.  Generate additional code that
68632       ** tests the RHS for NULLs.  If the RHS contains a NULL then
68633       ** jump to destIfNull.  If there are no NULLs in the RHS then
68634       ** jump to destIfFalse.
68635       */
68636       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
68637       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
68638       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
68639       sqlite3VdbeJumpHere(v, j3);
68640       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
68641       sqlite3VdbeJumpHere(v, j2);
68642
68643       /* Jump to the appropriate target depending on whether or not
68644       ** the RHS contains a NULL
68645       */
68646       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
68647       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
68648
68649       /* The OP_Found at the top of this branch jumps here when true, 
68650       ** causing the overall IN expression evaluation to fall through.
68651       */
68652       sqlite3VdbeJumpHere(v, j1);
68653     }
68654   }
68655   sqlite3ReleaseTempReg(pParse, r1);
68656   sqlite3ExprCachePop(pParse, 1);
68657   VdbeComment((v, "end IN expr"));
68658 }
68659 #endif /* SQLITE_OMIT_SUBQUERY */
68660
68661 /*
68662 ** Duplicate an 8-byte value
68663 */
68664 static char *dup8bytes(Vdbe *v, const char *in){
68665   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
68666   if( out ){
68667     memcpy(out, in, 8);
68668   }
68669   return out;
68670 }
68671
68672 #ifndef SQLITE_OMIT_FLOATING_POINT
68673 /*
68674 ** Generate an instruction that will put the floating point
68675 ** value described by z[0..n-1] into register iMem.
68676 **
68677 ** The z[] string will probably not be zero-terminated.  But the 
68678 ** z[n] character is guaranteed to be something that does not look
68679 ** like the continuation of the number.
68680 */
68681 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
68682   if( ALWAYS(z!=0) ){
68683     double value;
68684     char *zV;
68685     sqlite3AtoF(z, &value);
68686     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
68687     if( negateFlag ) value = -value;
68688     zV = dup8bytes(v, (char*)&value);
68689     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
68690   }
68691 }
68692 #endif
68693
68694
68695 /*
68696 ** Generate an instruction that will put the integer describe by
68697 ** text z[0..n-1] into register iMem.
68698 **
68699 ** The z[] string will probably not be zero-terminated.  But the 
68700 ** z[n] character is guaranteed to be something that does not look
68701 ** like the continuation of the number.
68702 */
68703 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
68704   Vdbe *v = pParse->pVdbe;
68705   if( pExpr->flags & EP_IntValue ){
68706     int i = pExpr->u.iValue;
68707     if( negFlag ) i = -i;
68708     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
68709   }else{
68710     const char *z = pExpr->u.zToken;
68711     assert( z!=0 );
68712     if( sqlite3FitsIn64Bits(z, negFlag) ){
68713       i64 value;
68714       char *zV;
68715       sqlite3Atoi64(z, &value);
68716       if( negFlag ) value = -value;
68717       zV = dup8bytes(v, (char*)&value);
68718       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
68719     }else{
68720 #ifdef SQLITE_OMIT_FLOATING_POINT
68721       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
68722 #else
68723       codeReal(v, z, negFlag, iMem);
68724 #endif
68725     }
68726   }
68727 }
68728
68729 /*
68730 ** Clear a cache entry.
68731 */
68732 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
68733   if( p->tempReg ){
68734     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
68735       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
68736     }
68737     p->tempReg = 0;
68738   }
68739 }
68740
68741
68742 /*
68743 ** Record in the column cache that a particular column from a
68744 ** particular table is stored in a particular register.
68745 */
68746 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
68747   int i;
68748   int minLru;
68749   int idxLru;
68750   struct yColCache *p;
68751
68752   assert( iReg>0 );  /* Register numbers are always positive */
68753   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
68754
68755   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
68756   ** for testing only - to verify that SQLite always gets the same answer
68757   ** with and without the column cache.
68758   */
68759   if( pParse->db->flags & SQLITE_ColumnCache ) return;
68760
68761   /* First replace any existing entry.
68762   **
68763   ** Actually, the way the column cache is currently used, we are guaranteed
68764   ** that the object will never already be in cache.  Verify this guarantee.
68765   */
68766 #ifndef NDEBUG
68767   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68768 #if 0 /* This code wold remove the entry from the cache if it existed */
68769     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
68770       cacheEntryClear(pParse, p);
68771       p->iLevel = pParse->iCacheLevel;
68772       p->iReg = iReg;
68773       p->lru = pParse->iCacheCnt++;
68774       return;
68775     }
68776 #endif
68777     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
68778   }
68779 #endif
68780
68781   /* Find an empty slot and replace it */
68782   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68783     if( p->iReg==0 ){
68784       p->iLevel = pParse->iCacheLevel;
68785       p->iTable = iTab;
68786       p->iColumn = iCol;
68787       p->iReg = iReg;
68788       p->tempReg = 0;
68789       p->lru = pParse->iCacheCnt++;
68790       return;
68791     }
68792   }
68793
68794   /* Replace the last recently used */
68795   minLru = 0x7fffffff;
68796   idxLru = -1;
68797   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68798     if( p->lru<minLru ){
68799       idxLru = i;
68800       minLru = p->lru;
68801     }
68802   }
68803   if( ALWAYS(idxLru>=0) ){
68804     p = &pParse->aColCache[idxLru];
68805     p->iLevel = pParse->iCacheLevel;
68806     p->iTable = iTab;
68807     p->iColumn = iCol;
68808     p->iReg = iReg;
68809     p->tempReg = 0;
68810     p->lru = pParse->iCacheCnt++;
68811     return;
68812   }
68813 }
68814
68815 /*
68816 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
68817 ** Purge the range of registers from the column cache.
68818 */
68819 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
68820   int i;
68821   int iLast = iReg + nReg - 1;
68822   struct yColCache *p;
68823   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68824     int r = p->iReg;
68825     if( r>=iReg && r<=iLast ){
68826       cacheEntryClear(pParse, p);
68827       p->iReg = 0;
68828     }
68829   }
68830 }
68831
68832 /*
68833 ** Remember the current column cache context.  Any new entries added
68834 ** added to the column cache after this call are removed when the
68835 ** corresponding pop occurs.
68836 */
68837 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
68838   pParse->iCacheLevel++;
68839 }
68840
68841 /*
68842 ** Remove from the column cache any entries that were added since the
68843 ** the previous N Push operations.  In other words, restore the cache
68844 ** to the state it was in N Pushes ago.
68845 */
68846 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
68847   int i;
68848   struct yColCache *p;
68849   assert( N>0 );
68850   assert( pParse->iCacheLevel>=N );
68851   pParse->iCacheLevel -= N;
68852   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68853     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
68854       cacheEntryClear(pParse, p);
68855       p->iReg = 0;
68856     }
68857   }
68858 }
68859
68860 /*
68861 ** When a cached column is reused, make sure that its register is
68862 ** no longer available as a temp register.  ticket #3879:  that same
68863 ** register might be in the cache in multiple places, so be sure to
68864 ** get them all.
68865 */
68866 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
68867   int i;
68868   struct yColCache *p;
68869   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68870     if( p->iReg==iReg ){
68871       p->tempReg = 0;
68872     }
68873   }
68874 }
68875
68876 /*
68877 ** Generate code to extract the value of the iCol-th column of a table.
68878 */
68879 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
68880   Vdbe *v,        /* The VDBE under construction */
68881   Table *pTab,    /* The table containing the value */
68882   int iTabCur,    /* The cursor for this table */
68883   int iCol,       /* Index of the column to extract */
68884   int regOut      /* Extract the valud into this register */
68885 ){
68886   if( iCol<0 || iCol==pTab->iPKey ){
68887     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
68888   }else{
68889     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
68890     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
68891   }
68892   if( iCol>=0 ){
68893     sqlite3ColumnDefault(v, pTab, iCol, regOut);
68894   }
68895 }
68896
68897 /*
68898 ** Generate code that will extract the iColumn-th column from
68899 ** table pTab and store the column value in a register.  An effort
68900 ** is made to store the column value in register iReg, but this is
68901 ** not guaranteed.  The location of the column value is returned.
68902 **
68903 ** There must be an open cursor to pTab in iTable when this routine
68904 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
68905 */
68906 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
68907   Parse *pParse,   /* Parsing and code generating context */
68908   Table *pTab,     /* Description of the table we are reading from */
68909   int iColumn,     /* Index of the table column */
68910   int iTable,      /* The cursor pointing to the table */
68911   int iReg         /* Store results here */
68912 ){
68913   Vdbe *v = pParse->pVdbe;
68914   int i;
68915   struct yColCache *p;
68916
68917   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68918     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
68919       p->lru = pParse->iCacheCnt++;
68920       sqlite3ExprCachePinRegister(pParse, p->iReg);
68921       return p->iReg;
68922     }
68923   }  
68924   assert( v!=0 );
68925   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
68926   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
68927   return iReg;
68928 }
68929
68930 /*
68931 ** Clear all column cache entries.
68932 */
68933 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
68934   int i;
68935   struct yColCache *p;
68936
68937   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68938     if( p->iReg ){
68939       cacheEntryClear(pParse, p);
68940       p->iReg = 0;
68941     }
68942   }
68943 }
68944
68945 /*
68946 ** Record the fact that an affinity change has occurred on iCount
68947 ** registers starting with iStart.
68948 */
68949 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
68950   sqlite3ExprCacheRemove(pParse, iStart, iCount);
68951 }
68952
68953 /*
68954 ** Generate code to move content from registers iFrom...iFrom+nReg-1
68955 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
68956 */
68957 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
68958   int i;
68959   struct yColCache *p;
68960   if( NEVER(iFrom==iTo) ) return;
68961   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
68962   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68963     int x = p->iReg;
68964     if( x>=iFrom && x<iFrom+nReg ){
68965       p->iReg += iTo-iFrom;
68966     }
68967   }
68968 }
68969
68970 /*
68971 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
68972 ** over to iTo..iTo+nReg-1.
68973 */
68974 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
68975   int i;
68976   if( NEVER(iFrom==iTo) ) return;
68977   for(i=0; i<nReg; i++){
68978     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
68979   }
68980 }
68981
68982 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
68983 /*
68984 ** Return true if any register in the range iFrom..iTo (inclusive)
68985 ** is used as part of the column cache.
68986 **
68987 ** This routine is used within assert() and testcase() macros only
68988 ** and does not appear in a normal build.
68989 */
68990 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
68991   int i;
68992   struct yColCache *p;
68993   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68994     int r = p->iReg;
68995     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
68996   }
68997   return 0;
68998 }
68999 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
69000
69001 /*
69002 ** If the last instruction coded is an ephemeral copy of any of
69003 ** the registers in the nReg registers beginning with iReg, then
69004 ** convert the last instruction from OP_SCopy to OP_Copy.
69005 */
69006 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
69007   VdbeOp *pOp;
69008   Vdbe *v;
69009
69010   assert( pParse->db->mallocFailed==0 );
69011   v = pParse->pVdbe;
69012   assert( v!=0 );
69013   pOp = sqlite3VdbeGetOp(v, -1);
69014   assert( pOp!=0 );
69015   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
69016     pOp->opcode = OP_Copy;
69017   }
69018 }
69019
69020 /*
69021 ** Generate code to store the value of the iAlias-th alias in register
69022 ** target.  The first time this is called, pExpr is evaluated to compute
69023 ** the value of the alias.  The value is stored in an auxiliary register
69024 ** and the number of that register is returned.  On subsequent calls,
69025 ** the register number is returned without generating any code.
69026 **
69027 ** Note that in order for this to work, code must be generated in the
69028 ** same order that it is executed.
69029 **
69030 ** Aliases are numbered starting with 1.  So iAlias is in the range
69031 ** of 1 to pParse->nAlias inclusive.  
69032 **
69033 ** pParse->aAlias[iAlias-1] records the register number where the value
69034 ** of the iAlias-th alias is stored.  If zero, that means that the
69035 ** alias has not yet been computed.
69036 */
69037 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
69038 #if 0
69039   sqlite3 *db = pParse->db;
69040   int iReg;
69041   if( pParse->nAliasAlloc<pParse->nAlias ){
69042     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
69043                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
69044     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
69045     if( db->mallocFailed ) return 0;
69046     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
69047            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
69048     pParse->nAliasAlloc = pParse->nAlias;
69049   }
69050   assert( iAlias>0 && iAlias<=pParse->nAlias );
69051   iReg = pParse->aAlias[iAlias-1];
69052   if( iReg==0 ){
69053     if( pParse->iCacheLevel>0 ){
69054       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69055     }else{
69056       iReg = ++pParse->nMem;
69057       sqlite3ExprCode(pParse, pExpr, iReg);
69058       pParse->aAlias[iAlias-1] = iReg;
69059     }
69060   }
69061   return iReg;
69062 #else
69063   UNUSED_PARAMETER(iAlias);
69064   return sqlite3ExprCodeTarget(pParse, pExpr, target);
69065 #endif
69066 }
69067
69068 /*
69069 ** Generate code into the current Vdbe to evaluate the given
69070 ** expression.  Attempt to store the results in register "target".
69071 ** Return the register where results are stored.
69072 **
69073 ** With this routine, there is no guarantee that results will
69074 ** be stored in target.  The result might be stored in some other
69075 ** register if it is convenient to do so.  The calling function
69076 ** must check the return code and move the results to the desired
69077 ** register.
69078 */
69079 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
69080   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
69081   int op;                   /* The opcode being coded */
69082   int inReg = target;       /* Results stored in register inReg */
69083   int regFree1 = 0;         /* If non-zero free this temporary register */
69084   int regFree2 = 0;         /* If non-zero free this temporary register */
69085   int r1, r2, r3, r4;       /* Various register numbers */
69086   sqlite3 *db = pParse->db; /* The database connection */
69087
69088   assert( target>0 && target<=pParse->nMem );
69089   if( v==0 ){
69090     assert( pParse->db->mallocFailed );
69091     return 0;
69092   }
69093
69094   if( pExpr==0 ){
69095     op = TK_NULL;
69096   }else{
69097     op = pExpr->op;
69098   }
69099   switch( op ){
69100     case TK_AGG_COLUMN: {
69101       AggInfo *pAggInfo = pExpr->pAggInfo;
69102       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
69103       if( !pAggInfo->directMode ){
69104         assert( pCol->iMem>0 );
69105         inReg = pCol->iMem;
69106         break;
69107       }else if( pAggInfo->useSortingIdx ){
69108         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
69109                               pCol->iSorterColumn, target);
69110         break;
69111       }
69112       /* Otherwise, fall thru into the TK_COLUMN case */
69113     }
69114     case TK_COLUMN: {
69115       if( pExpr->iTable<0 ){
69116         /* This only happens when coding check constraints */
69117         assert( pParse->ckBase>0 );
69118         inReg = pExpr->iColumn + pParse->ckBase;
69119       }else{
69120         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
69121                                  pExpr->iColumn, pExpr->iTable, target);
69122       }
69123       break;
69124     }
69125     case TK_INTEGER: {
69126       codeInteger(pParse, pExpr, 0, target);
69127       break;
69128     }
69129 #ifndef SQLITE_OMIT_FLOATING_POINT
69130     case TK_FLOAT: {
69131       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69132       codeReal(v, pExpr->u.zToken, 0, target);
69133       break;
69134     }
69135 #endif
69136     case TK_STRING: {
69137       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69138       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
69139       break;
69140     }
69141     case TK_NULL: {
69142       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69143       break;
69144     }
69145 #ifndef SQLITE_OMIT_BLOB_LITERAL
69146     case TK_BLOB: {
69147       int n;
69148       const char *z;
69149       char *zBlob;
69150       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69151       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
69152       assert( pExpr->u.zToken[1]=='\'' );
69153       z = &pExpr->u.zToken[2];
69154       n = sqlite3Strlen30(z) - 1;
69155       assert( z[n]=='\'' );
69156       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
69157       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
69158       break;
69159     }
69160 #endif
69161     case TK_VARIABLE: {
69162       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69163       assert( pExpr->u.zToken!=0 );
69164       assert( pExpr->u.zToken[0]!=0 );
69165       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
69166       if( pExpr->u.zToken[1]!=0 ){
69167         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
69168       }
69169       break;
69170     }
69171     case TK_REGISTER: {
69172       inReg = pExpr->iTable;
69173       break;
69174     }
69175     case TK_AS: {
69176       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
69177       break;
69178     }
69179 #ifndef SQLITE_OMIT_CAST
69180     case TK_CAST: {
69181       /* Expressions of the form:   CAST(pLeft AS token) */
69182       int aff, to_op;
69183       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
69184       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69185       aff = sqlite3AffinityType(pExpr->u.zToken);
69186       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
69187       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
69188       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
69189       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
69190       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
69191       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
69192       testcase( to_op==OP_ToText );
69193       testcase( to_op==OP_ToBlob );
69194       testcase( to_op==OP_ToNumeric );
69195       testcase( to_op==OP_ToInt );
69196       testcase( to_op==OP_ToReal );
69197       if( inReg!=target ){
69198         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
69199         inReg = target;
69200       }
69201       sqlite3VdbeAddOp1(v, to_op, inReg);
69202       testcase( usedAsColumnCache(pParse, inReg, inReg) );
69203       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
69204       break;
69205     }
69206 #endif /* SQLITE_OMIT_CAST */
69207     case TK_LT:
69208     case TK_LE:
69209     case TK_GT:
69210     case TK_GE:
69211     case TK_NE:
69212     case TK_EQ: {
69213       assert( TK_LT==OP_Lt );
69214       assert( TK_LE==OP_Le );
69215       assert( TK_GT==OP_Gt );
69216       assert( TK_GE==OP_Ge );
69217       assert( TK_EQ==OP_Eq );
69218       assert( TK_NE==OP_Ne );
69219       testcase( op==TK_LT );
69220       testcase( op==TK_LE );
69221       testcase( op==TK_GT );
69222       testcase( op==TK_GE );
69223       testcase( op==TK_EQ );
69224       testcase( op==TK_NE );
69225       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69226       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69227       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69228                   r1, r2, inReg, SQLITE_STOREP2);
69229       testcase( regFree1==0 );
69230       testcase( regFree2==0 );
69231       break;
69232     }
69233     case TK_IS:
69234     case TK_ISNOT: {
69235       testcase( op==TK_IS );
69236       testcase( op==TK_ISNOT );
69237       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69238       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69239       op = (op==TK_IS) ? TK_EQ : TK_NE;
69240       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69241                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
69242       testcase( regFree1==0 );
69243       testcase( regFree2==0 );
69244       break;
69245     }
69246     case TK_AND:
69247     case TK_OR:
69248     case TK_PLUS:
69249     case TK_STAR:
69250     case TK_MINUS:
69251     case TK_REM:
69252     case TK_BITAND:
69253     case TK_BITOR:
69254     case TK_SLASH:
69255     case TK_LSHIFT:
69256     case TK_RSHIFT: 
69257     case TK_CONCAT: {
69258       assert( TK_AND==OP_And );
69259       assert( TK_OR==OP_Or );
69260       assert( TK_PLUS==OP_Add );
69261       assert( TK_MINUS==OP_Subtract );
69262       assert( TK_REM==OP_Remainder );
69263       assert( TK_BITAND==OP_BitAnd );
69264       assert( TK_BITOR==OP_BitOr );
69265       assert( TK_SLASH==OP_Divide );
69266       assert( TK_LSHIFT==OP_ShiftLeft );
69267       assert( TK_RSHIFT==OP_ShiftRight );
69268       assert( TK_CONCAT==OP_Concat );
69269       testcase( op==TK_AND );
69270       testcase( op==TK_OR );
69271       testcase( op==TK_PLUS );
69272       testcase( op==TK_MINUS );
69273       testcase( op==TK_REM );
69274       testcase( op==TK_BITAND );
69275       testcase( op==TK_BITOR );
69276       testcase( op==TK_SLASH );
69277       testcase( op==TK_LSHIFT );
69278       testcase( op==TK_RSHIFT );
69279       testcase( op==TK_CONCAT );
69280       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69281       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69282       sqlite3VdbeAddOp3(v, op, r2, r1, target);
69283       testcase( regFree1==0 );
69284       testcase( regFree2==0 );
69285       break;
69286     }
69287     case TK_UMINUS: {
69288       Expr *pLeft = pExpr->pLeft;
69289       assert( pLeft );
69290       if( pLeft->op==TK_INTEGER ){
69291         codeInteger(pParse, pLeft, 1, target);
69292 #ifndef SQLITE_OMIT_FLOATING_POINT
69293       }else if( pLeft->op==TK_FLOAT ){
69294         assert( !ExprHasProperty(pExpr, EP_IntValue) );
69295         codeReal(v, pLeft->u.zToken, 1, target);
69296 #endif
69297       }else{
69298         regFree1 = r1 = sqlite3GetTempReg(pParse);
69299         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
69300         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
69301         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
69302         testcase( regFree2==0 );
69303       }
69304       inReg = target;
69305       break;
69306     }
69307     case TK_BITNOT:
69308     case TK_NOT: {
69309       assert( TK_BITNOT==OP_BitNot );
69310       assert( TK_NOT==OP_Not );
69311       testcase( op==TK_BITNOT );
69312       testcase( op==TK_NOT );
69313       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69314       testcase( regFree1==0 );
69315       inReg = target;
69316       sqlite3VdbeAddOp2(v, op, r1, inReg);
69317       break;
69318     }
69319     case TK_ISNULL:
69320     case TK_NOTNULL: {
69321       int addr;
69322       assert( TK_ISNULL==OP_IsNull );
69323       assert( TK_NOTNULL==OP_NotNull );
69324       testcase( op==TK_ISNULL );
69325       testcase( op==TK_NOTNULL );
69326       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
69327       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69328       testcase( regFree1==0 );
69329       addr = sqlite3VdbeAddOp1(v, op, r1);
69330       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
69331       sqlite3VdbeJumpHere(v, addr);
69332       break;
69333     }
69334     case TK_AGG_FUNCTION: {
69335       AggInfo *pInfo = pExpr->pAggInfo;
69336       if( pInfo==0 ){
69337         assert( !ExprHasProperty(pExpr, EP_IntValue) );
69338         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
69339       }else{
69340         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
69341       }
69342       break;
69343     }
69344     case TK_CONST_FUNC:
69345     case TK_FUNCTION: {
69346       ExprList *pFarg;       /* List of function arguments */
69347       int nFarg;             /* Number of function arguments */
69348       FuncDef *pDef;         /* The function definition object */
69349       int nId;               /* Length of the function name in bytes */
69350       const char *zId;       /* The function name */
69351       int constMask = 0;     /* Mask of function arguments that are constant */
69352       int i;                 /* Loop counter */
69353       u8 enc = ENC(db);      /* The text encoding used by this database */
69354       CollSeq *pColl = 0;    /* A collating sequence */
69355
69356       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69357       testcase( op==TK_CONST_FUNC );
69358       testcase( op==TK_FUNCTION );
69359       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
69360         pFarg = 0;
69361       }else{
69362         pFarg = pExpr->x.pList;
69363       }
69364       nFarg = pFarg ? pFarg->nExpr : 0;
69365       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69366       zId = pExpr->u.zToken;
69367       nId = sqlite3Strlen30(zId);
69368       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
69369       if( pDef==0 ){
69370         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
69371         break;
69372       }
69373
69374       /* Attempt a direct implementation of the built-in COALESCE() and
69375       ** IFNULL() functions.  This avoids unnecessary evalation of
69376       ** arguments past the first non-NULL argument.
69377       */
69378       if( pDef->flags & SQLITE_FUNC_COALESCE ){
69379         int endCoalesce = sqlite3VdbeMakeLabel(v);
69380         assert( nFarg>=2 );
69381         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
69382         for(i=1; i<nFarg; i++){
69383           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
69384           sqlite3ExprCacheRemove(pParse, target, 1);
69385           sqlite3ExprCachePush(pParse);
69386           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
69387           sqlite3ExprCachePop(pParse, 1);
69388         }
69389         sqlite3VdbeResolveLabel(v, endCoalesce);
69390         break;
69391       }
69392
69393
69394       if( pFarg ){
69395         r1 = sqlite3GetTempRange(pParse, nFarg);
69396         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
69397         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
69398         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
69399       }else{
69400         r1 = 0;
69401       }
69402 #ifndef SQLITE_OMIT_VIRTUALTABLE
69403       /* Possibly overload the function if the first argument is
69404       ** a virtual table column.
69405       **
69406       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
69407       ** second argument, not the first, as the argument to test to
69408       ** see if it is a column in a virtual table.  This is done because
69409       ** the left operand of infix functions (the operand we want to
69410       ** control overloading) ends up as the second argument to the
69411       ** function.  The expression "A glob B" is equivalent to 
69412       ** "glob(B,A).  We want to use the A in "A glob B" to test
69413       ** for function overloading.  But we use the B term in "glob(B,A)".
69414       */
69415       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
69416         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
69417       }else if( nFarg>0 ){
69418         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
69419       }
69420 #endif
69421       for(i=0; i<nFarg; i++){
69422         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
69423           constMask |= (1<<i);
69424         }
69425         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
69426           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
69427         }
69428       }
69429       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
69430         if( !pColl ) pColl = db->pDfltColl; 
69431         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
69432       }
69433       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
69434                         (char*)pDef, P4_FUNCDEF);
69435       sqlite3VdbeChangeP5(v, (u8)nFarg);
69436       if( nFarg ){
69437         sqlite3ReleaseTempRange(pParse, r1, nFarg);
69438       }
69439       break;
69440     }
69441 #ifndef SQLITE_OMIT_SUBQUERY
69442     case TK_EXISTS:
69443     case TK_SELECT: {
69444       testcase( op==TK_EXISTS );
69445       testcase( op==TK_SELECT );
69446       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
69447       break;
69448     }
69449     case TK_IN: {
69450       int destIfFalse = sqlite3VdbeMakeLabel(v);
69451       int destIfNull = sqlite3VdbeMakeLabel(v);
69452       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69453       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
69454       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
69455       sqlite3VdbeResolveLabel(v, destIfFalse);
69456       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
69457       sqlite3VdbeResolveLabel(v, destIfNull);
69458       break;
69459     }
69460 #endif /* SQLITE_OMIT_SUBQUERY */
69461
69462
69463     /*
69464     **    x BETWEEN y AND z
69465     **
69466     ** This is equivalent to
69467     **
69468     **    x>=y AND x<=z
69469     **
69470     ** X is stored in pExpr->pLeft.
69471     ** Y is stored in pExpr->pList->a[0].pExpr.
69472     ** Z is stored in pExpr->pList->a[1].pExpr.
69473     */
69474     case TK_BETWEEN: {
69475       Expr *pLeft = pExpr->pLeft;
69476       struct ExprList_item *pLItem = pExpr->x.pList->a;
69477       Expr *pRight = pLItem->pExpr;
69478
69479       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
69480       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69481       testcase( regFree1==0 );
69482       testcase( regFree2==0 );
69483       r3 = sqlite3GetTempReg(pParse);
69484       r4 = sqlite3GetTempReg(pParse);
69485       codeCompare(pParse, pLeft, pRight, OP_Ge,
69486                   r1, r2, r3, SQLITE_STOREP2);
69487       pLItem++;
69488       pRight = pLItem->pExpr;
69489       sqlite3ReleaseTempReg(pParse, regFree2);
69490       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69491       testcase( regFree2==0 );
69492       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
69493       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
69494       sqlite3ReleaseTempReg(pParse, r3);
69495       sqlite3ReleaseTempReg(pParse, r4);
69496       break;
69497     }
69498     case TK_UPLUS: {
69499       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
69500       break;
69501     }
69502
69503     case TK_TRIGGER: {
69504       /* If the opcode is TK_TRIGGER, then the expression is a reference
69505       ** to a column in the new.* or old.* pseudo-tables available to
69506       ** trigger programs. In this case Expr.iTable is set to 1 for the
69507       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
69508       ** is set to the column of the pseudo-table to read, or to -1 to
69509       ** read the rowid field.
69510       **
69511       ** The expression is implemented using an OP_Param opcode. The p1
69512       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
69513       ** to reference another column of the old.* pseudo-table, where 
69514       ** i is the index of the column. For a new.rowid reference, p1 is
69515       ** set to (n+1), where n is the number of columns in each pseudo-table.
69516       ** For a reference to any other column in the new.* pseudo-table, p1
69517       ** is set to (n+2+i), where n and i are as defined previously. For
69518       ** example, if the table on which triggers are being fired is
69519       ** declared as:
69520       **
69521       **   CREATE TABLE t1(a, b);
69522       **
69523       ** Then p1 is interpreted as follows:
69524       **
69525       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
69526       **   p1==1   ->    old.a         p1==4   ->    new.a
69527       **   p1==2   ->    old.b         p1==5   ->    new.b       
69528       */
69529       Table *pTab = pExpr->pTab;
69530       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
69531
69532       assert( pExpr->iTable==0 || pExpr->iTable==1 );
69533       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
69534       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
69535       assert( p1>=0 && p1<(pTab->nCol*2+2) );
69536
69537       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
69538       VdbeComment((v, "%s.%s -> $%d",
69539         (pExpr->iTable ? "new" : "old"),
69540         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
69541         target
69542       ));
69543
69544 #ifndef SQLITE_OMIT_FLOATING_POINT
69545       /* If the column has REAL affinity, it may currently be stored as an
69546       ** integer. Use OP_RealAffinity to make sure it is really real.  */
69547       if( pExpr->iColumn>=0 
69548        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
69549       ){
69550         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
69551       }
69552 #endif
69553       break;
69554     }
69555
69556
69557     /*
69558     ** Form A:
69559     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69560     **
69561     ** Form B:
69562     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69563     **
69564     ** Form A is can be transformed into the equivalent form B as follows:
69565     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
69566     **        WHEN x=eN THEN rN ELSE y END
69567     **
69568     ** X (if it exists) is in pExpr->pLeft.
69569     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
69570     ** ELSE clause and no other term matches, then the result of the
69571     ** exprssion is NULL.
69572     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
69573     **
69574     ** The result of the expression is the Ri for the first matching Ei,
69575     ** or if there is no matching Ei, the ELSE term Y, or if there is
69576     ** no ELSE term, NULL.
69577     */
69578     default: assert( op==TK_CASE ); {
69579       int endLabel;                     /* GOTO label for end of CASE stmt */
69580       int nextCase;                     /* GOTO label for next WHEN clause */
69581       int nExpr;                        /* 2x number of WHEN terms */
69582       int i;                            /* Loop counter */
69583       ExprList *pEList;                 /* List of WHEN terms */
69584       struct ExprList_item *aListelem;  /* Array of WHEN terms */
69585       Expr opCompare;                   /* The X==Ei expression */
69586       Expr cacheX;                      /* Cached expression X */
69587       Expr *pX;                         /* The X expression */
69588       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
69589       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
69590
69591       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
69592       assert((pExpr->x.pList->nExpr % 2) == 0);
69593       assert(pExpr->x.pList->nExpr > 0);
69594       pEList = pExpr->x.pList;
69595       aListelem = pEList->a;
69596       nExpr = pEList->nExpr;
69597       endLabel = sqlite3VdbeMakeLabel(v);
69598       if( (pX = pExpr->pLeft)!=0 ){
69599         cacheX = *pX;
69600         testcase( pX->op==TK_COLUMN );
69601         testcase( pX->op==TK_REGISTER );
69602         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
69603         testcase( regFree1==0 );
69604         cacheX.op = TK_REGISTER;
69605         opCompare.op = TK_EQ;
69606         opCompare.pLeft = &cacheX;
69607         pTest = &opCompare;
69608       }
69609       for(i=0; i<nExpr; i=i+2){
69610         sqlite3ExprCachePush(pParse);
69611         if( pX ){
69612           assert( pTest!=0 );
69613           opCompare.pRight = aListelem[i].pExpr;
69614         }else{
69615           pTest = aListelem[i].pExpr;
69616         }
69617         nextCase = sqlite3VdbeMakeLabel(v);
69618         testcase( pTest->op==TK_COLUMN );
69619         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
69620         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
69621         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
69622         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
69623         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
69624         sqlite3ExprCachePop(pParse, 1);
69625         sqlite3VdbeResolveLabel(v, nextCase);
69626       }
69627       if( pExpr->pRight ){
69628         sqlite3ExprCachePush(pParse);
69629         sqlite3ExprCode(pParse, pExpr->pRight, target);
69630         sqlite3ExprCachePop(pParse, 1);
69631       }else{
69632         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69633       }
69634       assert( db->mallocFailed || pParse->nErr>0 
69635            || pParse->iCacheLevel==iCacheLevel );
69636       sqlite3VdbeResolveLabel(v, endLabel);
69637       break;
69638     }
69639 #ifndef SQLITE_OMIT_TRIGGER
69640     case TK_RAISE: {
69641       assert( pExpr->affinity==OE_Rollback 
69642            || pExpr->affinity==OE_Abort
69643            || pExpr->affinity==OE_Fail
69644            || pExpr->affinity==OE_Ignore
69645       );
69646       if( !pParse->pTriggerTab ){
69647         sqlite3ErrorMsg(pParse,
69648                        "RAISE() may only be used within a trigger-program");
69649         return 0;
69650       }
69651       if( pExpr->affinity==OE_Abort ){
69652         sqlite3MayAbort(pParse);
69653       }
69654       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69655       if( pExpr->affinity==OE_Ignore ){
69656         sqlite3VdbeAddOp4(
69657             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
69658       }else{
69659         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
69660       }
69661
69662       break;
69663     }
69664 #endif
69665   }
69666   sqlite3ReleaseTempReg(pParse, regFree1);
69667   sqlite3ReleaseTempReg(pParse, regFree2);
69668   return inReg;
69669 }
69670
69671 /*
69672 ** Generate code to evaluate an expression and store the results
69673 ** into a register.  Return the register number where the results
69674 ** are stored.
69675 **
69676 ** If the register is a temporary register that can be deallocated,
69677 ** then write its number into *pReg.  If the result register is not
69678 ** a temporary, then set *pReg to zero.
69679 */
69680 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
69681   int r1 = sqlite3GetTempReg(pParse);
69682   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69683   if( r2==r1 ){
69684     *pReg = r1;
69685   }else{
69686     sqlite3ReleaseTempReg(pParse, r1);
69687     *pReg = 0;
69688   }
69689   return r2;
69690 }
69691
69692 /*
69693 ** Generate code that will evaluate expression pExpr and store the
69694 ** results in register target.  The results are guaranteed to appear
69695 ** in register target.
69696 */
69697 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
69698   int inReg;
69699
69700   assert( target>0 && target<=pParse->nMem );
69701   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69702   assert( pParse->pVdbe || pParse->db->mallocFailed );
69703   if( inReg!=target && pParse->pVdbe ){
69704     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
69705   }
69706   return target;
69707 }
69708
69709 /*
69710 ** Generate code that evalutes the given expression and puts the result
69711 ** in register target.
69712 **
69713 ** Also make a copy of the expression results into another "cache" register
69714 ** and modify the expression so that the next time it is evaluated,
69715 ** the result is a copy of the cache register.
69716 **
69717 ** This routine is used for expressions that are used multiple 
69718 ** times.  They are evaluated once and the results of the expression
69719 ** are reused.
69720 */
69721 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
69722   Vdbe *v = pParse->pVdbe;
69723   int inReg;
69724   inReg = sqlite3ExprCode(pParse, pExpr, target);
69725   assert( target>0 );
69726   /* This routine is called for terms to INSERT or UPDATE.  And the only
69727   ** other place where expressions can be converted into TK_REGISTER is
69728   ** in WHERE clause processing.  So as currently implemented, there is
69729   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
69730   ** keep the ALWAYS() in case the conditions above change with future
69731   ** modifications or enhancements. */
69732   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
69733     int iMem;
69734     iMem = ++pParse->nMem;
69735     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
69736     pExpr->iTable = iMem;
69737     pExpr->op2 = pExpr->op;
69738     pExpr->op = TK_REGISTER;
69739   }
69740   return inReg;
69741 }
69742
69743 /*
69744 ** Return TRUE if pExpr is an constant expression that is appropriate
69745 ** for factoring out of a loop.  Appropriate expressions are:
69746 **
69747 **    *  Any expression that evaluates to two or more opcodes.
69748 **
69749 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
69750 **       or OP_Variable that does not need to be placed in a 
69751 **       specific register.
69752 **
69753 ** There is no point in factoring out single-instruction constant
69754 ** expressions that need to be placed in a particular register.  
69755 ** We could factor them out, but then we would end up adding an
69756 ** OP_SCopy instruction to move the value into the correct register
69757 ** later.  We might as well just use the original instruction and
69758 ** avoid the OP_SCopy.
69759 */
69760 static int isAppropriateForFactoring(Expr *p){
69761   if( !sqlite3ExprIsConstantNotJoin(p) ){
69762     return 0;  /* Only constant expressions are appropriate for factoring */
69763   }
69764   if( (p->flags & EP_FixedDest)==0 ){
69765     return 1;  /* Any constant without a fixed destination is appropriate */
69766   }
69767   while( p->op==TK_UPLUS ) p = p->pLeft;
69768   switch( p->op ){
69769 #ifndef SQLITE_OMIT_BLOB_LITERAL
69770     case TK_BLOB:
69771 #endif
69772     case TK_VARIABLE:
69773     case TK_INTEGER:
69774     case TK_FLOAT:
69775     case TK_NULL:
69776     case TK_STRING: {
69777       testcase( p->op==TK_BLOB );
69778       testcase( p->op==TK_VARIABLE );
69779       testcase( p->op==TK_INTEGER );
69780       testcase( p->op==TK_FLOAT );
69781       testcase( p->op==TK_NULL );
69782       testcase( p->op==TK_STRING );
69783       /* Single-instruction constants with a fixed destination are
69784       ** better done in-line.  If we factor them, they will just end
69785       ** up generating an OP_SCopy to move the value to the destination
69786       ** register. */
69787       return 0;
69788     }
69789     case TK_UMINUS: {
69790       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
69791         return 0;
69792       }
69793       break;
69794     }
69795     default: {
69796       break;
69797     }
69798   }
69799   return 1;
69800 }
69801
69802 /*
69803 ** If pExpr is a constant expression that is appropriate for
69804 ** factoring out of a loop, then evaluate the expression
69805 ** into a register and convert the expression into a TK_REGISTER
69806 ** expression.
69807 */
69808 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
69809   Parse *pParse = pWalker->pParse;
69810   switch( pExpr->op ){
69811     case TK_IN:
69812     case TK_REGISTER: {
69813       return WRC_Prune;
69814     }
69815     case TK_FUNCTION:
69816     case TK_AGG_FUNCTION:
69817     case TK_CONST_FUNC: {
69818       /* The arguments to a function have a fixed destination.
69819       ** Mark them this way to avoid generated unneeded OP_SCopy
69820       ** instructions. 
69821       */
69822       ExprList *pList = pExpr->x.pList;
69823       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69824       if( pList ){
69825         int i = pList->nExpr;
69826         struct ExprList_item *pItem = pList->a;
69827         for(; i>0; i--, pItem++){
69828           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
69829         }
69830       }
69831       break;
69832     }
69833   }
69834   if( isAppropriateForFactoring(pExpr) ){
69835     int r1 = ++pParse->nMem;
69836     int r2;
69837     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69838     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
69839     pExpr->op2 = pExpr->op;
69840     pExpr->op = TK_REGISTER;
69841     pExpr->iTable = r2;
69842     return WRC_Prune;
69843   }
69844   return WRC_Continue;
69845 }
69846
69847 /*
69848 ** Preevaluate constant subexpressions within pExpr and store the
69849 ** results in registers.  Modify pExpr so that the constant subexpresions
69850 ** are TK_REGISTER opcodes that refer to the precomputed values.
69851 */
69852 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
69853   Walker w;
69854   w.xExprCallback = evalConstExpr;
69855   w.xSelectCallback = 0;
69856   w.pParse = pParse;
69857   sqlite3WalkExpr(&w, pExpr);
69858 }
69859
69860
69861 /*
69862 ** Generate code that pushes the value of every element of the given
69863 ** expression list into a sequence of registers beginning at target.
69864 **
69865 ** Return the number of elements evaluated.
69866 */
69867 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
69868   Parse *pParse,     /* Parsing context */
69869   ExprList *pList,   /* The expression list to be coded */
69870   int target,        /* Where to write results */
69871   int doHardCopy     /* Make a hard copy of every element */
69872 ){
69873   struct ExprList_item *pItem;
69874   int i, n;
69875   assert( pList!=0 );
69876   assert( target>0 );
69877   n = pList->nExpr;
69878   for(pItem=pList->a, i=0; i<n; i++, pItem++){
69879     if( pItem->iAlias ){
69880       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
69881       Vdbe *v = sqlite3GetVdbe(pParse);
69882       if( iReg!=target+i ){
69883         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
69884       }
69885     }else{
69886       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
69887     }
69888     if( doHardCopy && !pParse->db->mallocFailed ){
69889       sqlite3ExprHardCopy(pParse, target, n);
69890     }
69891   }
69892   return n;
69893 }
69894
69895 /*
69896 ** Generate code for a BETWEEN operator.
69897 **
69898 **    x BETWEEN y AND z
69899 **
69900 ** The above is equivalent to 
69901 **
69902 **    x>=y AND x<=z
69903 **
69904 ** Code it as such, taking care to do the common subexpression
69905 ** elementation of x.
69906 */
69907 static void exprCodeBetween(
69908   Parse *pParse,    /* Parsing and code generating context */
69909   Expr *pExpr,      /* The BETWEEN expression */
69910   int dest,         /* Jump here if the jump is taken */
69911   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
69912   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
69913 ){
69914   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
69915   Expr compLeft;    /* The  x>=y  term */
69916   Expr compRight;   /* The  x<=z  term */
69917   Expr exprX;       /* The  x  subexpression */
69918   int regFree1 = 0; /* Temporary use register */
69919
69920   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69921   exprX = *pExpr->pLeft;
69922   exprAnd.op = TK_AND;
69923   exprAnd.pLeft = &compLeft;
69924   exprAnd.pRight = &compRight;
69925   compLeft.op = TK_GE;
69926   compLeft.pLeft = &exprX;
69927   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
69928   compRight.op = TK_LE;
69929   compRight.pLeft = &exprX;
69930   compRight.pRight = pExpr->x.pList->a[1].pExpr;
69931   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
69932   exprX.op = TK_REGISTER;
69933   if( jumpIfTrue ){
69934     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
69935   }else{
69936     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
69937   }
69938   sqlite3ReleaseTempReg(pParse, regFree1);
69939
69940   /* Ensure adequate test coverage */
69941   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
69942   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
69943   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
69944   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
69945   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
69946   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
69947   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
69948   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
69949 }
69950
69951 /*
69952 ** Generate code for a boolean expression such that a jump is made
69953 ** to the label "dest" if the expression is true but execution
69954 ** continues straight thru if the expression is false.
69955 **
69956 ** If the expression evaluates to NULL (neither true nor false), then
69957 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
69958 **
69959 ** This code depends on the fact that certain token values (ex: TK_EQ)
69960 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
69961 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
69962 ** the make process cause these values to align.  Assert()s in the code
69963 ** below verify that the numbers are aligned correctly.
69964 */
69965 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
69966   Vdbe *v = pParse->pVdbe;
69967   int op = 0;
69968   int regFree1 = 0;
69969   int regFree2 = 0;
69970   int r1, r2;
69971
69972   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
69973   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
69974   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
69975   op = pExpr->op;
69976   switch( op ){
69977     case TK_AND: {
69978       int d2 = sqlite3VdbeMakeLabel(v);
69979       testcase( jumpIfNull==0 );
69980       sqlite3ExprCachePush(pParse);
69981       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
69982       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69983       sqlite3VdbeResolveLabel(v, d2);
69984       sqlite3ExprCachePop(pParse, 1);
69985       break;
69986     }
69987     case TK_OR: {
69988       testcase( jumpIfNull==0 );
69989       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
69990       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69991       break;
69992     }
69993     case TK_NOT: {
69994       testcase( jumpIfNull==0 );
69995       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
69996       break;
69997     }
69998     case TK_LT:
69999     case TK_LE:
70000     case TK_GT:
70001     case TK_GE:
70002     case TK_NE:
70003     case TK_EQ: {
70004       assert( TK_LT==OP_Lt );
70005       assert( TK_LE==OP_Le );
70006       assert( TK_GT==OP_Gt );
70007       assert( TK_GE==OP_Ge );
70008       assert( TK_EQ==OP_Eq );
70009       assert( TK_NE==OP_Ne );
70010       testcase( op==TK_LT );
70011       testcase( op==TK_LE );
70012       testcase( op==TK_GT );
70013       testcase( op==TK_GE );
70014       testcase( op==TK_EQ );
70015       testcase( op==TK_NE );
70016       testcase( jumpIfNull==0 );
70017       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70018       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70019       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70020                   r1, r2, dest, jumpIfNull);
70021       testcase( regFree1==0 );
70022       testcase( regFree2==0 );
70023       break;
70024     }
70025     case TK_IS:
70026     case TK_ISNOT: {
70027       testcase( op==TK_IS );
70028       testcase( op==TK_ISNOT );
70029       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70030       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70031       op = (op==TK_IS) ? TK_EQ : TK_NE;
70032       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70033                   r1, r2, dest, SQLITE_NULLEQ);
70034       testcase( regFree1==0 );
70035       testcase( regFree2==0 );
70036       break;
70037     }
70038     case TK_ISNULL:
70039     case TK_NOTNULL: {
70040       assert( TK_ISNULL==OP_IsNull );
70041       assert( TK_NOTNULL==OP_NotNull );
70042       testcase( op==TK_ISNULL );
70043       testcase( op==TK_NOTNULL );
70044       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70045       sqlite3VdbeAddOp2(v, op, r1, dest);
70046       testcase( regFree1==0 );
70047       break;
70048     }
70049     case TK_BETWEEN: {
70050       testcase( jumpIfNull==0 );
70051       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
70052       break;
70053     }
70054     case TK_IN: {
70055       int destIfFalse = sqlite3VdbeMakeLabel(v);
70056       int destIfNull = jumpIfNull ? dest : destIfFalse;
70057       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
70058       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
70059       sqlite3VdbeResolveLabel(v, destIfFalse);
70060       break;
70061     }
70062     default: {
70063       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
70064       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
70065       testcase( regFree1==0 );
70066       testcase( jumpIfNull==0 );
70067       break;
70068     }
70069   }
70070   sqlite3ReleaseTempReg(pParse, regFree1);
70071   sqlite3ReleaseTempReg(pParse, regFree2);  
70072 }
70073
70074 /*
70075 ** Generate code for a boolean expression such that a jump is made
70076 ** to the label "dest" if the expression is false but execution
70077 ** continues straight thru if the expression is true.
70078 **
70079 ** If the expression evaluates to NULL (neither true nor false) then
70080 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
70081 ** is 0.
70082 */
70083 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
70084   Vdbe *v = pParse->pVdbe;
70085   int op = 0;
70086   int regFree1 = 0;
70087   int regFree2 = 0;
70088   int r1, r2;
70089
70090   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
70091   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
70092   if( pExpr==0 )    return;
70093
70094   /* The value of pExpr->op and op are related as follows:
70095   **
70096   **       pExpr->op            op
70097   **       ---------          ----------
70098   **       TK_ISNULL          OP_NotNull
70099   **       TK_NOTNULL         OP_IsNull
70100   **       TK_NE              OP_Eq
70101   **       TK_EQ              OP_Ne
70102   **       TK_GT              OP_Le
70103   **       TK_LE              OP_Gt
70104   **       TK_GE              OP_Lt
70105   **       TK_LT              OP_Ge
70106   **
70107   ** For other values of pExpr->op, op is undefined and unused.
70108   ** The value of TK_ and OP_ constants are arranged such that we
70109   ** can compute the mapping above using the following expression.
70110   ** Assert()s verify that the computation is correct.
70111   */
70112   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
70113
70114   /* Verify correct alignment of TK_ and OP_ constants
70115   */
70116   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
70117   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
70118   assert( pExpr->op!=TK_NE || op==OP_Eq );
70119   assert( pExpr->op!=TK_EQ || op==OP_Ne );
70120   assert( pExpr->op!=TK_LT || op==OP_Ge );
70121   assert( pExpr->op!=TK_LE || op==OP_Gt );
70122   assert( pExpr->op!=TK_GT || op==OP_Le );
70123   assert( pExpr->op!=TK_GE || op==OP_Lt );
70124
70125   switch( pExpr->op ){
70126     case TK_AND: {
70127       testcase( jumpIfNull==0 );
70128       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
70129       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
70130       break;
70131     }
70132     case TK_OR: {
70133       int d2 = sqlite3VdbeMakeLabel(v);
70134       testcase( jumpIfNull==0 );
70135       sqlite3ExprCachePush(pParse);
70136       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
70137       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
70138       sqlite3VdbeResolveLabel(v, d2);
70139       sqlite3ExprCachePop(pParse, 1);
70140       break;
70141     }
70142     case TK_NOT: {
70143       testcase( jumpIfNull==0 );
70144       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
70145       break;
70146     }
70147     case TK_LT:
70148     case TK_LE:
70149     case TK_GT:
70150     case TK_GE:
70151     case TK_NE:
70152     case TK_EQ: {
70153       testcase( op==TK_LT );
70154       testcase( op==TK_LE );
70155       testcase( op==TK_GT );
70156       testcase( op==TK_GE );
70157       testcase( op==TK_EQ );
70158       testcase( op==TK_NE );
70159       testcase( jumpIfNull==0 );
70160       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70161       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70162       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70163                   r1, r2, dest, jumpIfNull);
70164       testcase( regFree1==0 );
70165       testcase( regFree2==0 );
70166       break;
70167     }
70168     case TK_IS:
70169     case TK_ISNOT: {
70170       testcase( pExpr->op==TK_IS );
70171       testcase( pExpr->op==TK_ISNOT );
70172       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70173       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70174       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
70175       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70176                   r1, r2, dest, SQLITE_NULLEQ);
70177       testcase( regFree1==0 );
70178       testcase( regFree2==0 );
70179       break;
70180     }
70181     case TK_ISNULL:
70182     case TK_NOTNULL: {
70183       testcase( op==TK_ISNULL );
70184       testcase( op==TK_NOTNULL );
70185       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70186       sqlite3VdbeAddOp2(v, op, r1, dest);
70187       testcase( regFree1==0 );
70188       break;
70189     }
70190     case TK_BETWEEN: {
70191       testcase( jumpIfNull==0 );
70192       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
70193       break;
70194     }
70195     case TK_IN: {
70196       if( jumpIfNull ){
70197         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
70198       }else{
70199         int destIfNull = sqlite3VdbeMakeLabel(v);
70200         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
70201         sqlite3VdbeResolveLabel(v, destIfNull);
70202       }
70203       break;
70204     }
70205     default: {
70206       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
70207       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
70208       testcase( regFree1==0 );
70209       testcase( jumpIfNull==0 );
70210       break;
70211     }
70212   }
70213   sqlite3ReleaseTempReg(pParse, regFree1);
70214   sqlite3ReleaseTempReg(pParse, regFree2);
70215 }
70216
70217 /*
70218 ** Do a deep comparison of two expression trees.  Return 0 if the two
70219 ** expressions are completely identical.  Return 1 if they differ only
70220 ** by a COLLATE operator at the top level.  Return 2 if there are differences
70221 ** other than the top-level COLLATE operator.
70222 **
70223 ** Sometimes this routine will return 2 even if the two expressions
70224 ** really are equivalent.  If we cannot prove that the expressions are
70225 ** identical, we return 2 just to be safe.  So if this routine
70226 ** returns 2, then you do not really know for certain if the two
70227 ** expressions are the same.  But if you get a 0 or 1 return, then you
70228 ** can be sure the expressions are the same.  In the places where
70229 ** this routine is used, it does not hurt to get an extra 2 - that
70230 ** just might result in some slightly slower code.  But returning
70231 ** an incorrect 0 or 1 could lead to a malfunction.
70232 */
70233 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
70234   if( pA==0||pB==0 ){
70235     return pB==pA ? 0 : 2;
70236   }
70237   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
70238   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
70239   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
70240     return 2;
70241   }
70242   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
70243   if( pA->op!=pB->op ) return 2;
70244   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
70245   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
70246   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
70247   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
70248   if( ExprHasProperty(pA, EP_IntValue) ){
70249     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
70250       return 2;
70251     }
70252   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
70253     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
70254     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
70255       return 2;
70256     }
70257   }
70258   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
70259   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
70260   return 0;
70261 }
70262
70263 /*
70264 ** Compare two ExprList objects.  Return 0 if they are identical and 
70265 ** non-zero if they differ in any way.
70266 **
70267 ** This routine might return non-zero for equivalent ExprLists.  The
70268 ** only consequence will be disabled optimizations.  But this routine
70269 ** must never return 0 if the two ExprList objects are different, or
70270 ** a malfunction will result.
70271 **
70272 ** Two NULL pointers are considered to be the same.  But a NULL pointer
70273 ** always differs from a non-NULL pointer.
70274 */
70275 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
70276   int i;
70277   if( pA==0 && pB==0 ) return 0;
70278   if( pA==0 || pB==0 ) return 1;
70279   if( pA->nExpr!=pB->nExpr ) return 1;
70280   for(i=0; i<pA->nExpr; i++){
70281     Expr *pExprA = pA->a[i].pExpr;
70282     Expr *pExprB = pB->a[i].pExpr;
70283     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
70284     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
70285   }
70286   return 0;
70287 }
70288
70289 /*
70290 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
70291 ** the new element.  Return a negative number if malloc fails.
70292 */
70293 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
70294   int i;
70295   pInfo->aCol = sqlite3ArrayAllocate(
70296        db,
70297        pInfo->aCol,
70298        sizeof(pInfo->aCol[0]),
70299        3,
70300        &pInfo->nColumn,
70301        &pInfo->nColumnAlloc,
70302        &i
70303   );
70304   return i;
70305 }    
70306
70307 /*
70308 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
70309 ** the new element.  Return a negative number if malloc fails.
70310 */
70311 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
70312   int i;
70313   pInfo->aFunc = sqlite3ArrayAllocate(
70314        db, 
70315        pInfo->aFunc,
70316        sizeof(pInfo->aFunc[0]),
70317        3,
70318        &pInfo->nFunc,
70319        &pInfo->nFuncAlloc,
70320        &i
70321   );
70322   return i;
70323 }    
70324
70325 /*
70326 ** This is the xExprCallback for a tree walker.  It is used to
70327 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
70328 ** for additional information.
70329 */
70330 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
70331   int i;
70332   NameContext *pNC = pWalker->u.pNC;
70333   Parse *pParse = pNC->pParse;
70334   SrcList *pSrcList = pNC->pSrcList;
70335   AggInfo *pAggInfo = pNC->pAggInfo;
70336
70337   switch( pExpr->op ){
70338     case TK_AGG_COLUMN:
70339     case TK_COLUMN: {
70340       testcase( pExpr->op==TK_AGG_COLUMN );
70341       testcase( pExpr->op==TK_COLUMN );
70342       /* Check to see if the column is in one of the tables in the FROM
70343       ** clause of the aggregate query */
70344       if( ALWAYS(pSrcList!=0) ){
70345         struct SrcList_item *pItem = pSrcList->a;
70346         for(i=0; i<pSrcList->nSrc; i++, pItem++){
70347           struct AggInfo_col *pCol;
70348           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70349           if( pExpr->iTable==pItem->iCursor ){
70350             /* If we reach this point, it means that pExpr refers to a table
70351             ** that is in the FROM clause of the aggregate query.  
70352             **
70353             ** Make an entry for the column in pAggInfo->aCol[] if there
70354             ** is not an entry there already.
70355             */
70356             int k;
70357             pCol = pAggInfo->aCol;
70358             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
70359               if( pCol->iTable==pExpr->iTable &&
70360                   pCol->iColumn==pExpr->iColumn ){
70361                 break;
70362               }
70363             }
70364             if( (k>=pAggInfo->nColumn)
70365              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
70366             ){
70367               pCol = &pAggInfo->aCol[k];
70368               pCol->pTab = pExpr->pTab;
70369               pCol->iTable = pExpr->iTable;
70370               pCol->iColumn = pExpr->iColumn;
70371               pCol->iMem = ++pParse->nMem;
70372               pCol->iSorterColumn = -1;
70373               pCol->pExpr = pExpr;
70374               if( pAggInfo->pGroupBy ){
70375                 int j, n;
70376                 ExprList *pGB = pAggInfo->pGroupBy;
70377                 struct ExprList_item *pTerm = pGB->a;
70378                 n = pGB->nExpr;
70379                 for(j=0; j<n; j++, pTerm++){
70380                   Expr *pE = pTerm->pExpr;
70381                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
70382                       pE->iColumn==pExpr->iColumn ){
70383                     pCol->iSorterColumn = j;
70384                     break;
70385                   }
70386                 }
70387               }
70388               if( pCol->iSorterColumn<0 ){
70389                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
70390               }
70391             }
70392             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
70393             ** because it was there before or because we just created it).
70394             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
70395             ** pAggInfo->aCol[] entry.
70396             */
70397             ExprSetIrreducible(pExpr);
70398             pExpr->pAggInfo = pAggInfo;
70399             pExpr->op = TK_AGG_COLUMN;
70400             pExpr->iAgg = (i16)k;
70401             break;
70402           } /* endif pExpr->iTable==pItem->iCursor */
70403         } /* end loop over pSrcList */
70404       }
70405       return WRC_Prune;
70406     }
70407     case TK_AGG_FUNCTION: {
70408       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
70409       ** to be ignored */
70410       if( pNC->nDepth==0 ){
70411         /* Check to see if pExpr is a duplicate of another aggregate 
70412         ** function that is already in the pAggInfo structure
70413         */
70414         struct AggInfo_func *pItem = pAggInfo->aFunc;
70415         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
70416           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
70417             break;
70418           }
70419         }
70420         if( i>=pAggInfo->nFunc ){
70421           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
70422           */
70423           u8 enc = ENC(pParse->db);
70424           i = addAggInfoFunc(pParse->db, pAggInfo);
70425           if( i>=0 ){
70426             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70427             pItem = &pAggInfo->aFunc[i];
70428             pItem->pExpr = pExpr;
70429             pItem->iMem = ++pParse->nMem;
70430             assert( !ExprHasProperty(pExpr, EP_IntValue) );
70431             pItem->pFunc = sqlite3FindFunction(pParse->db,
70432                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
70433                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
70434             if( pExpr->flags & EP_Distinct ){
70435               pItem->iDistinct = pParse->nTab++;
70436             }else{
70437               pItem->iDistinct = -1;
70438             }
70439           }
70440         }
70441         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
70442         */
70443         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70444         ExprSetIrreducible(pExpr);
70445         pExpr->iAgg = (i16)i;
70446         pExpr->pAggInfo = pAggInfo;
70447         return WRC_Prune;
70448       }
70449     }
70450   }
70451   return WRC_Continue;
70452 }
70453 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
70454   NameContext *pNC = pWalker->u.pNC;
70455   if( pNC->nDepth==0 ){
70456     pNC->nDepth++;
70457     sqlite3WalkSelect(pWalker, pSelect);
70458     pNC->nDepth--;
70459     return WRC_Prune;
70460   }else{
70461     return WRC_Continue;
70462   }
70463 }
70464
70465 /*
70466 ** Analyze the given expression looking for aggregate functions and
70467 ** for variables that need to be added to the pParse->aAgg[] array.
70468 ** Make additional entries to the pParse->aAgg[] array as necessary.
70469 **
70470 ** This routine should only be called after the expression has been
70471 ** analyzed by sqlite3ResolveExprNames().
70472 */
70473 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
70474   Walker w;
70475   w.xExprCallback = analyzeAggregate;
70476   w.xSelectCallback = analyzeAggregatesInSelect;
70477   w.u.pNC = pNC;
70478   assert( pNC->pSrcList!=0 );
70479   sqlite3WalkExpr(&w, pExpr);
70480 }
70481
70482 /*
70483 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
70484 ** expression list.  Return the number of errors.
70485 **
70486 ** If an error is found, the analysis is cut short.
70487 */
70488 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
70489   struct ExprList_item *pItem;
70490   int i;
70491   if( pList ){
70492     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
70493       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
70494     }
70495   }
70496 }
70497
70498 /*
70499 ** Allocate a single new register for use to hold some intermediate result.
70500 */
70501 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
70502   if( pParse->nTempReg==0 ){
70503     return ++pParse->nMem;
70504   }
70505   return pParse->aTempReg[--pParse->nTempReg];
70506 }
70507
70508 /*
70509 ** Deallocate a register, making available for reuse for some other
70510 ** purpose.
70511 **
70512 ** If a register is currently being used by the column cache, then
70513 ** the dallocation is deferred until the column cache line that uses
70514 ** the register becomes stale.
70515 */
70516 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
70517   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70518     int i;
70519     struct yColCache *p;
70520     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70521       if( p->iReg==iReg ){
70522         p->tempReg = 1;
70523         return;
70524       }
70525     }
70526     pParse->aTempReg[pParse->nTempReg++] = iReg;
70527   }
70528 }
70529
70530 /*
70531 ** Allocate or deallocate a block of nReg consecutive registers
70532 */
70533 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
70534   int i, n;
70535   i = pParse->iRangeReg;
70536   n = pParse->nRangeReg;
70537   if( nReg<=n ){
70538     assert( !usedAsColumnCache(pParse, i, i+n-1) );
70539     pParse->iRangeReg += nReg;
70540     pParse->nRangeReg -= nReg;
70541   }else{
70542     i = pParse->nMem+1;
70543     pParse->nMem += nReg;
70544   }
70545   return i;
70546 }
70547 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
70548   sqlite3ExprCacheRemove(pParse, iReg, nReg);
70549   if( nReg>pParse->nRangeReg ){
70550     pParse->nRangeReg = nReg;
70551     pParse->iRangeReg = iReg;
70552   }
70553 }
70554
70555 /************** End of expr.c ************************************************/
70556 /************** Begin file alter.c *******************************************/
70557 /*
70558 ** 2005 February 15
70559 **
70560 ** The author disclaims copyright to this source code.  In place of
70561 ** a legal notice, here is a blessing:
70562 **
70563 **    May you do good and not evil.
70564 **    May you find forgiveness for yourself and forgive others.
70565 **    May you share freely, never taking more than you give.
70566 **
70567 *************************************************************************
70568 ** This file contains C code routines that used to generate VDBE code
70569 ** that implements the ALTER TABLE command.
70570 */
70571
70572 /*
70573 ** The code in this file only exists if we are not omitting the
70574 ** ALTER TABLE logic from the build.
70575 */
70576 #ifndef SQLITE_OMIT_ALTERTABLE
70577
70578
70579 /*
70580 ** This function is used by SQL generated to implement the 
70581 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
70582 ** CREATE INDEX command. The second is a table name. The table name in 
70583 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
70584 ** argument and the result returned. Examples:
70585 **
70586 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
70587 **     -> 'CREATE TABLE def(a, b, c)'
70588 **
70589 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
70590 **     -> 'CREATE INDEX i ON def(a, b, c)'
70591 */
70592 static void renameTableFunc(
70593   sqlite3_context *context,
70594   int NotUsed,
70595   sqlite3_value **argv
70596 ){
70597   unsigned char const *zSql = sqlite3_value_text(argv[0]);
70598   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70599
70600   int token;
70601   Token tname;
70602   unsigned char const *zCsr = zSql;
70603   int len = 0;
70604   char *zRet;
70605
70606   sqlite3 *db = sqlite3_context_db_handle(context);
70607
70608   UNUSED_PARAMETER(NotUsed);
70609
70610   /* The principle used to locate the table name in the CREATE TABLE 
70611   ** statement is that the table name is the first non-space token that
70612   ** is immediately followed by a TK_LP or TK_USING token.
70613   */
70614   if( zSql ){
70615     do {
70616       if( !*zCsr ){
70617         /* Ran out of input before finding an opening bracket. Return NULL. */
70618         return;
70619       }
70620
70621       /* Store the token that zCsr points to in tname. */
70622       tname.z = (char*)zCsr;
70623       tname.n = len;
70624
70625       /* Advance zCsr to the next token. Store that token type in 'token',
70626       ** and its length in 'len' (to be used next iteration of this loop).
70627       */
70628       do {
70629         zCsr += len;
70630         len = sqlite3GetToken(zCsr, &token);
70631       } while( token==TK_SPACE );
70632       assert( len>0 );
70633     } while( token!=TK_LP && token!=TK_USING );
70634
70635     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
70636        zTableName, tname.z+tname.n);
70637     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70638   }
70639 }
70640
70641 /*
70642 ** This C function implements an SQL user function that is used by SQL code
70643 ** generated by the ALTER TABLE ... RENAME command to modify the definition
70644 ** of any foreign key constraints that use the table being renamed as the 
70645 ** parent table. It is passed three arguments:
70646 **
70647 **   1) The complete text of the CREATE TABLE statement being modified,
70648 **   2) The old name of the table being renamed, and
70649 **   3) The new name of the table being renamed.
70650 **
70651 ** It returns the new CREATE TABLE statement. For example:
70652 **
70653 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
70654 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
70655 */
70656 #ifndef SQLITE_OMIT_FOREIGN_KEY
70657 static void renameParentFunc(
70658   sqlite3_context *context,
70659   int NotUsed,
70660   sqlite3_value **argv
70661 ){
70662   sqlite3 *db = sqlite3_context_db_handle(context);
70663   char *zOutput = 0;
70664   char *zResult;
70665   unsigned char const *zInput = sqlite3_value_text(argv[0]);
70666   unsigned char const *zOld = sqlite3_value_text(argv[1]);
70667   unsigned char const *zNew = sqlite3_value_text(argv[2]);
70668
70669   unsigned const char *z;         /* Pointer to token */
70670   int n;                          /* Length of token z */
70671   int token;                      /* Type of token */
70672
70673   UNUSED_PARAMETER(NotUsed);
70674   for(z=zInput; *z; z=z+n){
70675     n = sqlite3GetToken(z, &token);
70676     if( token==TK_REFERENCES ){
70677       char *zParent;
70678       do {
70679         z += n;
70680         n = sqlite3GetToken(z, &token);
70681       }while( token==TK_SPACE );
70682
70683       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
70684       if( zParent==0 ) break;
70685       sqlite3Dequote(zParent);
70686       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
70687         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
70688             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
70689         );
70690         sqlite3DbFree(db, zOutput);
70691         zOutput = zOut;
70692         zInput = &z[n];
70693       }
70694       sqlite3DbFree(db, zParent);
70695     }
70696   }
70697
70698   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
70699   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
70700   sqlite3DbFree(db, zOutput);
70701 }
70702 #endif
70703
70704 #ifndef SQLITE_OMIT_TRIGGER
70705 /* This function is used by SQL generated to implement the
70706 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
70707 ** statement. The second is a table name. The table name in the CREATE 
70708 ** TRIGGER statement is replaced with the third argument and the result 
70709 ** returned. This is analagous to renameTableFunc() above, except for CREATE
70710 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
70711 */
70712 static void renameTriggerFunc(
70713   sqlite3_context *context,
70714   int NotUsed,
70715   sqlite3_value **argv
70716 ){
70717   unsigned char const *zSql = sqlite3_value_text(argv[0]);
70718   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70719
70720   int token;
70721   Token tname;
70722   int dist = 3;
70723   unsigned char const *zCsr = zSql;
70724   int len = 0;
70725   char *zRet;
70726   sqlite3 *db = sqlite3_context_db_handle(context);
70727
70728   UNUSED_PARAMETER(NotUsed);
70729
70730   /* The principle used to locate the table name in the CREATE TRIGGER 
70731   ** statement is that the table name is the first token that is immediatedly
70732   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
70733   ** of TK_WHEN, TK_BEGIN or TK_FOR.
70734   */
70735   if( zSql ){
70736     do {
70737
70738       if( !*zCsr ){
70739         /* Ran out of input before finding the table name. Return NULL. */
70740         return;
70741       }
70742
70743       /* Store the token that zCsr points to in tname. */
70744       tname.z = (char*)zCsr;
70745       tname.n = len;
70746
70747       /* Advance zCsr to the next token. Store that token type in 'token',
70748       ** and its length in 'len' (to be used next iteration of this loop).
70749       */
70750       do {
70751         zCsr += len;
70752         len = sqlite3GetToken(zCsr, &token);
70753       }while( token==TK_SPACE );
70754       assert( len>0 );
70755
70756       /* Variable 'dist' stores the number of tokens read since the most
70757       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
70758       ** token is read and 'dist' equals 2, the condition stated above
70759       ** to be met.
70760       **
70761       ** Note that ON cannot be a database, table or column name, so
70762       ** there is no need to worry about syntax like 
70763       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
70764       */
70765       dist++;
70766       if( token==TK_DOT || token==TK_ON ){
70767         dist = 0;
70768       }
70769     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
70770
70771     /* Variable tname now contains the token that is the old table-name
70772     ** in the CREATE TRIGGER statement.
70773     */
70774     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
70775        zTableName, tname.z+tname.n);
70776     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70777   }
70778 }
70779 #endif   /* !SQLITE_OMIT_TRIGGER */
70780
70781 /*
70782 ** Register built-in functions used to help implement ALTER TABLE
70783 */
70784 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
70785   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
70786     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
70787 #ifndef SQLITE_OMIT_TRIGGER
70788     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
70789 #endif
70790 #ifndef SQLITE_OMIT_FOREIGN_KEY
70791     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
70792 #endif
70793   };
70794   int i;
70795   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70796   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
70797
70798   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
70799     sqlite3FuncDefInsert(pHash, &aFunc[i]);
70800   }
70801 }
70802
70803 /*
70804 ** This function is used to create the text of expressions of the form:
70805 **
70806 **   name=<constant1> OR name=<constant2> OR ...
70807 **
70808 ** If argument zWhere is NULL, then a pointer string containing the text 
70809 ** "name=<constant>" is returned, where <constant> is the quoted version
70810 ** of the string passed as argument zConstant. The returned buffer is
70811 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
70812 ** caller to ensure that it is eventually freed.
70813 **
70814 ** If argument zWhere is not NULL, then the string returned is 
70815 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
70816 ** In this case zWhere is passed to sqlite3DbFree() before returning.
70817 ** 
70818 */
70819 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
70820   char *zNew;
70821   if( !zWhere ){
70822     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
70823   }else{
70824     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
70825     sqlite3DbFree(db, zWhere);
70826   }
70827   return zNew;
70828 }
70829
70830 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
70831 /*
70832 ** Generate the text of a WHERE expression which can be used to select all
70833 ** tables that have foreign key constraints that refer to table pTab (i.e.
70834 ** constraints for which pTab is the parent table) from the sqlite_master
70835 ** table.
70836 */
70837 static char *whereForeignKeys(Parse *pParse, Table *pTab){
70838   FKey *p;
70839   char *zWhere = 0;
70840   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
70841     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
70842   }
70843   return zWhere;
70844 }
70845 #endif
70846
70847 /*
70848 ** Generate the text of a WHERE expression which can be used to select all
70849 ** temporary triggers on table pTab from the sqlite_temp_master table. If
70850 ** table pTab has no temporary triggers, or is itself stored in the 
70851 ** temporary database, NULL is returned.
70852 */
70853 static char *whereTempTriggers(Parse *pParse, Table *pTab){
70854   Trigger *pTrig;
70855   char *zWhere = 0;
70856   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
70857
70858   /* If the table is not located in the temp-db (in which case NULL is 
70859   ** returned, loop through the tables list of triggers. For each trigger
70860   ** that is not part of the temp-db schema, add a clause to the WHERE 
70861   ** expression being built up in zWhere.
70862   */
70863   if( pTab->pSchema!=pTempSchema ){
70864     sqlite3 *db = pParse->db;
70865     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70866       if( pTrig->pSchema==pTempSchema ){
70867         zWhere = whereOrName(db, zWhere, pTrig->zName);
70868       }
70869     }
70870   }
70871   return zWhere;
70872 }
70873
70874 /*
70875 ** Generate code to drop and reload the internal representation of table
70876 ** pTab from the database, including triggers and temporary triggers.
70877 ** Argument zName is the name of the table in the database schema at
70878 ** the time the generated code is executed. This can be different from
70879 ** pTab->zName if this function is being called to code part of an 
70880 ** "ALTER TABLE RENAME TO" statement.
70881 */
70882 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
70883   Vdbe *v;
70884   char *zWhere;
70885   int iDb;                   /* Index of database containing pTab */
70886 #ifndef SQLITE_OMIT_TRIGGER
70887   Trigger *pTrig;
70888 #endif
70889
70890   v = sqlite3GetVdbe(pParse);
70891   if( NEVER(v==0) ) return;
70892   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70893   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70894   assert( iDb>=0 );
70895
70896 #ifndef SQLITE_OMIT_TRIGGER
70897   /* Drop any table triggers from the internal schema. */
70898   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70899     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
70900     assert( iTrigDb==iDb || iTrigDb==1 );
70901     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
70902   }
70903 #endif
70904
70905   /* Drop the table and index from the internal schema.  */
70906   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
70907
70908   /* Reload the table, index and permanent trigger schemas. */
70909   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
70910   if( !zWhere ) return;
70911   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70912
70913 #ifndef SQLITE_OMIT_TRIGGER
70914   /* Now, if the table is not stored in the temp database, reload any temp 
70915   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
70916   */
70917   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
70918     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
70919   }
70920 #endif
70921 }
70922
70923 /*
70924 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
70925 ** command. 
70926 */
70927 SQLITE_PRIVATE void sqlite3AlterRenameTable(
70928   Parse *pParse,            /* Parser context. */
70929   SrcList *pSrc,            /* The table to rename. */
70930   Token *pName              /* The new table name. */
70931 ){
70932   int iDb;                  /* Database that contains the table */
70933   char *zDb;                /* Name of database iDb */
70934   Table *pTab;              /* Table being renamed */
70935   char *zName = 0;          /* NULL-terminated version of pName */ 
70936   sqlite3 *db = pParse->db; /* Database connection */
70937   int nTabName;             /* Number of UTF-8 characters in zTabName */
70938   const char *zTabName;     /* Original name of the table */
70939   Vdbe *v;
70940 #ifndef SQLITE_OMIT_TRIGGER
70941   char *zWhere = 0;         /* Where clause to locate temp triggers */
70942 #endif
70943   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
70944   int savedDbFlags;         /* Saved value of db->flags */
70945
70946   savedDbFlags = db->flags;  
70947   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
70948   assert( pSrc->nSrc==1 );
70949   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70950
70951   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
70952   if( !pTab ) goto exit_rename_table;
70953   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70954   zDb = db->aDb[iDb].zName;
70955   db->flags |= SQLITE_PreferBuiltin;
70956
70957   /* Get a NULL terminated version of the new table name. */
70958   zName = sqlite3NameFromToken(db, pName);
70959   if( !zName ) goto exit_rename_table;
70960
70961   /* Check that a table or index named 'zName' does not already exist
70962   ** in database iDb. If so, this is an error.
70963   */
70964   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
70965     sqlite3ErrorMsg(pParse, 
70966         "there is already another table or index with this name: %s", zName);
70967     goto exit_rename_table;
70968   }
70969
70970   /* Make sure it is not a system table being altered, or a reserved name
70971   ** that the table is being renamed to.
70972   */
70973   if( sqlite3Strlen30(pTab->zName)>6 
70974    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
70975   ){
70976     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
70977     goto exit_rename_table;
70978   }
70979   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
70980     goto exit_rename_table;
70981   }
70982
70983 #ifndef SQLITE_OMIT_VIEW
70984   if( pTab->pSelect ){
70985     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
70986     goto exit_rename_table;
70987   }
70988 #endif
70989
70990 #ifndef SQLITE_OMIT_AUTHORIZATION
70991   /* Invoke the authorization callback. */
70992   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
70993     goto exit_rename_table;
70994   }
70995 #endif
70996
70997 #ifndef SQLITE_OMIT_VIRTUALTABLE
70998   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70999     goto exit_rename_table;
71000   }
71001   if( IsVirtual(pTab) ){
71002     pVTab = sqlite3GetVTable(db, pTab);
71003     if( pVTab->pVtab->pModule->xRename==0 ){
71004       pVTab = 0;
71005     }
71006   }
71007 #endif
71008
71009   /* Begin a transaction and code the VerifyCookie for database iDb. 
71010   ** Then modify the schema cookie (since the ALTER TABLE modifies the
71011   ** schema). Open a statement transaction if the table is a virtual
71012   ** table.
71013   */
71014   v = sqlite3GetVdbe(pParse);
71015   if( v==0 ){
71016     goto exit_rename_table;
71017   }
71018   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
71019   sqlite3ChangeCookie(pParse, iDb);
71020
71021   /* If this is a virtual table, invoke the xRename() function if
71022   ** one is defined. The xRename() callback will modify the names
71023   ** of any resources used by the v-table implementation (including other
71024   ** SQLite tables) that are identified by the name of the virtual table.
71025   */
71026 #ifndef SQLITE_OMIT_VIRTUALTABLE
71027   if( pVTab ){
71028     int i = ++pParse->nMem;
71029     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
71030     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
71031     sqlite3MayAbort(pParse);
71032   }
71033 #endif
71034
71035   /* figure out how many UTF-8 characters are in zName */
71036   zTabName = pTab->zName;
71037   nTabName = sqlite3Utf8CharLen(zTabName, -1);
71038
71039 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71040   if( db->flags&SQLITE_ForeignKeys ){
71041     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
71042     ** statements corresponding to all child tables of foreign key constraints
71043     ** for which the renamed table is the parent table.  */
71044     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
71045       sqlite3NestedParse(pParse, 
71046           "UPDATE \"%w\".%s SET "
71047               "sql = sqlite_rename_parent(sql, %Q, %Q) "
71048               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
71049       sqlite3DbFree(db, zWhere);
71050     }
71051   }
71052 #endif
71053
71054   /* Modify the sqlite_master table to use the new table name. */
71055   sqlite3NestedParse(pParse,
71056       "UPDATE %Q.%s SET "
71057 #ifdef SQLITE_OMIT_TRIGGER
71058           "sql = sqlite_rename_table(sql, %Q), "
71059 #else
71060           "sql = CASE "
71061             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
71062             "ELSE sqlite_rename_table(sql, %Q) END, "
71063 #endif
71064           "tbl_name = %Q, "
71065           "name = CASE "
71066             "WHEN type='table' THEN %Q "
71067             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
71068              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
71069             "ELSE name END "
71070       "WHERE tbl_name=%Q AND "
71071           "(type='table' OR type='index' OR type='trigger');", 
71072       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
71073 #ifndef SQLITE_OMIT_TRIGGER
71074       zName,
71075 #endif
71076       zName, nTabName, zTabName
71077   );
71078
71079 #ifndef SQLITE_OMIT_AUTOINCREMENT
71080   /* If the sqlite_sequence table exists in this database, then update 
71081   ** it with the new table name.
71082   */
71083   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
71084     sqlite3NestedParse(pParse,
71085         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
71086         zDb, zName, pTab->zName);
71087   }
71088 #endif
71089
71090 #ifndef SQLITE_OMIT_TRIGGER
71091   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
71092   ** table. Don't do this if the table being ALTERed is itself located in
71093   ** the temp database.
71094   */
71095   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
71096     sqlite3NestedParse(pParse, 
71097         "UPDATE sqlite_temp_master SET "
71098             "sql = sqlite_rename_trigger(sql, %Q), "
71099             "tbl_name = %Q "
71100             "WHERE %s;", zName, zName, zWhere);
71101     sqlite3DbFree(db, zWhere);
71102   }
71103 #endif
71104
71105 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71106   if( db->flags&SQLITE_ForeignKeys ){
71107     FKey *p;
71108     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
71109       Table *pFrom = p->pFrom;
71110       if( pFrom!=pTab ){
71111         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
71112       }
71113     }
71114   }
71115 #endif
71116
71117   /* Drop and reload the internal table schema. */
71118   reloadTableSchema(pParse, pTab, zName);
71119
71120 exit_rename_table:
71121   sqlite3SrcListDelete(db, pSrc);
71122   sqlite3DbFree(db, zName);
71123   db->flags = savedDbFlags;
71124 }
71125
71126
71127 /*
71128 ** Generate code to make sure the file format number is at least minFormat.
71129 ** The generated code will increase the file format number if necessary.
71130 */
71131 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
71132   Vdbe *v;
71133   v = sqlite3GetVdbe(pParse);
71134   /* The VDBE should have been allocated before this routine is called.
71135   ** If that allocation failed, we would have quit before reaching this
71136   ** point */
71137   if( ALWAYS(v) ){
71138     int r1 = sqlite3GetTempReg(pParse);
71139     int r2 = sqlite3GetTempReg(pParse);
71140     int j1;
71141     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
71142     sqlite3VdbeUsesBtree(v, iDb);
71143     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
71144     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
71145     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
71146     sqlite3VdbeJumpHere(v, j1);
71147     sqlite3ReleaseTempReg(pParse, r1);
71148     sqlite3ReleaseTempReg(pParse, r2);
71149   }
71150 }
71151
71152 /*
71153 ** This function is called after an "ALTER TABLE ... ADD" statement
71154 ** has been parsed. Argument pColDef contains the text of the new
71155 ** column definition.
71156 **
71157 ** The Table structure pParse->pNewTable was extended to include
71158 ** the new column during parsing.
71159 */
71160 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
71161   Table *pNew;              /* Copy of pParse->pNewTable */
71162   Table *pTab;              /* Table being altered */
71163   int iDb;                  /* Database number */
71164   const char *zDb;          /* Database name */
71165   const char *zTab;         /* Table name */
71166   char *zCol;               /* Null-terminated column definition */
71167   Column *pCol;             /* The new column */
71168   Expr *pDflt;              /* Default value for the new column */
71169   sqlite3 *db;              /* The database connection; */
71170
71171   db = pParse->db;
71172   if( pParse->nErr || db->mallocFailed ) return;
71173   pNew = pParse->pNewTable;
71174   assert( pNew );
71175
71176   assert( sqlite3BtreeHoldsAllMutexes(db) );
71177   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
71178   zDb = db->aDb[iDb].zName;
71179   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
71180   pCol = &pNew->aCol[pNew->nCol-1];
71181   pDflt = pCol->pDflt;
71182   pTab = sqlite3FindTable(db, zTab, zDb);
71183   assert( pTab );
71184
71185 #ifndef SQLITE_OMIT_AUTHORIZATION
71186   /* Invoke the authorization callback. */
71187   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
71188     return;
71189   }
71190 #endif
71191
71192   /* If the default value for the new column was specified with a 
71193   ** literal NULL, then set pDflt to 0. This simplifies checking
71194   ** for an SQL NULL default below.
71195   */
71196   if( pDflt && pDflt->op==TK_NULL ){
71197     pDflt = 0;
71198   }
71199
71200   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
71201   ** If there is a NOT NULL constraint, then the default value for the
71202   ** column must not be NULL.
71203   */
71204   if( pCol->isPrimKey ){
71205     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
71206     return;
71207   }
71208   if( pNew->pIndex ){
71209     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
71210     return;
71211   }
71212   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
71213     sqlite3ErrorMsg(pParse, 
71214         "Cannot add a REFERENCES column with non-NULL default value");
71215     return;
71216   }
71217   if( pCol->notNull && !pDflt ){
71218     sqlite3ErrorMsg(pParse, 
71219         "Cannot add a NOT NULL column with default value NULL");
71220     return;
71221   }
71222
71223   /* Ensure the default expression is something that sqlite3ValueFromExpr()
71224   ** can handle (i.e. not CURRENT_TIME etc.)
71225   */
71226   if( pDflt ){
71227     sqlite3_value *pVal;
71228     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
71229       db->mallocFailed = 1;
71230       return;
71231     }
71232     if( !pVal ){
71233       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
71234       return;
71235     }
71236     sqlite3ValueFree(pVal);
71237   }
71238
71239   /* Modify the CREATE TABLE statement. */
71240   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
71241   if( zCol ){
71242     char *zEnd = &zCol[pColDef->n-1];
71243     int savedDbFlags = db->flags;
71244     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
71245       *zEnd-- = '\0';
71246     }
71247     db->flags |= SQLITE_PreferBuiltin;
71248     sqlite3NestedParse(pParse, 
71249         "UPDATE \"%w\".%s SET "
71250           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
71251         "WHERE type = 'table' AND name = %Q", 
71252       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
71253       zTab
71254     );
71255     sqlite3DbFree(db, zCol);
71256     db->flags = savedDbFlags;
71257   }
71258
71259   /* If the default value of the new column is NULL, then set the file
71260   ** format to 2. If the default value of the new column is not NULL,
71261   ** the file format becomes 3.
71262   */
71263   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
71264
71265   /* Reload the schema of the modified table. */
71266   reloadTableSchema(pParse, pTab, pTab->zName);
71267 }
71268
71269 /*
71270 ** This function is called by the parser after the table-name in
71271 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
71272 ** pSrc is the full-name of the table being altered.
71273 **
71274 ** This routine makes a (partial) copy of the Table structure
71275 ** for the table being altered and sets Parse.pNewTable to point
71276 ** to it. Routines called by the parser as the column definition
71277 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
71278 ** the copy. The copy of the Table structure is deleted by tokenize.c 
71279 ** after parsing is finished.
71280 **
71281 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
71282 ** coding the "ALTER TABLE ... ADD" statement.
71283 */
71284 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
71285   Table *pNew;
71286   Table *pTab;
71287   Vdbe *v;
71288   int iDb;
71289   int i;
71290   int nAlloc;
71291   sqlite3 *db = pParse->db;
71292
71293   /* Look up the table being altered. */
71294   assert( pParse->pNewTable==0 );
71295   assert( sqlite3BtreeHoldsAllMutexes(db) );
71296   if( db->mallocFailed ) goto exit_begin_add_column;
71297   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
71298   if( !pTab ) goto exit_begin_add_column;
71299
71300 #ifndef SQLITE_OMIT_VIRTUALTABLE
71301   if( IsVirtual(pTab) ){
71302     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
71303     goto exit_begin_add_column;
71304   }
71305 #endif
71306
71307   /* Make sure this is not an attempt to ALTER a view. */
71308   if( pTab->pSelect ){
71309     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
71310     goto exit_begin_add_column;
71311   }
71312
71313   assert( pTab->addColOffset>0 );
71314   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71315
71316   /* Put a copy of the Table struct in Parse.pNewTable for the
71317   ** sqlite3AddColumn() function and friends to modify.  But modify
71318   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
71319   ** prefix, we insure that the name will not collide with an existing
71320   ** table because user table are not allowed to have the "sqlite_"
71321   ** prefix on their name.
71322   */
71323   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
71324   if( !pNew ) goto exit_begin_add_column;
71325   pParse->pNewTable = pNew;
71326   pNew->nRef = 1;
71327   pNew->dbMem = pTab->dbMem;
71328   pNew->nCol = pTab->nCol;
71329   assert( pNew->nCol>0 );
71330   nAlloc = (((pNew->nCol-1)/8)*8)+8;
71331   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
71332   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
71333   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
71334   if( !pNew->aCol || !pNew->zName ){
71335     db->mallocFailed = 1;
71336     goto exit_begin_add_column;
71337   }
71338   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
71339   for(i=0; i<pNew->nCol; i++){
71340     Column *pCol = &pNew->aCol[i];
71341     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
71342     pCol->zColl = 0;
71343     pCol->zType = 0;
71344     pCol->pDflt = 0;
71345     pCol->zDflt = 0;
71346   }
71347   pNew->pSchema = db->aDb[iDb].pSchema;
71348   pNew->addColOffset = pTab->addColOffset;
71349   pNew->nRef = 1;
71350
71351   /* Begin a transaction and increment the schema cookie.  */
71352   sqlite3BeginWriteOperation(pParse, 0, iDb);
71353   v = sqlite3GetVdbe(pParse);
71354   if( !v ) goto exit_begin_add_column;
71355   sqlite3ChangeCookie(pParse, iDb);
71356
71357 exit_begin_add_column:
71358   sqlite3SrcListDelete(db, pSrc);
71359   return;
71360 }
71361 #endif  /* SQLITE_ALTER_TABLE */
71362
71363 /************** End of alter.c ***********************************************/
71364 /************** Begin file analyze.c *****************************************/
71365 /*
71366 ** 2005 July 8
71367 **
71368 ** The author disclaims copyright to this source code.  In place of
71369 ** a legal notice, here is a blessing:
71370 **
71371 **    May you do good and not evil.
71372 **    May you find forgiveness for yourself and forgive others.
71373 **    May you share freely, never taking more than you give.
71374 **
71375 *************************************************************************
71376 ** This file contains code associated with the ANALYZE command.
71377 */
71378 #ifndef SQLITE_OMIT_ANALYZE
71379
71380 /*
71381 ** This routine generates code that opens the sqlite_stat1 table for
71382 ** writing with cursor iStatCur. If the library was built with the
71383 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
71384 ** opened for writing using cursor (iStatCur+1)
71385 **
71386 ** If the sqlite_stat1 tables does not previously exist, it is created.
71387 ** Similarly, if the sqlite_stat2 table does not exist and the library
71388 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
71389 **
71390 ** Argument zWhere may be a pointer to a buffer containing a table name,
71391 ** or it may be a NULL pointer. If it is not NULL, then all entries in
71392 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
71393 ** with the named table are deleted. If zWhere==0, then code is generated
71394 ** to delete all stat table entries.
71395 */
71396 static void openStatTable(
71397   Parse *pParse,          /* Parsing context */
71398   int iDb,                /* The database we are looking in */
71399   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
71400   const char *zWhere      /* Delete entries associated with this table */
71401 ){
71402   static const struct {
71403     const char *zName;
71404     const char *zCols;
71405   } aTable[] = {
71406     { "sqlite_stat1", "tbl,idx,stat" },
71407 #ifdef SQLITE_ENABLE_STAT2
71408     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
71409 #endif
71410   };
71411
71412   int aRoot[] = {0, 0};
71413   u8 aCreateTbl[] = {0, 0};
71414
71415   int i;
71416   sqlite3 *db = pParse->db;
71417   Db *pDb;
71418   Vdbe *v = sqlite3GetVdbe(pParse);
71419   if( v==0 ) return;
71420   assert( sqlite3BtreeHoldsAllMutexes(db) );
71421   assert( sqlite3VdbeDb(v)==db );
71422   pDb = &db->aDb[iDb];
71423
71424   for(i=0; i<ArraySize(aTable); i++){
71425     const char *zTab = aTable[i].zName;
71426     Table *pStat;
71427     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
71428       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
71429       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
71430       ** of the new table in register pParse->regRoot. This is important 
71431       ** because the OpenWrite opcode below will be needing it. */
71432       sqlite3NestedParse(pParse,
71433           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
71434       );
71435       aRoot[i] = pParse->regRoot;
71436       aCreateTbl[i] = 1;
71437     }else{
71438       /* The table already exists. If zWhere is not NULL, delete all entries 
71439       ** associated with the table zWhere. If zWhere is NULL, delete the
71440       ** entire contents of the table. */
71441       aRoot[i] = pStat->tnum;
71442       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
71443       if( zWhere ){
71444         sqlite3NestedParse(pParse,
71445            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
71446         );
71447       }else{
71448         /* The sqlite_stat[12] table already exists.  Delete all rows. */
71449         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
71450       }
71451     }
71452   }
71453
71454   /* Open the sqlite_stat[12] tables for writing. */
71455   for(i=0; i<ArraySize(aTable); i++){
71456     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
71457     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
71458     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
71459   }
71460 }
71461
71462 /*
71463 ** Generate code to do an analysis of all indices associated with
71464 ** a single table.
71465 */
71466 static void analyzeOneTable(
71467   Parse *pParse,   /* Parser context */
71468   Table *pTab,     /* Table whose indices are to be analyzed */
71469   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
71470   int iMem         /* Available memory locations begin here */
71471 ){
71472   sqlite3 *db = pParse->db;    /* Database handle */
71473   Index *pIdx;                 /* An index to being analyzed */
71474   int iIdxCur;                 /* Cursor open on index being analyzed */
71475   Vdbe *v;                     /* The virtual machine being built up */
71476   int i;                       /* Loop counter */
71477   int topOfLoop;               /* The top of the loop */
71478   int endOfLoop;               /* The end of the loop */
71479   int addr;                    /* The address of an instruction */
71480   int iDb;                     /* Index of database containing pTab */
71481   int regTabname = iMem++;     /* Register containing table name */
71482   int regIdxname = iMem++;     /* Register containing index name */
71483   int regSampleno = iMem++;    /* Register containing next sample number */
71484   int regCol = iMem++;         /* Content of a column analyzed table */
71485   int regRec = iMem++;         /* Register holding completed record */
71486   int regTemp = iMem++;        /* Temporary use register */
71487   int regRowid = iMem++;       /* Rowid for the inserted record */
71488
71489 #ifdef SQLITE_ENABLE_STAT2
71490   int regTemp2 = iMem++;       /* Temporary use register */
71491   int regSamplerecno = iMem++; /* Index of next sample to record */
71492   int regRecno = iMem++;       /* Current sample index */
71493   int regLast = iMem++;        /* Index of last sample to record */
71494   int regFirst = iMem++;       /* Index of first sample to record */
71495 #endif
71496
71497   v = sqlite3GetVdbe(pParse);
71498   if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
71499     /* Do no analysis for tables that have no indices */
71500     return;
71501   }
71502   assert( sqlite3BtreeHoldsAllMutexes(db) );
71503   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71504   assert( iDb>=0 );
71505 #ifndef SQLITE_OMIT_AUTHORIZATION
71506   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
71507       db->aDb[iDb].zName ) ){
71508     return;
71509   }
71510 #endif
71511
71512   /* Establish a read-lock on the table at the shared-cache level. */
71513   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
71514
71515   iIdxCur = pParse->nTab++;
71516   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71517     int nCol = pIdx->nColumn;
71518     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
71519
71520     if( iMem+1+(nCol*2)>pParse->nMem ){
71521       pParse->nMem = iMem+1+(nCol*2);
71522     }
71523
71524     /* Open a cursor to the index to be analyzed. */
71525     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
71526     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
71527         (char *)pKey, P4_KEYINFO_HANDOFF);
71528     VdbeComment((v, "%s", pIdx->zName));
71529
71530     /* Populate the registers containing the table and index names. */
71531     if( pTab->pIndex==pIdx ){
71532       sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
71533     }
71534     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
71535
71536 #ifdef SQLITE_ENABLE_STAT2
71537
71538     /* If this iteration of the loop is generating code to analyze the
71539     ** first index in the pTab->pIndex list, then register regLast has
71540     ** not been populated. In this case populate it now.  */
71541     if( pTab->pIndex==pIdx ){
71542       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
71543       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
71544       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
71545
71546       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
71547       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
71548       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
71549       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
71550       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
71551       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
71552       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
71553       sqlite3VdbeJumpHere(v, addr);
71554     }
71555
71556     /* Zero the regSampleno and regRecno registers. */
71557     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
71558     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
71559     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
71560 #endif
71561
71562     /* The block of memory cells initialized here is used as follows.
71563     **
71564     **    iMem:                
71565     **        The total number of rows in the table.
71566     **
71567     **    iMem+1 .. iMem+nCol: 
71568     **        Number of distinct entries in index considering the 
71569     **        left-most N columns only, where N is between 1 and nCol, 
71570     **        inclusive.
71571     **
71572     **    iMem+nCol+1 .. Mem+2*nCol:  
71573     **        Previous value of indexed columns, from left to right.
71574     **
71575     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
71576     ** initialized to contain an SQL NULL.
71577     */
71578     for(i=0; i<=nCol; i++){
71579       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
71580     }
71581     for(i=0; i<nCol; i++){
71582       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
71583     }
71584
71585     /* Start the analysis loop. This loop runs through all the entries in
71586     ** the index b-tree.  */
71587     endOfLoop = sqlite3VdbeMakeLabel(v);
71588     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
71589     topOfLoop = sqlite3VdbeCurrentAddr(v);
71590     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
71591
71592     for(i=0; i<nCol; i++){
71593       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
71594 #ifdef SQLITE_ENABLE_STAT2
71595       if( i==0 ){
71596         /* Check if the record that cursor iIdxCur points to contains a
71597         ** value that should be stored in the sqlite_stat2 table. If so,
71598         ** store it.  */
71599         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
71600         assert( regTabname+1==regIdxname 
71601              && regTabname+2==regSampleno
71602              && regTabname+3==regCol
71603         );
71604         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71605         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
71606         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
71607         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
71608
71609         /* Calculate new values for regSamplerecno and regSampleno.
71610         **
71611         **   sampleno = sampleno + 1
71612         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
71613         */
71614         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
71615         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
71616         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71617         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
71618         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
71619         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
71620         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
71621
71622         sqlite3VdbeJumpHere(v, ne);
71623         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
71624       }
71625 #endif
71626
71627       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
71628       /**** TODO:  add collating sequence *****/
71629       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71630     }
71631     if( db->mallocFailed ){
71632       /* If a malloc failure has occurred, then the result of the expression 
71633       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
71634       ** below may be negative. Which causes an assert() to fail (or an
71635       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
71636       return;
71637     }
71638     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
71639     for(i=0; i<nCol; i++){
71640       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
71641       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
71642       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
71643     }
71644
71645     /* End of the analysis loop. */
71646     sqlite3VdbeResolveLabel(v, endOfLoop);
71647     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
71648     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
71649
71650     /* Store the results in sqlite_stat1.
71651     **
71652     ** The result is a single row of the sqlite_stat1 table.  The first
71653     ** two columns are the names of the table and index.  The third column
71654     ** is a string composed of a list of integer statistics about the
71655     ** index.  The first integer in the list is the total number of entries
71656     ** in the index.  There is one additional integer in the list for each
71657     ** column of the table.  This additional integer is a guess of how many
71658     ** rows of the table the index will select.  If D is the count of distinct
71659     ** values and K is the total number of rows, then the integer is computed
71660     ** as:
71661     **
71662     **        I = (K+D-1)/D
71663     **
71664     ** If K==0 then no entry is made into the sqlite_stat1 table.  
71665     ** If K>0 then it is always the case the D>0 so division by zero
71666     ** is never possible.
71667     */
71668     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
71669     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
71670     for(i=0; i<nCol; i++){
71671       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
71672       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71673       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
71674       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71675       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
71676       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
71677       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71678     }
71679     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
71680     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
71681     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
71682     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
71683     sqlite3VdbeJumpHere(v, addr);
71684   }
71685 }
71686
71687 /*
71688 ** Generate code that will cause the most recent index analysis to
71689 ** be laoded into internal hash tables where is can be used.
71690 */
71691 static void loadAnalysis(Parse *pParse, int iDb){
71692   Vdbe *v = sqlite3GetVdbe(pParse);
71693   if( v ){
71694     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
71695   }
71696 }
71697
71698 /*
71699 ** Generate code that will do an analysis of an entire database
71700 */
71701 static void analyzeDatabase(Parse *pParse, int iDb){
71702   sqlite3 *db = pParse->db;
71703   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
71704   HashElem *k;
71705   int iStatCur;
71706   int iMem;
71707
71708   sqlite3BeginWriteOperation(pParse, 0, iDb);
71709   iStatCur = pParse->nTab;
71710   pParse->nTab += 2;
71711   openStatTable(pParse, iDb, iStatCur, 0);
71712   iMem = pParse->nMem+1;
71713   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
71714     Table *pTab = (Table*)sqliteHashData(k);
71715     analyzeOneTable(pParse, pTab, iStatCur, iMem);
71716   }
71717   loadAnalysis(pParse, iDb);
71718 }
71719
71720 /*
71721 ** Generate code that will do an analysis of a single table in
71722 ** a database.
71723 */
71724 static void analyzeTable(Parse *pParse, Table *pTab){
71725   int iDb;
71726   int iStatCur;
71727
71728   assert( pTab!=0 );
71729   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71730   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71731   sqlite3BeginWriteOperation(pParse, 0, iDb);
71732   iStatCur = pParse->nTab;
71733   pParse->nTab += 2;
71734   openStatTable(pParse, iDb, iStatCur, pTab->zName);
71735   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
71736   loadAnalysis(pParse, iDb);
71737 }
71738
71739 /*
71740 ** Generate code for the ANALYZE command.  The parser calls this routine
71741 ** when it recognizes an ANALYZE command.
71742 **
71743 **        ANALYZE                            -- 1
71744 **        ANALYZE  <database>                -- 2
71745 **        ANALYZE  ?<database>.?<tablename>  -- 3
71746 **
71747 ** Form 1 causes all indices in all attached databases to be analyzed.
71748 ** Form 2 analyzes all indices the single database named.
71749 ** Form 3 analyzes all indices associated with the named table.
71750 */
71751 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
71752   sqlite3 *db = pParse->db;
71753   int iDb;
71754   int i;
71755   char *z, *zDb;
71756   Table *pTab;
71757   Token *pTableName;
71758
71759   /* Read the database schema. If an error occurs, leave an error message
71760   ** and code in pParse and return NULL. */
71761   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71762   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
71763     return;
71764   }
71765
71766   assert( pName2!=0 || pName1==0 );
71767   if( pName1==0 ){
71768     /* Form 1:  Analyze everything */
71769     for(i=0; i<db->nDb; i++){
71770       if( i==1 ) continue;  /* Do not analyze the TEMP database */
71771       analyzeDatabase(pParse, i);
71772     }
71773   }else if( pName2->n==0 ){
71774     /* Form 2:  Analyze the database or table named */
71775     iDb = sqlite3FindDb(db, pName1);
71776     if( iDb>=0 ){
71777       analyzeDatabase(pParse, iDb);
71778     }else{
71779       z = sqlite3NameFromToken(db, pName1);
71780       if( z ){
71781         pTab = sqlite3LocateTable(pParse, 0, z, 0);
71782         sqlite3DbFree(db, z);
71783         if( pTab ){
71784           analyzeTable(pParse, pTab);
71785         }
71786       }
71787     }
71788   }else{
71789     /* Form 3: Analyze the fully qualified table name */
71790     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
71791     if( iDb>=0 ){
71792       zDb = db->aDb[iDb].zName;
71793       z = sqlite3NameFromToken(db, pTableName);
71794       if( z ){
71795         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
71796         sqlite3DbFree(db, z);
71797         if( pTab ){
71798           analyzeTable(pParse, pTab);
71799         }
71800       }
71801     }   
71802   }
71803 }
71804
71805 /*
71806 ** Used to pass information from the analyzer reader through to the
71807 ** callback routine.
71808 */
71809 typedef struct analysisInfo analysisInfo;
71810 struct analysisInfo {
71811   sqlite3 *db;
71812   const char *zDatabase;
71813 };
71814
71815 /*
71816 ** This callback is invoked once for each index when reading the
71817 ** sqlite_stat1 table.  
71818 **
71819 **     argv[0] = name of the index
71820 **     argv[1] = results of analysis - on integer for each column
71821 */
71822 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
71823   analysisInfo *pInfo = (analysisInfo*)pData;
71824   Index *pIndex;
71825   int i, c;
71826   unsigned int v;
71827   const char *z;
71828
71829   assert( argc==2 );
71830   UNUSED_PARAMETER2(NotUsed, argc);
71831
71832   if( argv==0 || argv[0]==0 || argv[1]==0 ){
71833     return 0;
71834   }
71835   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
71836   if( pIndex==0 ){
71837     return 0;
71838   }
71839   z = argv[1];
71840   for(i=0; *z && i<=pIndex->nColumn; i++){
71841     v = 0;
71842     while( (c=z[0])>='0' && c<='9' ){
71843       v = v*10 + c - '0';
71844       z++;
71845     }
71846     pIndex->aiRowEst[i] = v;
71847     if( *z==' ' ) z++;
71848   }
71849   return 0;
71850 }
71851
71852 /*
71853 ** If the Index.aSample variable is not NULL, delete the aSample[] array
71854 ** and its contents.
71855 */
71856 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
71857 #ifdef SQLITE_ENABLE_STAT2
71858   if( pIdx->aSample ){
71859     int j;
71860     sqlite3 *dbMem = pIdx->pTable->dbMem;
71861     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
71862       IndexSample *p = &pIdx->aSample[j];
71863       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
71864         sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
71865       }
71866     }
71867     sqlite3DbFree(dbMem, pIdx->aSample);
71868     pIdx->aSample = 0;
71869   }
71870 #else
71871   UNUSED_PARAMETER(pIdx);
71872 #endif
71873 }
71874
71875 /*
71876 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
71877 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
71878 ** arrays. The contents of sqlite_stat2 are used to populate the
71879 ** Index.aSample[] arrays.
71880 **
71881 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
71882 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
71883 ** during compilation and the sqlite_stat2 table is present, no data is 
71884 ** read from it.
71885 **
71886 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
71887 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
71888 ** returned. However, in this case, data is read from the sqlite_stat1
71889 ** table (if it is present) before returning.
71890 **
71891 ** If an OOM error occurs, this function always sets db->mallocFailed.
71892 ** This means if the caller does not care about other errors, the return
71893 ** code may be ignored.
71894 */
71895 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
71896   analysisInfo sInfo;
71897   HashElem *i;
71898   char *zSql;
71899   int rc;
71900
71901   assert( iDb>=0 && iDb<db->nDb );
71902   assert( db->aDb[iDb].pBt!=0 );
71903   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
71904
71905   /* Clear any prior statistics */
71906   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
71907     Index *pIdx = sqliteHashData(i);
71908     sqlite3DefaultRowEst(pIdx);
71909     sqlite3DeleteIndexSamples(pIdx);
71910   }
71911
71912   /* Check to make sure the sqlite_stat1 table exists */
71913   sInfo.db = db;
71914   sInfo.zDatabase = db->aDb[iDb].zName;
71915   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
71916     return SQLITE_ERROR;
71917   }
71918
71919   /* Load new statistics out of the sqlite_stat1 table */
71920   zSql = sqlite3MPrintf(db, 
71921       "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
71922   if( zSql==0 ){
71923     rc = SQLITE_NOMEM;
71924   }else{
71925     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
71926     sqlite3DbFree(db, zSql);
71927   }
71928
71929
71930   /* Load the statistics from the sqlite_stat2 table. */
71931 #ifdef SQLITE_ENABLE_STAT2
71932   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
71933     rc = SQLITE_ERROR;
71934   }
71935   if( rc==SQLITE_OK ){
71936     sqlite3_stmt *pStmt = 0;
71937
71938     zSql = sqlite3MPrintf(db, 
71939         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
71940     if( !zSql ){
71941       rc = SQLITE_NOMEM;
71942     }else{
71943       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
71944       sqlite3DbFree(db, zSql);
71945     }
71946
71947     if( rc==SQLITE_OK ){
71948       while( sqlite3_step(pStmt)==SQLITE_ROW ){
71949         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
71950         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
71951         if( pIdx ){
71952           int iSample = sqlite3_column_int(pStmt, 1);
71953           sqlite3 *dbMem = pIdx->pTable->dbMem;
71954           assert( dbMem==db || dbMem==0 );
71955           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
71956             int eType = sqlite3_column_type(pStmt, 2);
71957
71958             if( pIdx->aSample==0 ){
71959               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
71960               pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
71961               if( pIdx->aSample==0 ){
71962                 db->mallocFailed = 1;
71963                 break;
71964               }
71965             }
71966
71967             assert( pIdx->aSample );
71968             {
71969               IndexSample *pSample = &pIdx->aSample[iSample];
71970               pSample->eType = (u8)eType;
71971               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
71972                 pSample->u.r = sqlite3_column_double(pStmt, 2);
71973               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
71974                 const char *z = (const char *)(
71975                     (eType==SQLITE_BLOB) ?
71976                     sqlite3_column_blob(pStmt, 2):
71977                     sqlite3_column_text(pStmt, 2)
71978                 );
71979                 int n = sqlite3_column_bytes(pStmt, 2);
71980                 if( n>24 ){
71981                   n = 24;
71982                 }
71983                 pSample->nByte = (u8)n;
71984                 if( n < 1){
71985                   pSample->u.z = 0;
71986                 }else{
71987                   pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
71988                   if( pSample->u.z ){
71989                     memcpy(pSample->u.z, z, n);
71990                   }else{
71991                     db->mallocFailed = 1;
71992                     break;
71993                   }
71994                 }
71995               }
71996             }
71997           }
71998         }
71999       }
72000       rc = sqlite3_finalize(pStmt);
72001     }
72002   }
72003 #endif
72004
72005   if( rc==SQLITE_NOMEM ){
72006     db->mallocFailed = 1;
72007   }
72008   return rc;
72009 }
72010
72011
72012 #endif /* SQLITE_OMIT_ANALYZE */
72013
72014 /************** End of analyze.c *********************************************/
72015 /************** Begin file attach.c ******************************************/
72016 /*
72017 ** 2003 April 6
72018 **
72019 ** The author disclaims copyright to this source code.  In place of
72020 ** a legal notice, here is a blessing:
72021 **
72022 **    May you do good and not evil.
72023 **    May you find forgiveness for yourself and forgive others.
72024 **    May you share freely, never taking more than you give.
72025 **
72026 *************************************************************************
72027 ** This file contains code used to implement the ATTACH and DETACH commands.
72028 */
72029
72030 #ifndef SQLITE_OMIT_ATTACH
72031 /*
72032 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
72033 ** is slightly different from resolving a normal SQL expression, because simple
72034 ** identifiers are treated as strings, not possible column names or aliases.
72035 **
72036 ** i.e. if the parser sees:
72037 **
72038 **     ATTACH DATABASE abc AS def
72039 **
72040 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
72041 ** looking for columns of the same name.
72042 **
72043 ** This only applies to the root node of pExpr, so the statement:
72044 **
72045 **     ATTACH DATABASE abc||def AS 'db2'
72046 **
72047 ** will fail because neither abc or def can be resolved.
72048 */
72049 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
72050 {
72051   int rc = SQLITE_OK;
72052   if( pExpr ){
72053     if( pExpr->op!=TK_ID ){
72054       rc = sqlite3ResolveExprNames(pName, pExpr);
72055       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
72056         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
72057         return SQLITE_ERROR;
72058       }
72059     }else{
72060       pExpr->op = TK_STRING;
72061     }
72062   }
72063   return rc;
72064 }
72065
72066 /*
72067 ** An SQL user-function registered to do the work of an ATTACH statement. The
72068 ** three arguments to the function come directly from an attach statement:
72069 **
72070 **     ATTACH DATABASE x AS y KEY z
72071 **
72072 **     SELECT sqlite_attach(x, y, z)
72073 **
72074 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
72075 ** third argument.
72076 */
72077 static void attachFunc(
72078   sqlite3_context *context,
72079   int NotUsed,
72080   sqlite3_value **argv
72081 ){
72082   int i;
72083   int rc = 0;
72084   sqlite3 *db = sqlite3_context_db_handle(context);
72085   const char *zName;
72086   const char *zFile;
72087   Db *aNew;
72088   char *zErrDyn = 0;
72089
72090   UNUSED_PARAMETER(NotUsed);
72091
72092   zFile = (const char *)sqlite3_value_text(argv[0]);
72093   zName = (const char *)sqlite3_value_text(argv[1]);
72094   if( zFile==0 ) zFile = "";
72095   if( zName==0 ) zName = "";
72096
72097   /* Check for the following errors:
72098   **
72099   **     * Too many attached databases,
72100   **     * Transaction currently open
72101   **     * Specified database name already being used.
72102   */
72103   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
72104     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
72105       db->aLimit[SQLITE_LIMIT_ATTACHED]
72106     );
72107     goto attach_error;
72108   }
72109   if( !db->autoCommit ){
72110     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
72111     goto attach_error;
72112   }
72113   for(i=0; i<db->nDb; i++){
72114     char *z = db->aDb[i].zName;
72115     assert( z && zName );
72116     if( sqlite3StrICmp(z, zName)==0 ){
72117       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
72118       goto attach_error;
72119     }
72120   }
72121
72122   /* Allocate the new entry in the db->aDb[] array and initialise the schema
72123   ** hash tables.
72124   */
72125   if( db->aDb==db->aDbStatic ){
72126     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
72127     if( aNew==0 ) return;
72128     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
72129   }else{
72130     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
72131     if( aNew==0 ) return;
72132   }
72133   db->aDb = aNew;
72134   aNew = &db->aDb[db->nDb];
72135   memset(aNew, 0, sizeof(*aNew));
72136
72137   /* Open the database file. If the btree is successfully opened, use
72138   ** it to obtain the database schema. At this point the schema may
72139   ** or may not be initialised.
72140   */
72141   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
72142                            db->openFlags | SQLITE_OPEN_MAIN_DB,
72143                            &aNew->pBt);
72144   db->nDb++;
72145   if( rc==SQLITE_CONSTRAINT ){
72146     rc = SQLITE_ERROR;
72147     zErrDyn = sqlite3MPrintf(db, "database is already attached");
72148   }else if( rc==SQLITE_OK ){
72149     Pager *pPager;
72150     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
72151     if( !aNew->pSchema ){
72152       rc = SQLITE_NOMEM;
72153     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
72154       zErrDyn = sqlite3MPrintf(db, 
72155         "attached databases must use the same text encoding as main database");
72156       rc = SQLITE_ERROR;
72157     }
72158     pPager = sqlite3BtreePager(aNew->pBt);
72159     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
72160     sqlite3BtreeSecureDelete(aNew->pBt,
72161                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
72162   }
72163   aNew->safety_level = 3;
72164   aNew->zName = sqlite3DbStrDup(db, zName);
72165   if( rc==SQLITE_OK && aNew->zName==0 ){
72166     rc = SQLITE_NOMEM;
72167   }
72168
72169
72170 #ifdef SQLITE_HAS_CODEC
72171   if( rc==SQLITE_OK ){
72172     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
72173     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
72174     int nKey;
72175     char *zKey;
72176     int t = sqlite3_value_type(argv[2]);
72177     switch( t ){
72178       case SQLITE_INTEGER:
72179       case SQLITE_FLOAT:
72180         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
72181         rc = SQLITE_ERROR;
72182         break;
72183         
72184       case SQLITE_TEXT:
72185       case SQLITE_BLOB:
72186         nKey = sqlite3_value_bytes(argv[2]);
72187         zKey = (char *)sqlite3_value_blob(argv[2]);
72188         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
72189         break;
72190
72191       case SQLITE_NULL:
72192         /* No key specified.  Use the key from the main database */
72193         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
72194         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
72195         break;
72196     }
72197   }
72198 #endif
72199
72200   /* If the file was opened successfully, read the schema for the new database.
72201   ** If this fails, or if opening the file failed, then close the file and 
72202   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
72203   ** we found it.
72204   */
72205   if( rc==SQLITE_OK ){
72206     sqlite3BtreeEnterAll(db);
72207     rc = sqlite3Init(db, &zErrDyn);
72208     sqlite3BtreeLeaveAll(db);
72209   }
72210   if( rc ){
72211     int iDb = db->nDb - 1;
72212     assert( iDb>=2 );
72213     if( db->aDb[iDb].pBt ){
72214       sqlite3BtreeClose(db->aDb[iDb].pBt);
72215       db->aDb[iDb].pBt = 0;
72216       db->aDb[iDb].pSchema = 0;
72217     }
72218     sqlite3ResetInternalSchema(db, 0);
72219     db->nDb = iDb;
72220     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
72221       db->mallocFailed = 1;
72222       sqlite3DbFree(db, zErrDyn);
72223       zErrDyn = sqlite3MPrintf(db, "out of memory");
72224     }else if( zErrDyn==0 ){
72225       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
72226     }
72227     goto attach_error;
72228   }
72229   
72230   return;
72231
72232 attach_error:
72233   /* Return an error if we get here */
72234   if( zErrDyn ){
72235     sqlite3_result_error(context, zErrDyn, -1);
72236     sqlite3DbFree(db, zErrDyn);
72237   }
72238   if( rc ) sqlite3_result_error_code(context, rc);
72239 }
72240
72241 /*
72242 ** An SQL user-function registered to do the work of an DETACH statement. The
72243 ** three arguments to the function come directly from a detach statement:
72244 **
72245 **     DETACH DATABASE x
72246 **
72247 **     SELECT sqlite_detach(x)
72248 */
72249 static void detachFunc(
72250   sqlite3_context *context,
72251   int NotUsed,
72252   sqlite3_value **argv
72253 ){
72254   const char *zName = (const char *)sqlite3_value_text(argv[0]);
72255   sqlite3 *db = sqlite3_context_db_handle(context);
72256   int i;
72257   Db *pDb = 0;
72258   char zErr[128];
72259
72260   UNUSED_PARAMETER(NotUsed);
72261
72262   if( zName==0 ) zName = "";
72263   for(i=0; i<db->nDb; i++){
72264     pDb = &db->aDb[i];
72265     if( pDb->pBt==0 ) continue;
72266     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
72267   }
72268
72269   if( i>=db->nDb ){
72270     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
72271     goto detach_error;
72272   }
72273   if( i<2 ){
72274     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
72275     goto detach_error;
72276   }
72277   if( !db->autoCommit ){
72278     sqlite3_snprintf(sizeof(zErr), zErr,
72279                      "cannot DETACH database within transaction");
72280     goto detach_error;
72281   }
72282   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
72283     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
72284     goto detach_error;
72285   }
72286
72287   sqlite3BtreeClose(pDb->pBt);
72288   pDb->pBt = 0;
72289   pDb->pSchema = 0;
72290   sqlite3ResetInternalSchema(db, 0);
72291   return;
72292
72293 detach_error:
72294   sqlite3_result_error(context, zErr, -1);
72295 }
72296
72297 /*
72298 ** This procedure generates VDBE code for a single invocation of either the
72299 ** sqlite_detach() or sqlite_attach() SQL user functions.
72300 */
72301 static void codeAttach(
72302   Parse *pParse,       /* The parser context */
72303   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
72304   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
72305   Expr *pAuthArg,      /* Expression to pass to authorization callback */
72306   Expr *pFilename,     /* Name of database file */
72307   Expr *pDbname,       /* Name of the database to use internally */
72308   Expr *pKey           /* Database key for encryption extension */
72309 ){
72310   int rc;
72311   NameContext sName;
72312   Vdbe *v;
72313   sqlite3* db = pParse->db;
72314   int regArgs;
72315
72316   memset(&sName, 0, sizeof(NameContext));
72317   sName.pParse = pParse;
72318
72319   if( 
72320       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
72321       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
72322       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
72323   ){
72324     pParse->nErr++;
72325     goto attach_end;
72326   }
72327
72328 #ifndef SQLITE_OMIT_AUTHORIZATION
72329   if( pAuthArg ){
72330     char *zAuthArg = pAuthArg->u.zToken;
72331     if( NEVER(zAuthArg==0) ){
72332       goto attach_end;
72333     }
72334     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
72335     if(rc!=SQLITE_OK ){
72336       goto attach_end;
72337     }
72338   }
72339 #endif /* SQLITE_OMIT_AUTHORIZATION */
72340
72341
72342   v = sqlite3GetVdbe(pParse);
72343   regArgs = sqlite3GetTempRange(pParse, 4);
72344   sqlite3ExprCode(pParse, pFilename, regArgs);
72345   sqlite3ExprCode(pParse, pDbname, regArgs+1);
72346   sqlite3ExprCode(pParse, pKey, regArgs+2);
72347
72348   assert( v || db->mallocFailed );
72349   if( v ){
72350     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
72351     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
72352     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
72353     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
72354
72355     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
72356     ** statement only). For DETACH, set it to false (expire all existing
72357     ** statements).
72358     */
72359     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
72360   }
72361   
72362 attach_end:
72363   sqlite3ExprDelete(db, pFilename);
72364   sqlite3ExprDelete(db, pDbname);
72365   sqlite3ExprDelete(db, pKey);
72366 }
72367
72368 /*
72369 ** Called by the parser to compile a DETACH statement.
72370 **
72371 **     DETACH pDbname
72372 */
72373 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
72374   static const FuncDef detach_func = {
72375     1,                /* nArg */
72376     SQLITE_UTF8,      /* iPrefEnc */
72377     0,                /* flags */
72378     0,                /* pUserData */
72379     0,                /* pNext */
72380     detachFunc,       /* xFunc */
72381     0,                /* xStep */
72382     0,                /* xFinalize */
72383     "sqlite_detach",  /* zName */
72384     0                 /* pHash */
72385   };
72386   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
72387 }
72388
72389 /*
72390 ** Called by the parser to compile an ATTACH statement.
72391 **
72392 **     ATTACH p AS pDbname KEY pKey
72393 */
72394 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
72395   static const FuncDef attach_func = {
72396     3,                /* nArg */
72397     SQLITE_UTF8,      /* iPrefEnc */
72398     0,                /* flags */
72399     0,                /* pUserData */
72400     0,                /* pNext */
72401     attachFunc,       /* xFunc */
72402     0,                /* xStep */
72403     0,                /* xFinalize */
72404     "sqlite_attach",  /* zName */
72405     0                 /* pHash */
72406   };
72407   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
72408 }
72409 #endif /* SQLITE_OMIT_ATTACH */
72410
72411 /*
72412 ** Initialize a DbFixer structure.  This routine must be called prior
72413 ** to passing the structure to one of the sqliteFixAAAA() routines below.
72414 **
72415 ** The return value indicates whether or not fixation is required.  TRUE
72416 ** means we do need to fix the database references, FALSE means we do not.
72417 */
72418 SQLITE_PRIVATE int sqlite3FixInit(
72419   DbFixer *pFix,      /* The fixer to be initialized */
72420   Parse *pParse,      /* Error messages will be written here */
72421   int iDb,            /* This is the database that must be used */
72422   const char *zType,  /* "view", "trigger", or "index" */
72423   const Token *pName  /* Name of the view, trigger, or index */
72424 ){
72425   sqlite3 *db;
72426
72427   if( NEVER(iDb<0) || iDb==1 ) return 0;
72428   db = pParse->db;
72429   assert( db->nDb>iDb );
72430   pFix->pParse = pParse;
72431   pFix->zDb = db->aDb[iDb].zName;
72432   pFix->zType = zType;
72433   pFix->pName = pName;
72434   return 1;
72435 }
72436
72437 /*
72438 ** The following set of routines walk through the parse tree and assign
72439 ** a specific database to all table references where the database name
72440 ** was left unspecified in the original SQL statement.  The pFix structure
72441 ** must have been initialized by a prior call to sqlite3FixInit().
72442 **
72443 ** These routines are used to make sure that an index, trigger, or
72444 ** view in one database does not refer to objects in a different database.
72445 ** (Exception: indices, triggers, and views in the TEMP database are
72446 ** allowed to refer to anything.)  If a reference is explicitly made
72447 ** to an object in a different database, an error message is added to
72448 ** pParse->zErrMsg and these routines return non-zero.  If everything
72449 ** checks out, these routines return 0.
72450 */
72451 SQLITE_PRIVATE int sqlite3FixSrcList(
72452   DbFixer *pFix,       /* Context of the fixation */
72453   SrcList *pList       /* The Source list to check and modify */
72454 ){
72455   int i;
72456   const char *zDb;
72457   struct SrcList_item *pItem;
72458
72459   if( NEVER(pList==0) ) return 0;
72460   zDb = pFix->zDb;
72461   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
72462     if( pItem->zDatabase==0 ){
72463       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
72464     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
72465       sqlite3ErrorMsg(pFix->pParse,
72466          "%s %T cannot reference objects in database %s",
72467          pFix->zType, pFix->pName, pItem->zDatabase);
72468       return 1;
72469     }
72470 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72471     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
72472     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
72473 #endif
72474   }
72475   return 0;
72476 }
72477 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72478 SQLITE_PRIVATE int sqlite3FixSelect(
72479   DbFixer *pFix,       /* Context of the fixation */
72480   Select *pSelect      /* The SELECT statement to be fixed to one database */
72481 ){
72482   while( pSelect ){
72483     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
72484       return 1;
72485     }
72486     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
72487       return 1;
72488     }
72489     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
72490       return 1;
72491     }
72492     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
72493       return 1;
72494     }
72495     pSelect = pSelect->pPrior;
72496   }
72497   return 0;
72498 }
72499 SQLITE_PRIVATE int sqlite3FixExpr(
72500   DbFixer *pFix,     /* Context of the fixation */
72501   Expr *pExpr        /* The expression to be fixed to one database */
72502 ){
72503   while( pExpr ){
72504     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
72505     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72506       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
72507     }else{
72508       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
72509     }
72510     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
72511       return 1;
72512     }
72513     pExpr = pExpr->pLeft;
72514   }
72515   return 0;
72516 }
72517 SQLITE_PRIVATE int sqlite3FixExprList(
72518   DbFixer *pFix,     /* Context of the fixation */
72519   ExprList *pList    /* The expression to be fixed to one database */
72520 ){
72521   int i;
72522   struct ExprList_item *pItem;
72523   if( pList==0 ) return 0;
72524   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
72525     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
72526       return 1;
72527     }
72528   }
72529   return 0;
72530 }
72531 #endif
72532
72533 #ifndef SQLITE_OMIT_TRIGGER
72534 SQLITE_PRIVATE int sqlite3FixTriggerStep(
72535   DbFixer *pFix,     /* Context of the fixation */
72536   TriggerStep *pStep /* The trigger step be fixed to one database */
72537 ){
72538   while( pStep ){
72539     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
72540       return 1;
72541     }
72542     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
72543       return 1;
72544     }
72545     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
72546       return 1;
72547     }
72548     pStep = pStep->pNext;
72549   }
72550   return 0;
72551 }
72552 #endif
72553
72554 /************** End of attach.c **********************************************/
72555 /************** Begin file auth.c ********************************************/
72556 /*
72557 ** 2003 January 11
72558 **
72559 ** The author disclaims copyright to this source code.  In place of
72560 ** a legal notice, here is a blessing:
72561 **
72562 **    May you do good and not evil.
72563 **    May you find forgiveness for yourself and forgive others.
72564 **    May you share freely, never taking more than you give.
72565 **
72566 *************************************************************************
72567 ** This file contains code used to implement the sqlite3_set_authorizer()
72568 ** API.  This facility is an optional feature of the library.  Embedded
72569 ** systems that do not need this facility may omit it by recompiling
72570 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
72571 */
72572
72573 /*
72574 ** All of the code in this file may be omitted by defining a single
72575 ** macro.
72576 */
72577 #ifndef SQLITE_OMIT_AUTHORIZATION
72578
72579 /*
72580 ** Set or clear the access authorization function.
72581 **
72582 ** The access authorization function is be called during the compilation
72583 ** phase to verify that the user has read and/or write access permission on
72584 ** various fields of the database.  The first argument to the auth function
72585 ** is a copy of the 3rd argument to this routine.  The second argument
72586 ** to the auth function is one of these constants:
72587 **
72588 **       SQLITE_CREATE_INDEX
72589 **       SQLITE_CREATE_TABLE
72590 **       SQLITE_CREATE_TEMP_INDEX
72591 **       SQLITE_CREATE_TEMP_TABLE
72592 **       SQLITE_CREATE_TEMP_TRIGGER
72593 **       SQLITE_CREATE_TEMP_VIEW
72594 **       SQLITE_CREATE_TRIGGER
72595 **       SQLITE_CREATE_VIEW
72596 **       SQLITE_DELETE
72597 **       SQLITE_DROP_INDEX
72598 **       SQLITE_DROP_TABLE
72599 **       SQLITE_DROP_TEMP_INDEX
72600 **       SQLITE_DROP_TEMP_TABLE
72601 **       SQLITE_DROP_TEMP_TRIGGER
72602 **       SQLITE_DROP_TEMP_VIEW
72603 **       SQLITE_DROP_TRIGGER
72604 **       SQLITE_DROP_VIEW
72605 **       SQLITE_INSERT
72606 **       SQLITE_PRAGMA
72607 **       SQLITE_READ
72608 **       SQLITE_SELECT
72609 **       SQLITE_TRANSACTION
72610 **       SQLITE_UPDATE
72611 **
72612 ** The third and fourth arguments to the auth function are the name of
72613 ** the table and the column that are being accessed.  The auth function
72614 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
72615 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
72616 ** means that the SQL statement will never-run - the sqlite3_exec() call
72617 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
72618 ** should run but attempts to read the specified column will return NULL
72619 ** and attempts to write the column will be ignored.
72620 **
72621 ** Setting the auth function to NULL disables this hook.  The default
72622 ** setting of the auth function is NULL.
72623 */
72624 SQLITE_API int sqlite3_set_authorizer(
72625   sqlite3 *db,
72626   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
72627   void *pArg
72628 ){
72629   sqlite3_mutex_enter(db->mutex);
72630   db->xAuth = xAuth;
72631   db->pAuthArg = pArg;
72632   sqlite3ExpirePreparedStatements(db);
72633   sqlite3_mutex_leave(db->mutex);
72634   return SQLITE_OK;
72635 }
72636
72637 /*
72638 ** Write an error message into pParse->zErrMsg that explains that the
72639 ** user-supplied authorization function returned an illegal value.
72640 */
72641 static void sqliteAuthBadReturnCode(Parse *pParse){
72642   sqlite3ErrorMsg(pParse, "authorizer malfunction");
72643   pParse->rc = SQLITE_ERROR;
72644 }
72645
72646 /*
72647 ** Invoke the authorization callback for permission to read column zCol from
72648 ** table zTab in database zDb. This function assumes that an authorization
72649 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
72650 **
72651 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
72652 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
72653 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
72654 */
72655 SQLITE_PRIVATE int sqlite3AuthReadCol(
72656   Parse *pParse,                  /* The parser context */
72657   const char *zTab,               /* Table name */
72658   const char *zCol,               /* Column name */
72659   int iDb                         /* Index of containing database. */
72660 ){
72661   sqlite3 *db = pParse->db;       /* Database handle */
72662   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
72663   int rc;                         /* Auth callback return code */
72664
72665   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
72666   if( rc==SQLITE_DENY ){
72667     if( db->nDb>2 || iDb!=0 ){
72668       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
72669     }else{
72670       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
72671     }
72672     pParse->rc = SQLITE_AUTH;
72673   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
72674     sqliteAuthBadReturnCode(pParse);
72675   }
72676   return rc;
72677 }
72678
72679 /*
72680 ** The pExpr should be a TK_COLUMN expression.  The table referred to
72681 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
72682 ** Check to see if it is OK to read this particular column.
72683 **
72684 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
72685 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
72686 ** then generate an error.
72687 */
72688 SQLITE_PRIVATE void sqlite3AuthRead(
72689   Parse *pParse,        /* The parser context */
72690   Expr *pExpr,          /* The expression to check authorization on */
72691   Schema *pSchema,      /* The schema of the expression */
72692   SrcList *pTabList     /* All table that pExpr might refer to */
72693 ){
72694   sqlite3 *db = pParse->db;
72695   Table *pTab = 0;      /* The table being read */
72696   const char *zCol;     /* Name of the column of the table */
72697   int iSrc;             /* Index in pTabList->a[] of table being read */
72698   int iDb;              /* The index of the database the expression refers to */
72699   int iCol;             /* Index of column in table */
72700
72701   if( db->xAuth==0 ) return;
72702   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
72703   if( iDb<0 ){
72704     /* An attempt to read a column out of a subquery or other
72705     ** temporary table. */
72706     return;
72707   }
72708
72709   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
72710   if( pExpr->op==TK_TRIGGER ){
72711     pTab = pParse->pTriggerTab;
72712   }else{
72713     assert( pTabList );
72714     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
72715       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
72716         pTab = pTabList->a[iSrc].pTab;
72717         break;
72718       }
72719     }
72720   }
72721   iCol = pExpr->iColumn;
72722   if( NEVER(pTab==0) ) return;
72723
72724   if( iCol>=0 ){
72725     assert( iCol<pTab->nCol );
72726     zCol = pTab->aCol[iCol].zName;
72727   }else if( pTab->iPKey>=0 ){
72728     assert( pTab->iPKey<pTab->nCol );
72729     zCol = pTab->aCol[pTab->iPKey].zName;
72730   }else{
72731     zCol = "ROWID";
72732   }
72733   assert( iDb>=0 && iDb<db->nDb );
72734   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
72735     pExpr->op = TK_NULL;
72736   }
72737 }
72738
72739 /*
72740 ** Do an authorization check using the code and arguments given.  Return
72741 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
72742 ** is returned, then the error count and error message in pParse are
72743 ** modified appropriately.
72744 */
72745 SQLITE_PRIVATE int sqlite3AuthCheck(
72746   Parse *pParse,
72747   int code,
72748   const char *zArg1,
72749   const char *zArg2,
72750   const char *zArg3
72751 ){
72752   sqlite3 *db = pParse->db;
72753   int rc;
72754
72755   /* Don't do any authorization checks if the database is initialising
72756   ** or if the parser is being invoked from within sqlite3_declare_vtab.
72757   */
72758   if( db->init.busy || IN_DECLARE_VTAB ){
72759     return SQLITE_OK;
72760   }
72761
72762   if( db->xAuth==0 ){
72763     return SQLITE_OK;
72764   }
72765   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
72766   if( rc==SQLITE_DENY ){
72767     sqlite3ErrorMsg(pParse, "not authorized");
72768     pParse->rc = SQLITE_AUTH;
72769   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
72770     rc = SQLITE_DENY;
72771     sqliteAuthBadReturnCode(pParse);
72772   }
72773   return rc;
72774 }
72775
72776 /*
72777 ** Push an authorization context.  After this routine is called, the
72778 ** zArg3 argument to authorization callbacks will be zContext until
72779 ** popped.  Or if pParse==0, this routine is a no-op.
72780 */
72781 SQLITE_PRIVATE void sqlite3AuthContextPush(
72782   Parse *pParse,
72783   AuthContext *pContext, 
72784   const char *zContext
72785 ){
72786   assert( pParse );
72787   pContext->pParse = pParse;
72788   pContext->zAuthContext = pParse->zAuthContext;
72789   pParse->zAuthContext = zContext;
72790 }
72791
72792 /*
72793 ** Pop an authorization context that was previously pushed
72794 ** by sqlite3AuthContextPush
72795 */
72796 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
72797   if( pContext->pParse ){
72798     pContext->pParse->zAuthContext = pContext->zAuthContext;
72799     pContext->pParse = 0;
72800   }
72801 }
72802
72803 #endif /* SQLITE_OMIT_AUTHORIZATION */
72804
72805 /************** End of auth.c ************************************************/
72806 /************** Begin file build.c *******************************************/
72807 /*
72808 ** 2001 September 15
72809 **
72810 ** The author disclaims copyright to this source code.  In place of
72811 ** a legal notice, here is a blessing:
72812 **
72813 **    May you do good and not evil.
72814 **    May you find forgiveness for yourself and forgive others.
72815 **    May you share freely, never taking more than you give.
72816 **
72817 *************************************************************************
72818 ** This file contains C code routines that are called by the SQLite parser
72819 ** when syntax rules are reduced.  The routines in this file handle the
72820 ** following kinds of SQL syntax:
72821 **
72822 **     CREATE TABLE
72823 **     DROP TABLE
72824 **     CREATE INDEX
72825 **     DROP INDEX
72826 **     creating ID lists
72827 **     BEGIN TRANSACTION
72828 **     COMMIT
72829 **     ROLLBACK
72830 */
72831
72832 /*
72833 ** This routine is called when a new SQL statement is beginning to
72834 ** be parsed.  Initialize the pParse structure as needed.
72835 */
72836 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
72837   pParse->explain = (u8)explainFlag;
72838   pParse->nVar = 0;
72839 }
72840
72841 #ifndef SQLITE_OMIT_SHARED_CACHE
72842 /*
72843 ** The TableLock structure is only used by the sqlite3TableLock() and
72844 ** codeTableLocks() functions.
72845 */
72846 struct TableLock {
72847   int iDb;             /* The database containing the table to be locked */
72848   int iTab;            /* The root page of the table to be locked */
72849   u8 isWriteLock;      /* True for write lock.  False for a read lock */
72850   const char *zName;   /* Name of the table */
72851 };
72852
72853 /*
72854 ** Record the fact that we want to lock a table at run-time.  
72855 **
72856 ** The table to be locked has root page iTab and is found in database iDb.
72857 ** A read or a write lock can be taken depending on isWritelock.
72858 **
72859 ** This routine just records the fact that the lock is desired.  The
72860 ** code to make the lock occur is generated by a later call to
72861 ** codeTableLocks() which occurs during sqlite3FinishCoding().
72862 */
72863 SQLITE_PRIVATE void sqlite3TableLock(
72864   Parse *pParse,     /* Parsing context */
72865   int iDb,           /* Index of the database containing the table to lock */
72866   int iTab,          /* Root page number of the table to be locked */
72867   u8 isWriteLock,    /* True for a write lock */
72868   const char *zName  /* Name of the table to be locked */
72869 ){
72870   Parse *pToplevel = sqlite3ParseToplevel(pParse);
72871   int i;
72872   int nBytes;
72873   TableLock *p;
72874   assert( iDb>=0 );
72875
72876   for(i=0; i<pToplevel->nTableLock; i++){
72877     p = &pToplevel->aTableLock[i];
72878     if( p->iDb==iDb && p->iTab==iTab ){
72879       p->isWriteLock = (p->isWriteLock || isWriteLock);
72880       return;
72881     }
72882   }
72883
72884   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
72885   pToplevel->aTableLock =
72886       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
72887   if( pToplevel->aTableLock ){
72888     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
72889     p->iDb = iDb;
72890     p->iTab = iTab;
72891     p->isWriteLock = isWriteLock;
72892     p->zName = zName;
72893   }else{
72894     pToplevel->nTableLock = 0;
72895     pToplevel->db->mallocFailed = 1;
72896   }
72897 }
72898
72899 /*
72900 ** Code an OP_TableLock instruction for each table locked by the
72901 ** statement (configured by calls to sqlite3TableLock()).
72902 */
72903 static void codeTableLocks(Parse *pParse){
72904   int i;
72905   Vdbe *pVdbe; 
72906
72907   pVdbe = sqlite3GetVdbe(pParse);
72908   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
72909
72910   for(i=0; i<pParse->nTableLock; i++){
72911     TableLock *p = &pParse->aTableLock[i];
72912     int p1 = p->iDb;
72913     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
72914                       p->zName, P4_STATIC);
72915   }
72916 }
72917 #else
72918   #define codeTableLocks(x)
72919 #endif
72920
72921 /*
72922 ** This routine is called after a single SQL statement has been
72923 ** parsed and a VDBE program to execute that statement has been
72924 ** prepared.  This routine puts the finishing touches on the
72925 ** VDBE program and resets the pParse structure for the next
72926 ** parse.
72927 **
72928 ** Note that if an error occurred, it might be the case that
72929 ** no VDBE code was generated.
72930 */
72931 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
72932   sqlite3 *db;
72933   Vdbe *v;
72934
72935   db = pParse->db;
72936   if( db->mallocFailed ) return;
72937   if( pParse->nested ) return;
72938   if( pParse->nErr ) return;
72939
72940   /* Begin by generating some termination code at the end of the
72941   ** vdbe program
72942   */
72943   v = sqlite3GetVdbe(pParse);
72944   assert( !pParse->isMultiWrite 
72945        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
72946   if( v ){
72947     sqlite3VdbeAddOp0(v, OP_Halt);
72948
72949     /* The cookie mask contains one bit for each database file open.
72950     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
72951     ** set for each database that is used.  Generate code to start a
72952     ** transaction on each used database and to verify the schema cookie
72953     ** on each used database.
72954     */
72955     if( pParse->cookieGoto>0 ){
72956       u32 mask;
72957       int iDb;
72958       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
72959       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
72960         if( (mask & pParse->cookieMask)==0 ) continue;
72961         sqlite3VdbeUsesBtree(v, iDb);
72962         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
72963         if( db->init.busy==0 ){
72964           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
72965         }
72966       }
72967 #ifndef SQLITE_OMIT_VIRTUALTABLE
72968       {
72969         int i;
72970         for(i=0; i<pParse->nVtabLock; i++){
72971           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
72972           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
72973         }
72974         pParse->nVtabLock = 0;
72975       }
72976 #endif
72977
72978       /* Once all the cookies have been verified and transactions opened, 
72979       ** obtain the required table-locks. This is a no-op unless the 
72980       ** shared-cache feature is enabled.
72981       */
72982       codeTableLocks(pParse);
72983
72984       /* Initialize any AUTOINCREMENT data structures required.
72985       */
72986       sqlite3AutoincrementBegin(pParse);
72987
72988       /* Finally, jump back to the beginning of the executable code. */
72989       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
72990     }
72991   }
72992
72993
72994   /* Get the VDBE program ready for execution
72995   */
72996   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
72997 #ifdef SQLITE_DEBUG
72998     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
72999     sqlite3VdbeTrace(v, trace);
73000 #endif
73001     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
73002     /* A minimum of one cursor is required if autoincrement is used
73003     *  See ticket [a696379c1f08866] */
73004     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
73005     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
73006                          pParse->nTab, pParse->nMaxArg, pParse->explain,
73007                          pParse->isMultiWrite && pParse->mayAbort);
73008     pParse->rc = SQLITE_DONE;
73009     pParse->colNamesSet = 0;
73010   }else{
73011     pParse->rc = SQLITE_ERROR;
73012   }
73013   pParse->nTab = 0;
73014   pParse->nMem = 0;
73015   pParse->nSet = 0;
73016   pParse->nVar = 0;
73017   pParse->cookieMask = 0;
73018   pParse->cookieGoto = 0;
73019 }
73020
73021 /*
73022 ** Run the parser and code generator recursively in order to generate
73023 ** code for the SQL statement given onto the end of the pParse context
73024 ** currently under construction.  When the parser is run recursively
73025 ** this way, the final OP_Halt is not appended and other initialization
73026 ** and finalization steps are omitted because those are handling by the
73027 ** outermost parser.
73028 **
73029 ** Not everything is nestable.  This facility is designed to permit
73030 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
73031 ** care if you decide to try to use this routine for some other purposes.
73032 */
73033 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
73034   va_list ap;
73035   char *zSql;
73036   char *zErrMsg = 0;
73037   sqlite3 *db = pParse->db;
73038 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
73039   char saveBuf[SAVE_SZ];
73040
73041   if( pParse->nErr ) return;
73042   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
73043   va_start(ap, zFormat);
73044   zSql = sqlite3VMPrintf(db, zFormat, ap);
73045   va_end(ap);
73046   if( zSql==0 ){
73047     return;   /* A malloc must have failed */
73048   }
73049   pParse->nested++;
73050   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
73051   memset(&pParse->nVar, 0, SAVE_SZ);
73052   sqlite3RunParser(pParse, zSql, &zErrMsg);
73053   sqlite3DbFree(db, zErrMsg);
73054   sqlite3DbFree(db, zSql);
73055   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
73056   pParse->nested--;
73057 }
73058
73059 /*
73060 ** Locate the in-memory structure that describes a particular database
73061 ** table given the name of that table and (optionally) the name of the
73062 ** database containing the table.  Return NULL if not found.
73063 **
73064 ** If zDatabase is 0, all databases are searched for the table and the
73065 ** first matching table is returned.  (No checking for duplicate table
73066 ** names is done.)  The search order is TEMP first, then MAIN, then any
73067 ** auxiliary databases added using the ATTACH command.
73068 **
73069 ** See also sqlite3LocateTable().
73070 */
73071 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
73072   Table *p = 0;
73073   int i;
73074   int nName;
73075   assert( zName!=0 );
73076   nName = sqlite3Strlen30(zName);
73077   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73078     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
73079     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
73080     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
73081     if( p ) break;
73082   }
73083   return p;
73084 }
73085
73086 /*
73087 ** Locate the in-memory structure that describes a particular database
73088 ** table given the name of that table and (optionally) the name of the
73089 ** database containing the table.  Return NULL if not found.  Also leave an
73090 ** error message in pParse->zErrMsg.
73091 **
73092 ** The difference between this routine and sqlite3FindTable() is that this
73093 ** routine leaves an error message in pParse->zErrMsg where
73094 ** sqlite3FindTable() does not.
73095 */
73096 SQLITE_PRIVATE Table *sqlite3LocateTable(
73097   Parse *pParse,         /* context in which to report errors */
73098   int isView,            /* True if looking for a VIEW rather than a TABLE */
73099   const char *zName,     /* Name of the table we are looking for */
73100   const char *zDbase     /* Name of the database.  Might be NULL */
73101 ){
73102   Table *p;
73103
73104   /* Read the database schema. If an error occurs, leave an error message
73105   ** and code in pParse and return NULL. */
73106   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73107     return 0;
73108   }
73109
73110   p = sqlite3FindTable(pParse->db, zName, zDbase);
73111   if( p==0 ){
73112     const char *zMsg = isView ? "no such view" : "no such table";
73113     if( zDbase ){
73114       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
73115     }else{
73116       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
73117     }
73118     pParse->checkSchema = 1;
73119   }
73120   return p;
73121 }
73122
73123 /*
73124 ** Locate the in-memory structure that describes 
73125 ** a particular index given the name of that index
73126 ** and the name of the database that contains the index.
73127 ** Return NULL if not found.
73128 **
73129 ** If zDatabase is 0, all databases are searched for the
73130 ** table and the first matching index is returned.  (No checking
73131 ** for duplicate index names is done.)  The search order is
73132 ** TEMP first, then MAIN, then any auxiliary databases added
73133 ** using the ATTACH command.
73134 */
73135 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
73136   Index *p = 0;
73137   int i;
73138   int nName = sqlite3Strlen30(zName);
73139   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73140     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
73141     Schema *pSchema = db->aDb[j].pSchema;
73142     assert( pSchema );
73143     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
73144     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
73145     if( p ) break;
73146   }
73147   return p;
73148 }
73149
73150 /*
73151 ** Reclaim the memory used by an index
73152 */
73153 static void freeIndex(Index *p){
73154   sqlite3 *db = p->pTable->dbMem;
73155 #ifndef SQLITE_OMIT_ANALYZE
73156   sqlite3DeleteIndexSamples(p);
73157 #endif
73158   sqlite3DbFree(db, p->zColAff);
73159   sqlite3DbFree(db, p);
73160 }
73161
73162 /*
73163 ** Remove the given index from the index hash table, and free
73164 ** its memory structures.
73165 **
73166 ** The index is removed from the database hash tables but
73167 ** it is not unlinked from the Table that it indexes.
73168 ** Unlinking from the Table must be done by the calling function.
73169 */
73170 static void sqlite3DeleteIndex(Index *p){
73171   Index *pOld;
73172   const char *zName = p->zName;
73173
73174   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
73175                            sqlite3Strlen30(zName), 0);
73176   assert( pOld==0 || pOld==p );
73177   freeIndex(p);
73178 }
73179
73180 /*
73181 ** For the index called zIdxName which is found in the database iDb,
73182 ** unlike that index from its Table then remove the index from
73183 ** the index hash table and free all memory structures associated
73184 ** with the index.
73185 */
73186 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
73187   Index *pIndex;
73188   int len;
73189   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
73190
73191   len = sqlite3Strlen30(zIdxName);
73192   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
73193   if( pIndex ){
73194     if( pIndex->pTable->pIndex==pIndex ){
73195       pIndex->pTable->pIndex = pIndex->pNext;
73196     }else{
73197       Index *p;
73198       /* Justification of ALWAYS();  The index must be on the list of
73199       ** indices. */
73200       p = pIndex->pTable->pIndex;
73201       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
73202       if( ALWAYS(p && p->pNext==pIndex) ){
73203         p->pNext = pIndex->pNext;
73204       }
73205     }
73206     freeIndex(pIndex);
73207   }
73208   db->flags |= SQLITE_InternChanges;
73209 }
73210
73211 /*
73212 ** Erase all schema information from the in-memory hash tables of
73213 ** a single database.  This routine is called to reclaim memory
73214 ** before the database closes.  It is also called during a rollback
73215 ** if there were schema changes during the transaction or if a
73216 ** schema-cookie mismatch occurs.
73217 **
73218 ** If iDb==0 then reset the internal schema tables for all database
73219 ** files.  If iDb>=1 then reset the internal schema for only the
73220 ** single file indicated.
73221 */
73222 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
73223   int i, j;
73224   assert( iDb>=0 && iDb<db->nDb );
73225
73226   if( iDb==0 ){
73227     sqlite3BtreeEnterAll(db);
73228   }
73229   for(i=iDb; i<db->nDb; i++){
73230     Db *pDb = &db->aDb[i];
73231     if( pDb->pSchema ){
73232       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
73233       sqlite3SchemaFree(pDb->pSchema);
73234     }
73235     if( iDb>0 ) return;
73236   }
73237   assert( iDb==0 );
73238   db->flags &= ~SQLITE_InternChanges;
73239   sqlite3VtabUnlockList(db);
73240   sqlite3BtreeLeaveAll(db);
73241
73242   /* If one or more of the auxiliary database files has been closed,
73243   ** then remove them from the auxiliary database list.  We take the
73244   ** opportunity to do this here since we have just deleted all of the
73245   ** schema hash tables and therefore do not have to make any changes
73246   ** to any of those tables.
73247   */
73248   for(i=j=2; i<db->nDb; i++){
73249     struct Db *pDb = &db->aDb[i];
73250     if( pDb->pBt==0 ){
73251       sqlite3DbFree(db, pDb->zName);
73252       pDb->zName = 0;
73253       continue;
73254     }
73255     if( j<i ){
73256       db->aDb[j] = db->aDb[i];
73257     }
73258     j++;
73259   }
73260   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
73261   db->nDb = j;
73262   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
73263     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
73264     sqlite3DbFree(db, db->aDb);
73265     db->aDb = db->aDbStatic;
73266   }
73267 }
73268
73269 /*
73270 ** This routine is called when a commit occurs.
73271 */
73272 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
73273   db->flags &= ~SQLITE_InternChanges;
73274 }
73275
73276 /*
73277 ** Clear the column names from a table or view.
73278 */
73279 static void sqliteResetColumnNames(Table *pTable){
73280   int i;
73281   Column *pCol;
73282   sqlite3 *db = pTable->dbMem;
73283   testcase( db==0 );
73284   assert( pTable!=0 );
73285   if( (pCol = pTable->aCol)!=0 ){
73286     for(i=0; i<pTable->nCol; i++, pCol++){
73287       sqlite3DbFree(db, pCol->zName);
73288       sqlite3ExprDelete(db, pCol->pDflt);
73289       sqlite3DbFree(db, pCol->zDflt);
73290       sqlite3DbFree(db, pCol->zType);
73291       sqlite3DbFree(db, pCol->zColl);
73292     }
73293     sqlite3DbFree(db, pTable->aCol);
73294   }
73295   pTable->aCol = 0;
73296   pTable->nCol = 0;
73297 }
73298
73299 /*
73300 ** Remove the memory data structures associated with the given
73301 ** Table.  No changes are made to disk by this routine.
73302 **
73303 ** This routine just deletes the data structure.  It does not unlink
73304 ** the table data structure from the hash table.  But it does destroy
73305 ** memory structures of the indices and foreign keys associated with 
73306 ** the table.
73307 */
73308 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
73309   Index *pIndex, *pNext;
73310   sqlite3 *db;
73311
73312   if( pTable==0 ) return;
73313   db = pTable->dbMem;
73314   testcase( db==0 );
73315
73316   /* Do not delete the table until the reference count reaches zero. */
73317   pTable->nRef--;
73318   if( pTable->nRef>0 ){
73319     return;
73320   }
73321   assert( pTable->nRef==0 );
73322
73323   /* Delete all indices associated with this table
73324   */
73325   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
73326     pNext = pIndex->pNext;
73327     assert( pIndex->pSchema==pTable->pSchema );
73328     sqlite3DeleteIndex(pIndex);
73329   }
73330
73331   /* Delete any foreign keys attached to this table. */
73332   sqlite3FkDelete(pTable);
73333
73334   /* Delete the Table structure itself.
73335   */
73336   sqliteResetColumnNames(pTable);
73337   sqlite3DbFree(db, pTable->zName);
73338   sqlite3DbFree(db, pTable->zColAff);
73339   sqlite3SelectDelete(db, pTable->pSelect);
73340 #ifndef SQLITE_OMIT_CHECK
73341   sqlite3ExprDelete(db, pTable->pCheck);
73342 #endif
73343   sqlite3VtabClear(pTable);
73344   sqlite3DbFree(db, pTable);
73345 }
73346
73347 /*
73348 ** Unlink the given table from the hash tables and the delete the
73349 ** table structure with all its indices and foreign keys.
73350 */
73351 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
73352   Table *p;
73353   Db *pDb;
73354
73355   assert( db!=0 );
73356   assert( iDb>=0 && iDb<db->nDb );
73357   assert( zTabName );
73358   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
73359   pDb = &db->aDb[iDb];
73360   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
73361                         sqlite3Strlen30(zTabName),0);
73362   sqlite3DeleteTable(p);
73363   db->flags |= SQLITE_InternChanges;
73364 }
73365
73366 /*
73367 ** Given a token, return a string that consists of the text of that
73368 ** token.  Space to hold the returned string
73369 ** is obtained from sqliteMalloc() and must be freed by the calling
73370 ** function.
73371 **
73372 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
73373 ** surround the body of the token are removed.
73374 **
73375 ** Tokens are often just pointers into the original SQL text and so
73376 ** are not \000 terminated and are not persistent.  The returned string
73377 ** is \000 terminated and is persistent.
73378 */
73379 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
73380   char *zName;
73381   if( pName ){
73382     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
73383     sqlite3Dequote(zName);
73384   }else{
73385     zName = 0;
73386   }
73387   return zName;
73388 }
73389
73390 /*
73391 ** Open the sqlite_master table stored in database number iDb for
73392 ** writing. The table is opened using cursor 0.
73393 */
73394 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
73395   Vdbe *v = sqlite3GetVdbe(p);
73396   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
73397   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
73398   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
73399   if( p->nTab==0 ){
73400     p->nTab = 1;
73401   }
73402 }
73403
73404 /*
73405 ** Parameter zName points to a nul-terminated buffer containing the name
73406 ** of a database ("main", "temp" or the name of an attached db). This
73407 ** function returns the index of the named database in db->aDb[], or
73408 ** -1 if the named db cannot be found.
73409 */
73410 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
73411   int i = -1;         /* Database number */
73412   if( zName ){
73413     Db *pDb;
73414     int n = sqlite3Strlen30(zName);
73415     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
73416       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
73417           0==sqlite3StrICmp(pDb->zName, zName) ){
73418         break;
73419       }
73420     }
73421   }
73422   return i;
73423 }
73424
73425 /*
73426 ** The token *pName contains the name of a database (either "main" or
73427 ** "temp" or the name of an attached db). This routine returns the
73428 ** index of the named database in db->aDb[], or -1 if the named db 
73429 ** does not exist.
73430 */
73431 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
73432   int i;                               /* Database number */
73433   char *zName;                         /* Name we are searching for */
73434   zName = sqlite3NameFromToken(db, pName);
73435   i = sqlite3FindDbName(db, zName);
73436   sqlite3DbFree(db, zName);
73437   return i;
73438 }
73439
73440 /* The table or view or trigger name is passed to this routine via tokens
73441 ** pName1 and pName2. If the table name was fully qualified, for example:
73442 **
73443 ** CREATE TABLE xxx.yyy (...);
73444 ** 
73445 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73446 ** the table name is not fully qualified, i.e.:
73447 **
73448 ** CREATE TABLE yyy(...);
73449 **
73450 ** Then pName1 is set to "yyy" and pName2 is "".
73451 **
73452 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
73453 ** pName2) that stores the unqualified table name.  The index of the
73454 ** database "xxx" is returned.
73455 */
73456 SQLITE_PRIVATE int sqlite3TwoPartName(
73457   Parse *pParse,      /* Parsing and code generating context */
73458   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
73459   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
73460   Token **pUnqual     /* Write the unqualified object name here */
73461 ){
73462   int iDb;                    /* Database holding the object */
73463   sqlite3 *db = pParse->db;
73464
73465   if( ALWAYS(pName2!=0) && pName2->n>0 ){
73466     if( db->init.busy ) {
73467       sqlite3ErrorMsg(pParse, "corrupt database");
73468       pParse->nErr++;
73469       return -1;
73470     }
73471     *pUnqual = pName2;
73472     iDb = sqlite3FindDb(db, pName1);
73473     if( iDb<0 ){
73474       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
73475       pParse->nErr++;
73476       return -1;
73477     }
73478   }else{
73479     assert( db->init.iDb==0 || db->init.busy );
73480     iDb = db->init.iDb;
73481     *pUnqual = pName1;
73482   }
73483   return iDb;
73484 }
73485
73486 /*
73487 ** This routine is used to check if the UTF-8 string zName is a legal
73488 ** unqualified name for a new schema object (table, index, view or
73489 ** trigger). All names are legal except those that begin with the string
73490 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
73491 ** is reserved for internal use.
73492 */
73493 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
73494   if( !pParse->db->init.busy && pParse->nested==0 
73495           && (pParse->db->flags & SQLITE_WriteSchema)==0
73496           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
73497     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
73498     return SQLITE_ERROR;
73499   }
73500   return SQLITE_OK;
73501 }
73502
73503 /*
73504 ** Begin constructing a new table representation in memory.  This is
73505 ** the first of several action routines that get called in response
73506 ** to a CREATE TABLE statement.  In particular, this routine is called
73507 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
73508 ** flag is true if the table should be stored in the auxiliary database
73509 ** file instead of in the main database file.  This is normally the case
73510 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
73511 ** CREATE and TABLE.
73512 **
73513 ** The new table record is initialized and put in pParse->pNewTable.
73514 ** As more of the CREATE TABLE statement is parsed, additional action
73515 ** routines will be called to add more information to this record.
73516 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
73517 ** is called to complete the construction of the new table record.
73518 */
73519 SQLITE_PRIVATE void sqlite3StartTable(
73520   Parse *pParse,   /* Parser context */
73521   Token *pName1,   /* First part of the name of the table or view */
73522   Token *pName2,   /* Second part of the name of the table or view */
73523   int isTemp,      /* True if this is a TEMP table */
73524   int isView,      /* True if this is a VIEW */
73525   int isVirtual,   /* True if this is a VIRTUAL table */
73526   int noErr        /* Do nothing if table already exists */
73527 ){
73528   Table *pTable;
73529   char *zName = 0; /* The name of the new table */
73530   sqlite3 *db = pParse->db;
73531   Vdbe *v;
73532   int iDb;         /* Database number to create the table in */
73533   Token *pName;    /* Unqualified name of the table to create */
73534
73535   /* The table or view name to create is passed to this routine via tokens
73536   ** pName1 and pName2. If the table name was fully qualified, for example:
73537   **
73538   ** CREATE TABLE xxx.yyy (...);
73539   ** 
73540   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73541   ** the table name is not fully qualified, i.e.:
73542   **
73543   ** CREATE TABLE yyy(...);
73544   **
73545   ** Then pName1 is set to "yyy" and pName2 is "".
73546   **
73547   ** The call below sets the pName pointer to point at the token (pName1 or
73548   ** pName2) that stores the unqualified table name. The variable iDb is
73549   ** set to the index of the database that the table or view is to be
73550   ** created in.
73551   */
73552   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
73553   if( iDb<0 ) return;
73554   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
73555     /* If creating a temp table, the name may not be qualified */
73556     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
73557     return;
73558   }
73559   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
73560
73561   pParse->sNameToken = *pName;
73562   zName = sqlite3NameFromToken(db, pName);
73563   if( zName==0 ) return;
73564   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
73565     goto begin_table_error;
73566   }
73567   if( db->init.iDb==1 ) isTemp = 1;
73568 #ifndef SQLITE_OMIT_AUTHORIZATION
73569   assert( (isTemp & 1)==isTemp );
73570   {
73571     int code;
73572     char *zDb = db->aDb[iDb].zName;
73573     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
73574       goto begin_table_error;
73575     }
73576     if( isView ){
73577       if( !OMIT_TEMPDB && isTemp ){
73578         code = SQLITE_CREATE_TEMP_VIEW;
73579       }else{
73580         code = SQLITE_CREATE_VIEW;
73581       }
73582     }else{
73583       if( !OMIT_TEMPDB && isTemp ){
73584         code = SQLITE_CREATE_TEMP_TABLE;
73585       }else{
73586         code = SQLITE_CREATE_TABLE;
73587       }
73588     }
73589     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
73590       goto begin_table_error;
73591     }
73592   }
73593 #endif
73594
73595   /* Make sure the new table name does not collide with an existing
73596   ** index or table name in the same database.  Issue an error message if
73597   ** it does. The exception is if the statement being parsed was passed
73598   ** to an sqlite3_declare_vtab() call. In that case only the column names
73599   ** and types will be used, so there is no need to test for namespace
73600   ** collisions.
73601   */
73602   if( !IN_DECLARE_VTAB ){
73603     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73604       goto begin_table_error;
73605     }
73606     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
73607     if( pTable ){
73608       if( !noErr ){
73609         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
73610       }
73611       goto begin_table_error;
73612     }
73613     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
73614       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
73615       goto begin_table_error;
73616     }
73617   }
73618
73619   pTable = sqlite3DbMallocZero(db, sizeof(Table));
73620   if( pTable==0 ){
73621     db->mallocFailed = 1;
73622     pParse->rc = SQLITE_NOMEM;
73623     pParse->nErr++;
73624     goto begin_table_error;
73625   }
73626   pTable->zName = zName;
73627   pTable->iPKey = -1;
73628   pTable->pSchema = db->aDb[iDb].pSchema;
73629   pTable->nRef = 1;
73630   pTable->dbMem = 0;
73631   assert( pParse->pNewTable==0 );
73632   pParse->pNewTable = pTable;
73633
73634   /* If this is the magic sqlite_sequence table used by autoincrement,
73635   ** then record a pointer to this table in the main database structure
73636   ** so that INSERT can find the table easily.
73637   */
73638 #ifndef SQLITE_OMIT_AUTOINCREMENT
73639   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
73640     pTable->pSchema->pSeqTab = pTable;
73641   }
73642 #endif
73643
73644   /* Begin generating the code that will insert the table record into
73645   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
73646   ** and allocate the record number for the table entry now.  Before any
73647   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
73648   ** indices to be created and the table record must come before the 
73649   ** indices.  Hence, the record number for the table must be allocated
73650   ** now.
73651   */
73652   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
73653     int j1;
73654     int fileFormat;
73655     int reg1, reg2, reg3;
73656     sqlite3BeginWriteOperation(pParse, 0, iDb);
73657
73658 #ifndef SQLITE_OMIT_VIRTUALTABLE
73659     if( isVirtual ){
73660       sqlite3VdbeAddOp0(v, OP_VBegin);
73661     }
73662 #endif
73663
73664     /* If the file format and encoding in the database have not been set, 
73665     ** set them now.
73666     */
73667     reg1 = pParse->regRowid = ++pParse->nMem;
73668     reg2 = pParse->regRoot = ++pParse->nMem;
73669     reg3 = ++pParse->nMem;
73670     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
73671     sqlite3VdbeUsesBtree(v, iDb);
73672     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
73673     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
73674                   1 : SQLITE_MAX_FILE_FORMAT;
73675     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
73676     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
73677     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
73678     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
73679     sqlite3VdbeJumpHere(v, j1);
73680
73681     /* This just creates a place-holder record in the sqlite_master table.
73682     ** The record created does not contain anything yet.  It will be replaced
73683     ** by the real entry in code generated at sqlite3EndTable().
73684     **
73685     ** The rowid for the new entry is left in register pParse->regRowid.
73686     ** The root page number of the new table is left in reg pParse->regRoot.
73687     ** The rowid and root page number values are needed by the code that
73688     ** sqlite3EndTable will generate.
73689     */
73690 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
73691     if( isView || isVirtual ){
73692       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
73693     }else
73694 #endif
73695     {
73696       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
73697     }
73698     sqlite3OpenMasterTable(pParse, iDb);
73699     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
73700     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
73701     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
73702     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73703     sqlite3VdbeAddOp0(v, OP_Close);
73704   }
73705
73706   /* Normal (non-error) return. */
73707   return;
73708
73709   /* If an error occurs, we jump here */
73710 begin_table_error:
73711   sqlite3DbFree(db, zName);
73712   return;
73713 }
73714
73715 /*
73716 ** This macro is used to compare two strings in a case-insensitive manner.
73717 ** It is slightly faster than calling sqlite3StrICmp() directly, but
73718 ** produces larger code.
73719 **
73720 ** WARNING: This macro is not compatible with the strcmp() family. It
73721 ** returns true if the two strings are equal, otherwise false.
73722 */
73723 #define STRICMP(x, y) (\
73724 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
73725 sqlite3UpperToLower[*(unsigned char *)(y)]     \
73726 && sqlite3StrICmp((x)+1,(y)+1)==0 )
73727
73728 /*
73729 ** Add a new column to the table currently being constructed.
73730 **
73731 ** The parser calls this routine once for each column declaration
73732 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
73733 ** first to get things going.  Then this routine is called for each
73734 ** column.
73735 */
73736 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
73737   Table *p;
73738   int i;
73739   char *z;
73740   Column *pCol;
73741   sqlite3 *db = pParse->db;
73742   if( (p = pParse->pNewTable)==0 ) return;
73743 #if SQLITE_MAX_COLUMN
73744   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73745     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
73746     return;
73747   }
73748 #endif
73749   z = sqlite3NameFromToken(db, pName);
73750   if( z==0 ) return;
73751   for(i=0; i<p->nCol; i++){
73752     if( STRICMP(z, p->aCol[i].zName) ){
73753       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
73754       sqlite3DbFree(db, z);
73755       return;
73756     }
73757   }
73758   if( (p->nCol & 0x7)==0 ){
73759     Column *aNew;
73760     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
73761     if( aNew==0 ){
73762       sqlite3DbFree(db, z);
73763       return;
73764     }
73765     p->aCol = aNew;
73766   }
73767   pCol = &p->aCol[p->nCol];
73768   memset(pCol, 0, sizeof(p->aCol[0]));
73769   pCol->zName = z;
73770  
73771   /* If there is no type specified, columns have the default affinity
73772   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
73773   ** be called next to set pCol->affinity correctly.
73774   */
73775   pCol->affinity = SQLITE_AFF_NONE;
73776   p->nCol++;
73777 }
73778
73779 /*
73780 ** This routine is called by the parser while in the middle of
73781 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
73782 ** been seen on a column.  This routine sets the notNull flag on
73783 ** the column currently under construction.
73784 */
73785 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
73786   Table *p;
73787   p = pParse->pNewTable;
73788   if( p==0 || NEVER(p->nCol<1) ) return;
73789   p->aCol[p->nCol-1].notNull = (u8)onError;
73790 }
73791
73792 /*
73793 ** Scan the column type name zType (length nType) and return the
73794 ** associated affinity type.
73795 **
73796 ** This routine does a case-independent search of zType for the 
73797 ** substrings in the following table. If one of the substrings is
73798 ** found, the corresponding affinity is returned. If zType contains
73799 ** more than one of the substrings, entries toward the top of 
73800 ** the table take priority. For example, if zType is 'BLOBINT', 
73801 ** SQLITE_AFF_INTEGER is returned.
73802 **
73803 ** Substring     | Affinity
73804 ** --------------------------------
73805 ** 'INT'         | SQLITE_AFF_INTEGER
73806 ** 'CHAR'        | SQLITE_AFF_TEXT
73807 ** 'CLOB'        | SQLITE_AFF_TEXT
73808 ** 'TEXT'        | SQLITE_AFF_TEXT
73809 ** 'BLOB'        | SQLITE_AFF_NONE
73810 ** 'REAL'        | SQLITE_AFF_REAL
73811 ** 'FLOA'        | SQLITE_AFF_REAL
73812 ** 'DOUB'        | SQLITE_AFF_REAL
73813 **
73814 ** If none of the substrings in the above table are found,
73815 ** SQLITE_AFF_NUMERIC is returned.
73816 */
73817 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
73818   u32 h = 0;
73819   char aff = SQLITE_AFF_NUMERIC;
73820
73821   if( zIn ) while( zIn[0] ){
73822     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
73823     zIn++;
73824     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
73825       aff = SQLITE_AFF_TEXT; 
73826     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
73827       aff = SQLITE_AFF_TEXT;
73828     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
73829       aff = SQLITE_AFF_TEXT;
73830     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
73831         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
73832       aff = SQLITE_AFF_NONE;
73833 #ifndef SQLITE_OMIT_FLOATING_POINT
73834     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
73835         && aff==SQLITE_AFF_NUMERIC ){
73836       aff = SQLITE_AFF_REAL;
73837     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
73838         && aff==SQLITE_AFF_NUMERIC ){
73839       aff = SQLITE_AFF_REAL;
73840     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
73841         && aff==SQLITE_AFF_NUMERIC ){
73842       aff = SQLITE_AFF_REAL;
73843 #endif
73844     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
73845       aff = SQLITE_AFF_INTEGER;
73846       break;
73847     }
73848   }
73849
73850   return aff;
73851 }
73852
73853 /*
73854 ** This routine is called by the parser while in the middle of
73855 ** parsing a CREATE TABLE statement.  The pFirst token is the first
73856 ** token in the sequence of tokens that describe the type of the
73857 ** column currently under construction.   pLast is the last token
73858 ** in the sequence.  Use this information to construct a string
73859 ** that contains the typename of the column and store that string
73860 ** in zType.
73861 */ 
73862 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
73863   Table *p;
73864   Column *pCol;
73865
73866   p = pParse->pNewTable;
73867   if( p==0 || NEVER(p->nCol<1) ) return;
73868   pCol = &p->aCol[p->nCol-1];
73869   assert( pCol->zType==0 );
73870   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
73871   pCol->affinity = sqlite3AffinityType(pCol->zType);
73872 }
73873
73874 /*
73875 ** The expression is the default value for the most recently added column
73876 ** of the table currently under construction.
73877 **
73878 ** Default value expressions must be constant.  Raise an exception if this
73879 ** is not the case.
73880 **
73881 ** This routine is called by the parser while in the middle of
73882 ** parsing a CREATE TABLE statement.
73883 */
73884 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
73885   Table *p;
73886   Column *pCol;
73887   sqlite3 *db = pParse->db;
73888   p = pParse->pNewTable;
73889   if( p!=0 ){
73890     pCol = &(p->aCol[p->nCol-1]);
73891     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
73892       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
73893           pCol->zName);
73894     }else{
73895       /* A copy of pExpr is used instead of the original, as pExpr contains
73896       ** tokens that point to volatile memory. The 'span' of the expression
73897       ** is required by pragma table_info.
73898       */
73899       sqlite3ExprDelete(db, pCol->pDflt);
73900       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
73901       sqlite3DbFree(db, pCol->zDflt);
73902       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
73903                                      (int)(pSpan->zEnd - pSpan->zStart));
73904     }
73905   }
73906   sqlite3ExprDelete(db, pSpan->pExpr);
73907 }
73908
73909 /*
73910 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
73911 ** of columns that form the primary key.  If pList is NULL, then the
73912 ** most recently added column of the table is the primary key.
73913 **
73914 ** A table can have at most one primary key.  If the table already has
73915 ** a primary key (and this is the second primary key) then create an
73916 ** error.
73917 **
73918 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
73919 ** then we will try to use that column as the rowid.  Set the Table.iPKey
73920 ** field of the table under construction to be the index of the
73921 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
73922 ** no INTEGER PRIMARY KEY.
73923 **
73924 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
73925 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
73926 */
73927 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
73928   Parse *pParse,    /* Parsing context */
73929   ExprList *pList,  /* List of field names to be indexed */
73930   int onError,      /* What to do with a uniqueness conflict */
73931   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
73932   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
73933 ){
73934   Table *pTab = pParse->pNewTable;
73935   char *zType = 0;
73936   int iCol = -1, i;
73937   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
73938   if( pTab->tabFlags & TF_HasPrimaryKey ){
73939     sqlite3ErrorMsg(pParse, 
73940       "table \"%s\" has more than one primary key", pTab->zName);
73941     goto primary_key_exit;
73942   }
73943   pTab->tabFlags |= TF_HasPrimaryKey;
73944   if( pList==0 ){
73945     iCol = pTab->nCol - 1;
73946     pTab->aCol[iCol].isPrimKey = 1;
73947   }else{
73948     for(i=0; i<pList->nExpr; i++){
73949       for(iCol=0; iCol<pTab->nCol; iCol++){
73950         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
73951           break;
73952         }
73953       }
73954       if( iCol<pTab->nCol ){
73955         pTab->aCol[iCol].isPrimKey = 1;
73956       }
73957     }
73958     if( pList->nExpr>1 ) iCol = -1;
73959   }
73960   if( iCol>=0 && iCol<pTab->nCol ){
73961     zType = pTab->aCol[iCol].zType;
73962   }
73963   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
73964         && sortOrder==SQLITE_SO_ASC ){
73965     pTab->iPKey = iCol;
73966     pTab->keyConf = (u8)onError;
73967     assert( autoInc==0 || autoInc==1 );
73968     pTab->tabFlags |= autoInc*TF_Autoincrement;
73969   }else if( autoInc ){
73970 #ifndef SQLITE_OMIT_AUTOINCREMENT
73971     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
73972        "INTEGER PRIMARY KEY");
73973 #endif
73974   }else{
73975     Index *p;
73976     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
73977     if( p ){
73978       p->autoIndex = 2;
73979     }
73980     pList = 0;
73981   }
73982
73983 primary_key_exit:
73984   sqlite3ExprListDelete(pParse->db, pList);
73985   return;
73986 }
73987
73988 /*
73989 ** Add a new CHECK constraint to the table currently under construction.
73990 */
73991 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
73992   Parse *pParse,    /* Parsing context */
73993   Expr *pCheckExpr  /* The check expression */
73994 ){
73995   sqlite3 *db = pParse->db;
73996 #ifndef SQLITE_OMIT_CHECK
73997   Table *pTab = pParse->pNewTable;
73998   if( pTab && !IN_DECLARE_VTAB ){
73999     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
74000   }else
74001 #endif
74002   {
74003     sqlite3ExprDelete(db, pCheckExpr);
74004   }
74005 }
74006
74007 /*
74008 ** Set the collation function of the most recently parsed table column
74009 ** to the CollSeq given.
74010 */
74011 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
74012   Table *p;
74013   int i;
74014   char *zColl;              /* Dequoted name of collation sequence */
74015   sqlite3 *db;
74016
74017   if( (p = pParse->pNewTable)==0 ) return;
74018   i = p->nCol-1;
74019   db = pParse->db;
74020   zColl = sqlite3NameFromToken(db, pToken);
74021   if( !zColl ) return;
74022
74023   if( sqlite3LocateCollSeq(pParse, zColl) ){
74024     Index *pIdx;
74025     p->aCol[i].zColl = zColl;
74026   
74027     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
74028     ** then an index may have been created on this column before the
74029     ** collation type was added. Correct this if it is the case.
74030     */
74031     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
74032       assert( pIdx->nColumn==1 );
74033       if( pIdx->aiColumn[0]==i ){
74034         pIdx->azColl[0] = p->aCol[i].zColl;
74035       }
74036     }
74037   }else{
74038     sqlite3DbFree(db, zColl);
74039   }
74040 }
74041
74042 /*
74043 ** This function returns the collation sequence for database native text
74044 ** encoding identified by the string zName, length nName.
74045 **
74046 ** If the requested collation sequence is not available, or not available
74047 ** in the database native encoding, the collation factory is invoked to
74048 ** request it. If the collation factory does not supply such a sequence,
74049 ** and the sequence is available in another text encoding, then that is
74050 ** returned instead.
74051 **
74052 ** If no versions of the requested collations sequence are available, or
74053 ** another error occurs, NULL is returned and an error message written into
74054 ** pParse.
74055 **
74056 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
74057 ** invokes the collation factory if the named collation cannot be found
74058 ** and generates an error message.
74059 **
74060 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
74061 */
74062 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
74063   sqlite3 *db = pParse->db;
74064   u8 enc = ENC(db);
74065   u8 initbusy = db->init.busy;
74066   CollSeq *pColl;
74067
74068   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
74069   if( !initbusy && (!pColl || !pColl->xCmp) ){
74070     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
74071     if( !pColl ){
74072       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
74073     }
74074   }
74075
74076   return pColl;
74077 }
74078
74079
74080 /*
74081 ** Generate code that will increment the schema cookie.
74082 **
74083 ** The schema cookie is used to determine when the schema for the
74084 ** database changes.  After each schema change, the cookie value
74085 ** changes.  When a process first reads the schema it records the
74086 ** cookie.  Thereafter, whenever it goes to access the database,
74087 ** it checks the cookie to make sure the schema has not changed
74088 ** since it was last read.
74089 **
74090 ** This plan is not completely bullet-proof.  It is possible for
74091 ** the schema to change multiple times and for the cookie to be
74092 ** set back to prior value.  But schema changes are infrequent
74093 ** and the probability of hitting the same cookie value is only
74094 ** 1 chance in 2^32.  So we're safe enough.
74095 */
74096 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
74097   int r1 = sqlite3GetTempReg(pParse);
74098   sqlite3 *db = pParse->db;
74099   Vdbe *v = pParse->pVdbe;
74100   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
74101   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
74102   sqlite3ReleaseTempReg(pParse, r1);
74103 }
74104
74105 /*
74106 ** Measure the number of characters needed to output the given
74107 ** identifier.  The number returned includes any quotes used
74108 ** but does not include the null terminator.
74109 **
74110 ** The estimate is conservative.  It might be larger that what is
74111 ** really needed.
74112 */
74113 static int identLength(const char *z){
74114   int n;
74115   for(n=0; *z; n++, z++){
74116     if( *z=='"' ){ n++; }
74117   }
74118   return n + 2;
74119 }
74120
74121 /*
74122 ** The first parameter is a pointer to an output buffer. The second 
74123 ** parameter is a pointer to an integer that contains the offset at
74124 ** which to write into the output buffer. This function copies the
74125 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
74126 ** to the specified offset in the buffer and updates *pIdx to refer
74127 ** to the first byte after the last byte written before returning.
74128 ** 
74129 ** If the string zSignedIdent consists entirely of alpha-numeric
74130 ** characters, does not begin with a digit and is not an SQL keyword,
74131 ** then it is copied to the output buffer exactly as it is. Otherwise,
74132 ** it is quoted using double-quotes.
74133 */
74134 static void identPut(char *z, int *pIdx, char *zSignedIdent){
74135   unsigned char *zIdent = (unsigned char*)zSignedIdent;
74136   int i, j, needQuote;
74137   i = *pIdx;
74138
74139   for(j=0; zIdent[j]; j++){
74140     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
74141   }
74142   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
74143   if( !needQuote ){
74144     needQuote = zIdent[j];
74145   }
74146
74147   if( needQuote ) z[i++] = '"';
74148   for(j=0; zIdent[j]; j++){
74149     z[i++] = zIdent[j];
74150     if( zIdent[j]=='"' ) z[i++] = '"';
74151   }
74152   if( needQuote ) z[i++] = '"';
74153   z[i] = 0;
74154   *pIdx = i;
74155 }
74156
74157 /*
74158 ** Generate a CREATE TABLE statement appropriate for the given
74159 ** table.  Memory to hold the text of the statement is obtained
74160 ** from sqliteMalloc() and must be freed by the calling function.
74161 */
74162 static char *createTableStmt(sqlite3 *db, Table *p){
74163   int i, k, n;
74164   char *zStmt;
74165   char *zSep, *zSep2, *zEnd;
74166   Column *pCol;
74167   n = 0;
74168   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
74169     n += identLength(pCol->zName) + 5;
74170   }
74171   n += identLength(p->zName);
74172   if( n<50 ){ 
74173     zSep = "";
74174     zSep2 = ",";
74175     zEnd = ")";
74176   }else{
74177     zSep = "\n  ";
74178     zSep2 = ",\n  ";
74179     zEnd = "\n)";
74180   }
74181   n += 35 + 6*p->nCol;
74182   zStmt = sqlite3Malloc( n );
74183   if( zStmt==0 ){
74184     db->mallocFailed = 1;
74185     return 0;
74186   }
74187   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
74188   k = sqlite3Strlen30(zStmt);
74189   identPut(zStmt, &k, p->zName);
74190   zStmt[k++] = '(';
74191   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
74192     static const char * const azType[] = {
74193         /* SQLITE_AFF_TEXT    */ " TEXT",
74194         /* SQLITE_AFF_NONE    */ "",
74195         /* SQLITE_AFF_NUMERIC */ " NUM",
74196         /* SQLITE_AFF_INTEGER */ " INT",
74197         /* SQLITE_AFF_REAL    */ " REAL"
74198     };
74199     int len;
74200     const char *zType;
74201
74202     sqlite3_snprintf(n-k, &zStmt[k], zSep);
74203     k += sqlite3Strlen30(&zStmt[k]);
74204     zSep = zSep2;
74205     identPut(zStmt, &k, pCol->zName);
74206     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
74207     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
74208     testcase( pCol->affinity==SQLITE_AFF_TEXT );
74209     testcase( pCol->affinity==SQLITE_AFF_NONE );
74210     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
74211     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
74212     testcase( pCol->affinity==SQLITE_AFF_REAL );
74213     
74214     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
74215     len = sqlite3Strlen30(zType);
74216     assert( pCol->affinity==SQLITE_AFF_NONE 
74217             || pCol->affinity==sqlite3AffinityType(zType) );
74218     memcpy(&zStmt[k], zType, len);
74219     k += len;
74220     assert( k<=n );
74221   }
74222   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
74223   return zStmt;
74224 }
74225
74226 /*
74227 ** This routine is called to report the final ")" that terminates
74228 ** a CREATE TABLE statement.
74229 **
74230 ** The table structure that other action routines have been building
74231 ** is added to the internal hash tables, assuming no errors have
74232 ** occurred.
74233 **
74234 ** An entry for the table is made in the master table on disk, unless
74235 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
74236 ** it means we are reading the sqlite_master table because we just
74237 ** connected to the database or because the sqlite_master table has
74238 ** recently changed, so the entry for this table already exists in
74239 ** the sqlite_master table.  We do not want to create it again.
74240 **
74241 ** If the pSelect argument is not NULL, it means that this routine
74242 ** was called to create a table generated from a 
74243 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
74244 ** the new table will match the result set of the SELECT.
74245 */
74246 SQLITE_PRIVATE void sqlite3EndTable(
74247   Parse *pParse,          /* Parse context */
74248   Token *pCons,           /* The ',' token after the last column defn. */
74249   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
74250   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
74251 ){
74252   Table *p;
74253   sqlite3 *db = pParse->db;
74254   int iDb;
74255
74256   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
74257     return;
74258   }
74259   p = pParse->pNewTable;
74260   if( p==0 ) return;
74261
74262   assert( !db->init.busy || !pSelect );
74263
74264   iDb = sqlite3SchemaToIndex(db, p->pSchema);
74265
74266 #ifndef SQLITE_OMIT_CHECK
74267   /* Resolve names in all CHECK constraint expressions.
74268   */
74269   if( p->pCheck ){
74270     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
74271     NameContext sNC;                /* Name context for pParse->pNewTable */
74272
74273     memset(&sNC, 0, sizeof(sNC));
74274     memset(&sSrc, 0, sizeof(sSrc));
74275     sSrc.nSrc = 1;
74276     sSrc.a[0].zName = p->zName;
74277     sSrc.a[0].pTab = p;
74278     sSrc.a[0].iCursor = -1;
74279     sNC.pParse = pParse;
74280     sNC.pSrcList = &sSrc;
74281     sNC.isCheck = 1;
74282     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
74283       return;
74284     }
74285   }
74286 #endif /* !defined(SQLITE_OMIT_CHECK) */
74287
74288   /* If the db->init.busy is 1 it means we are reading the SQL off the
74289   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
74290   ** So do not write to the disk again.  Extract the root page number
74291   ** for the table from the db->init.newTnum field.  (The page number
74292   ** should have been put there by the sqliteOpenCb routine.)
74293   */
74294   if( db->init.busy ){
74295     p->tnum = db->init.newTnum;
74296   }
74297
74298   /* If not initializing, then create a record for the new table
74299   ** in the SQLITE_MASTER table of the database.
74300   **
74301   ** If this is a TEMPORARY table, write the entry into the auxiliary
74302   ** file instead of into the main database file.
74303   */
74304   if( !db->init.busy ){
74305     int n;
74306     Vdbe *v;
74307     char *zType;    /* "view" or "table" */
74308     char *zType2;   /* "VIEW" or "TABLE" */
74309     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
74310
74311     v = sqlite3GetVdbe(pParse);
74312     if( NEVER(v==0) ) return;
74313
74314     sqlite3VdbeAddOp1(v, OP_Close, 0);
74315
74316     /* 
74317     ** Initialize zType for the new view or table.
74318     */
74319     if( p->pSelect==0 ){
74320       /* A regular table */
74321       zType = "table";
74322       zType2 = "TABLE";
74323 #ifndef SQLITE_OMIT_VIEW
74324     }else{
74325       /* A view */
74326       zType = "view";
74327       zType2 = "VIEW";
74328 #endif
74329     }
74330
74331     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
74332     ** statement to populate the new table. The root-page number for the
74333     ** new table is in register pParse->regRoot.
74334     **
74335     ** Once the SELECT has been coded by sqlite3Select(), it is in a
74336     ** suitable state to query for the column names and types to be used
74337     ** by the new table.
74338     **
74339     ** A shared-cache write-lock is not required to write to the new table,
74340     ** as a schema-lock must have already been obtained to create it. Since
74341     ** a schema-lock excludes all other database users, the write-lock would
74342     ** be redundant.
74343     */
74344     if( pSelect ){
74345       SelectDest dest;
74346       Table *pSelTab;
74347
74348       assert(pParse->nTab==1);
74349       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
74350       sqlite3VdbeChangeP5(v, 1);
74351       pParse->nTab = 2;
74352       sqlite3SelectDestInit(&dest, SRT_Table, 1);
74353       sqlite3Select(pParse, pSelect, &dest);
74354       sqlite3VdbeAddOp1(v, OP_Close, 1);
74355       if( pParse->nErr==0 ){
74356         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
74357         if( pSelTab==0 ) return;
74358         assert( p->aCol==0 );
74359         p->nCol = pSelTab->nCol;
74360         p->aCol = pSelTab->aCol;
74361         pSelTab->nCol = 0;
74362         pSelTab->aCol = 0;
74363         sqlite3DeleteTable(pSelTab);
74364       }
74365     }
74366
74367     /* Compute the complete text of the CREATE statement */
74368     if( pSelect ){
74369       zStmt = createTableStmt(db, p);
74370     }else{
74371       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
74372       zStmt = sqlite3MPrintf(db, 
74373           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
74374       );
74375     }
74376
74377     /* A slot for the record has already been allocated in the 
74378     ** SQLITE_MASTER table.  We just need to update that slot with all
74379     ** the information we've collected.
74380     */
74381     sqlite3NestedParse(pParse,
74382       "UPDATE %Q.%s "
74383          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
74384        "WHERE rowid=#%d",
74385       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
74386       zType,
74387       p->zName,
74388       p->zName,
74389       pParse->regRoot,
74390       zStmt,
74391       pParse->regRowid
74392     );
74393     sqlite3DbFree(db, zStmt);
74394     sqlite3ChangeCookie(pParse, iDb);
74395
74396 #ifndef SQLITE_OMIT_AUTOINCREMENT
74397     /* Check to see if we need to create an sqlite_sequence table for
74398     ** keeping track of autoincrement keys.
74399     */
74400     if( p->tabFlags & TF_Autoincrement ){
74401       Db *pDb = &db->aDb[iDb];
74402       if( pDb->pSchema->pSeqTab==0 ){
74403         sqlite3NestedParse(pParse,
74404           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
74405           pDb->zName
74406         );
74407       }
74408     }
74409 #endif
74410
74411     /* Reparse everything to update our internal data structures */
74412     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
74413         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
74414   }
74415
74416
74417   /* Add the table to the in-memory representation of the database.
74418   */
74419   if( db->init.busy ){
74420     Table *pOld;
74421     Schema *pSchema = p->pSchema;
74422     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
74423                              sqlite3Strlen30(p->zName),p);
74424     if( pOld ){
74425       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
74426       db->mallocFailed = 1;
74427       return;
74428     }
74429     pParse->pNewTable = 0;
74430     db->nTable++;
74431     db->flags |= SQLITE_InternChanges;
74432
74433 #ifndef SQLITE_OMIT_ALTERTABLE
74434     if( !p->pSelect ){
74435       const char *zName = (const char *)pParse->sNameToken.z;
74436       int nName;
74437       assert( !pSelect && pCons && pEnd );
74438       if( pCons->z==0 ){
74439         pCons = pEnd;
74440       }
74441       nName = (int)((const char *)pCons->z - zName);
74442       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
74443     }
74444 #endif
74445   }
74446 }
74447
74448 #ifndef SQLITE_OMIT_VIEW
74449 /*
74450 ** The parser calls this routine in order to create a new VIEW
74451 */
74452 SQLITE_PRIVATE void sqlite3CreateView(
74453   Parse *pParse,     /* The parsing context */
74454   Token *pBegin,     /* The CREATE token that begins the statement */
74455   Token *pName1,     /* The token that holds the name of the view */
74456   Token *pName2,     /* The token that holds the name of the view */
74457   Select *pSelect,   /* A SELECT statement that will become the new view */
74458   int isTemp,        /* TRUE for a TEMPORARY view */
74459   int noErr          /* Suppress error messages if VIEW already exists */
74460 ){
74461   Table *p;
74462   int n;
74463   const char *z;
74464   Token sEnd;
74465   DbFixer sFix;
74466   Token *pName;
74467   int iDb;
74468   sqlite3 *db = pParse->db;
74469
74470   if( pParse->nVar>0 ){
74471     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
74472     sqlite3SelectDelete(db, pSelect);
74473     return;
74474   }
74475   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
74476   p = pParse->pNewTable;
74477   if( p==0 ){
74478     sqlite3SelectDelete(db, pSelect);
74479     return;
74480   }
74481   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
74482                              ** there could not have been an error */
74483   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74484   iDb = sqlite3SchemaToIndex(db, p->pSchema);
74485   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
74486     && sqlite3FixSelect(&sFix, pSelect)
74487   ){
74488     sqlite3SelectDelete(db, pSelect);
74489     return;
74490   }
74491
74492   /* Make a copy of the entire SELECT statement that defines the view.
74493   ** This will force all the Expr.token.z values to be dynamically
74494   ** allocated rather than point to the input string - which means that
74495   ** they will persist after the current sqlite3_exec() call returns.
74496   */
74497   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
74498   sqlite3SelectDelete(db, pSelect);
74499   if( db->mallocFailed ){
74500     return;
74501   }
74502   if( !db->init.busy ){
74503     sqlite3ViewGetColumnNames(pParse, p);
74504   }
74505
74506   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
74507   ** the end.
74508   */
74509   sEnd = pParse->sLastToken;
74510   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
74511     sEnd.z += sEnd.n;
74512   }
74513   sEnd.n = 0;
74514   n = (int)(sEnd.z - pBegin->z);
74515   z = pBegin->z;
74516   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
74517   sEnd.z = &z[n-1];
74518   sEnd.n = 1;
74519
74520   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
74521   sqlite3EndTable(pParse, 0, &sEnd, 0);
74522   return;
74523 }
74524 #endif /* SQLITE_OMIT_VIEW */
74525
74526 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
74527 /*
74528 ** The Table structure pTable is really a VIEW.  Fill in the names of
74529 ** the columns of the view in the pTable structure.  Return the number
74530 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
74531 */
74532 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
74533   Table *pSelTab;   /* A fake table from which we get the result set */
74534   Select *pSel;     /* Copy of the SELECT that implements the view */
74535   int nErr = 0;     /* Number of errors encountered */
74536   int n;            /* Temporarily holds the number of cursors assigned */
74537   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
74538   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
74539
74540   assert( pTable );
74541
74542 #ifndef SQLITE_OMIT_VIRTUALTABLE
74543   if( sqlite3VtabCallConnect(pParse, pTable) ){
74544     return SQLITE_ERROR;
74545   }
74546   if( IsVirtual(pTable) ) return 0;
74547 #endif
74548
74549 #ifndef SQLITE_OMIT_VIEW
74550   /* A positive nCol means the columns names for this view are
74551   ** already known.
74552   */
74553   if( pTable->nCol>0 ) return 0;
74554
74555   /* A negative nCol is a special marker meaning that we are currently
74556   ** trying to compute the column names.  If we enter this routine with
74557   ** a negative nCol, it means two or more views form a loop, like this:
74558   **
74559   **     CREATE VIEW one AS SELECT * FROM two;
74560   **     CREATE VIEW two AS SELECT * FROM one;
74561   **
74562   ** Actually, the error above is now caught prior to reaching this point.
74563   ** But the following test is still important as it does come up
74564   ** in the following:
74565   ** 
74566   **     CREATE TABLE main.ex1(a);
74567   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
74568   **     SELECT * FROM temp.ex1;
74569   */
74570   if( pTable->nCol<0 ){
74571     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
74572     return 1;
74573   }
74574   assert( pTable->nCol>=0 );
74575
74576   /* If we get this far, it means we need to compute the table names.
74577   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
74578   ** "*" elements in the results set of the view and will assign cursors
74579   ** to the elements of the FROM clause.  But we do not want these changes
74580   ** to be permanent.  So the computation is done on a copy of the SELECT
74581   ** statement that defines the view.
74582   */
74583   assert( pTable->pSelect );
74584   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
74585   if( pSel ){
74586     u8 enableLookaside = db->lookaside.bEnabled;
74587     n = pParse->nTab;
74588     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
74589     pTable->nCol = -1;
74590     db->lookaside.bEnabled = 0;
74591 #ifndef SQLITE_OMIT_AUTHORIZATION
74592     xAuth = db->xAuth;
74593     db->xAuth = 0;
74594     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74595     db->xAuth = xAuth;
74596 #else
74597     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74598 #endif
74599     db->lookaside.bEnabled = enableLookaside;
74600     pParse->nTab = n;
74601     if( pSelTab ){
74602       assert( pTable->aCol==0 );
74603       pTable->nCol = pSelTab->nCol;
74604       pTable->aCol = pSelTab->aCol;
74605       pSelTab->nCol = 0;
74606       pSelTab->aCol = 0;
74607       sqlite3DeleteTable(pSelTab);
74608       pTable->pSchema->flags |= DB_UnresetViews;
74609     }else{
74610       pTable->nCol = 0;
74611       nErr++;
74612     }
74613     sqlite3SelectDelete(db, pSel);
74614   } else {
74615     nErr++;
74616   }
74617 #endif /* SQLITE_OMIT_VIEW */
74618   return nErr;  
74619 }
74620 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
74621
74622 #ifndef SQLITE_OMIT_VIEW
74623 /*
74624 ** Clear the column names from every VIEW in database idx.
74625 */
74626 static void sqliteViewResetAll(sqlite3 *db, int idx){
74627   HashElem *i;
74628   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
74629   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
74630     Table *pTab = sqliteHashData(i);
74631     if( pTab->pSelect ){
74632       sqliteResetColumnNames(pTab);
74633     }
74634   }
74635   DbClearProperty(db, idx, DB_UnresetViews);
74636 }
74637 #else
74638 # define sqliteViewResetAll(A,B)
74639 #endif /* SQLITE_OMIT_VIEW */
74640
74641 /*
74642 ** This function is called by the VDBE to adjust the internal schema
74643 ** used by SQLite when the btree layer moves a table root page. The
74644 ** root-page of a table or index in database iDb has changed from iFrom
74645 ** to iTo.
74646 **
74647 ** Ticket #1728:  The symbol table might still contain information
74648 ** on tables and/or indices that are the process of being deleted.
74649 ** If you are unlucky, one of those deleted indices or tables might
74650 ** have the same rootpage number as the real table or index that is
74651 ** being moved.  So we cannot stop searching after the first match 
74652 ** because the first match might be for one of the deleted indices
74653 ** or tables and not the table/index that is actually being moved.
74654 ** We must continue looping until all tables and indices with
74655 ** rootpage==iFrom have been converted to have a rootpage of iTo
74656 ** in order to be certain that we got the right one.
74657 */
74658 #ifndef SQLITE_OMIT_AUTOVACUUM
74659 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
74660   HashElem *pElem;
74661   Hash *pHash;
74662
74663   pHash = &pDb->pSchema->tblHash;
74664   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74665     Table *pTab = sqliteHashData(pElem);
74666     if( pTab->tnum==iFrom ){
74667       pTab->tnum = iTo;
74668     }
74669   }
74670   pHash = &pDb->pSchema->idxHash;
74671   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74672     Index *pIdx = sqliteHashData(pElem);
74673     if( pIdx->tnum==iFrom ){
74674       pIdx->tnum = iTo;
74675     }
74676   }
74677 }
74678 #endif
74679
74680 /*
74681 ** Write code to erase the table with root-page iTable from database iDb.
74682 ** Also write code to modify the sqlite_master table and internal schema
74683 ** if a root-page of another table is moved by the btree-layer whilst
74684 ** erasing iTable (this can happen with an auto-vacuum database).
74685 */ 
74686 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
74687   Vdbe *v = sqlite3GetVdbe(pParse);
74688   int r1 = sqlite3GetTempReg(pParse);
74689   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
74690   sqlite3MayAbort(pParse);
74691 #ifndef SQLITE_OMIT_AUTOVACUUM
74692   /* OP_Destroy stores an in integer r1. If this integer
74693   ** is non-zero, then it is the root page number of a table moved to
74694   ** location iTable. The following code modifies the sqlite_master table to
74695   ** reflect this.
74696   **
74697   ** The "#NNN" in the SQL is a special constant that means whatever value
74698   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
74699   ** token for additional information.
74700   */
74701   sqlite3NestedParse(pParse, 
74702      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
74703      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
74704 #endif
74705   sqlite3ReleaseTempReg(pParse, r1);
74706 }
74707
74708 /*
74709 ** Write VDBE code to erase table pTab and all associated indices on disk.
74710 ** Code to update the sqlite_master tables and internal schema definitions
74711 ** in case a root-page belonging to another table is moved by the btree layer
74712 ** is also added (this can happen with an auto-vacuum database).
74713 */
74714 static void destroyTable(Parse *pParse, Table *pTab){
74715 #ifdef SQLITE_OMIT_AUTOVACUUM
74716   Index *pIdx;
74717   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74718   destroyRootPage(pParse, pTab->tnum, iDb);
74719   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74720     destroyRootPage(pParse, pIdx->tnum, iDb);
74721   }
74722 #else
74723   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
74724   ** is not defined), then it is important to call OP_Destroy on the
74725   ** table and index root-pages in order, starting with the numerically 
74726   ** largest root-page number. This guarantees that none of the root-pages
74727   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
74728   ** following were coded:
74729   **
74730   ** OP_Destroy 4 0
74731   ** ...
74732   ** OP_Destroy 5 0
74733   **
74734   ** and root page 5 happened to be the largest root-page number in the
74735   ** database, then root page 5 would be moved to page 4 by the 
74736   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
74737   ** a free-list page.
74738   */
74739   int iTab = pTab->tnum;
74740   int iDestroyed = 0;
74741
74742   while( 1 ){
74743     Index *pIdx;
74744     int iLargest = 0;
74745
74746     if( iDestroyed==0 || iTab<iDestroyed ){
74747       iLargest = iTab;
74748     }
74749     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74750       int iIdx = pIdx->tnum;
74751       assert( pIdx->pSchema==pTab->pSchema );
74752       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
74753         iLargest = iIdx;
74754       }
74755     }
74756     if( iLargest==0 ){
74757       return;
74758     }else{
74759       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74760       destroyRootPage(pParse, iLargest, iDb);
74761       iDestroyed = iLargest;
74762     }
74763   }
74764 #endif
74765 }
74766
74767 /*
74768 ** This routine is called to do the work of a DROP TABLE statement.
74769 ** pName is the name of the table to be dropped.
74770 */
74771 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
74772   Table *pTab;
74773   Vdbe *v;
74774   sqlite3 *db = pParse->db;
74775   int iDb;
74776
74777   if( db->mallocFailed ){
74778     goto exit_drop_table;
74779   }
74780   assert( pParse->nErr==0 );
74781   assert( pName->nSrc==1 );
74782   if( noErr ) db->suppressErr++;
74783   pTab = sqlite3LocateTable(pParse, isView, 
74784                             pName->a[0].zName, pName->a[0].zDatabase);
74785   if( noErr ) db->suppressErr--;
74786
74787   if( pTab==0 ){
74788     goto exit_drop_table;
74789   }
74790   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74791   assert( iDb>=0 && iDb<db->nDb );
74792
74793   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
74794   ** it is initialized.
74795   */
74796   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
74797     goto exit_drop_table;
74798   }
74799 #ifndef SQLITE_OMIT_AUTHORIZATION
74800   {
74801     int code;
74802     const char *zTab = SCHEMA_TABLE(iDb);
74803     const char *zDb = db->aDb[iDb].zName;
74804     const char *zArg2 = 0;
74805     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
74806       goto exit_drop_table;
74807     }
74808     if( isView ){
74809       if( !OMIT_TEMPDB && iDb==1 ){
74810         code = SQLITE_DROP_TEMP_VIEW;
74811       }else{
74812         code = SQLITE_DROP_VIEW;
74813       }
74814 #ifndef SQLITE_OMIT_VIRTUALTABLE
74815     }else if( IsVirtual(pTab) ){
74816       code = SQLITE_DROP_VTABLE;
74817       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
74818 #endif
74819     }else{
74820       if( !OMIT_TEMPDB && iDb==1 ){
74821         code = SQLITE_DROP_TEMP_TABLE;
74822       }else{
74823         code = SQLITE_DROP_TABLE;
74824       }
74825     }
74826     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
74827       goto exit_drop_table;
74828     }
74829     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
74830       goto exit_drop_table;
74831     }
74832   }
74833 #endif
74834   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
74835     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
74836     goto exit_drop_table;
74837   }
74838
74839 #ifndef SQLITE_OMIT_VIEW
74840   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
74841   ** on a table.
74842   */
74843   if( isView && pTab->pSelect==0 ){
74844     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
74845     goto exit_drop_table;
74846   }
74847   if( !isView && pTab->pSelect ){
74848     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
74849     goto exit_drop_table;
74850   }
74851 #endif
74852
74853   /* Generate code to remove the table from the master table
74854   ** on disk.
74855   */
74856   v = sqlite3GetVdbe(pParse);
74857   if( v ){
74858     Trigger *pTrigger;
74859     Db *pDb = &db->aDb[iDb];
74860     sqlite3BeginWriteOperation(pParse, 1, iDb);
74861
74862 #ifndef SQLITE_OMIT_VIRTUALTABLE
74863     if( IsVirtual(pTab) ){
74864       sqlite3VdbeAddOp0(v, OP_VBegin);
74865     }
74866 #endif
74867     sqlite3FkDropTable(pParse, pName, pTab);
74868
74869     /* Drop all triggers associated with the table being dropped. Code
74870     ** is generated to remove entries from sqlite_master and/or
74871     ** sqlite_temp_master if required.
74872     */
74873     pTrigger = sqlite3TriggerList(pParse, pTab);
74874     while( pTrigger ){
74875       assert( pTrigger->pSchema==pTab->pSchema || 
74876           pTrigger->pSchema==db->aDb[1].pSchema );
74877       sqlite3DropTriggerPtr(pParse, pTrigger);
74878       pTrigger = pTrigger->pNext;
74879     }
74880
74881 #ifndef SQLITE_OMIT_AUTOINCREMENT
74882     /* Remove any entries of the sqlite_sequence table associated with
74883     ** the table being dropped. This is done before the table is dropped
74884     ** at the btree level, in case the sqlite_sequence table needs to
74885     ** move as a result of the drop (can happen in auto-vacuum mode).
74886     */
74887     if( pTab->tabFlags & TF_Autoincrement ){
74888       sqlite3NestedParse(pParse,
74889         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
74890         pDb->zName, pTab->zName
74891       );
74892     }
74893 #endif
74894
74895     /* Drop all SQLITE_MASTER table and index entries that refer to the
74896     ** table. The program name loops through the master table and deletes
74897     ** every row that refers to a table of the same name as the one being
74898     ** dropped. Triggers are handled seperately because a trigger can be
74899     ** created in the temp database that refers to a table in another
74900     ** database.
74901     */
74902     sqlite3NestedParse(pParse, 
74903         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
74904         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
74905
74906     /* Drop any statistics from the sqlite_stat1 table, if it exists */
74907     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
74908       sqlite3NestedParse(pParse,
74909         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
74910       );
74911     }
74912
74913     if( !isView && !IsVirtual(pTab) ){
74914       destroyTable(pParse, pTab);
74915     }
74916
74917     /* Remove the table entry from SQLite's internal schema and modify
74918     ** the schema cookie.
74919     */
74920     if( IsVirtual(pTab) ){
74921       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
74922     }
74923     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74924     sqlite3ChangeCookie(pParse, iDb);
74925   }
74926   sqliteViewResetAll(db, iDb);
74927
74928 exit_drop_table:
74929   sqlite3SrcListDelete(db, pName);
74930 }
74931
74932 /*
74933 ** This routine is called to create a new foreign key on the table
74934 ** currently under construction.  pFromCol determines which columns
74935 ** in the current table point to the foreign key.  If pFromCol==0 then
74936 ** connect the key to the last column inserted.  pTo is the name of
74937 ** the table referred to.  pToCol is a list of tables in the other
74938 ** pTo table that the foreign key points to.  flags contains all
74939 ** information about the conflict resolution algorithms specified
74940 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
74941 **
74942 ** An FKey structure is created and added to the table currently
74943 ** under construction in the pParse->pNewTable field.
74944 **
74945 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
74946 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
74947 */
74948 SQLITE_PRIVATE void sqlite3CreateForeignKey(
74949   Parse *pParse,       /* Parsing context */
74950   ExprList *pFromCol,  /* Columns in this table that point to other table */
74951   Token *pTo,          /* Name of the other table */
74952   ExprList *pToCol,    /* Columns in the other table */
74953   int flags            /* Conflict resolution algorithms. */
74954 ){
74955   sqlite3 *db = pParse->db;
74956 #ifndef SQLITE_OMIT_FOREIGN_KEY
74957   FKey *pFKey = 0;
74958   FKey *pNextTo;
74959   Table *p = pParse->pNewTable;
74960   int nByte;
74961   int i;
74962   int nCol;
74963   char *z;
74964
74965   assert( pTo!=0 );
74966   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
74967   if( pFromCol==0 ){
74968     int iCol = p->nCol-1;
74969     if( NEVER(iCol<0) ) goto fk_end;
74970     if( pToCol && pToCol->nExpr!=1 ){
74971       sqlite3ErrorMsg(pParse, "foreign key on %s"
74972          " should reference only one column of table %T",
74973          p->aCol[iCol].zName, pTo);
74974       goto fk_end;
74975     }
74976     nCol = 1;
74977   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
74978     sqlite3ErrorMsg(pParse,
74979         "number of columns in foreign key does not match the number of "
74980         "columns in the referenced table");
74981     goto fk_end;
74982   }else{
74983     nCol = pFromCol->nExpr;
74984   }
74985   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
74986   if( pToCol ){
74987     for(i=0; i<pToCol->nExpr; i++){
74988       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
74989     }
74990   }
74991   pFKey = sqlite3DbMallocZero(db, nByte );
74992   if( pFKey==0 ){
74993     goto fk_end;
74994   }
74995   pFKey->pFrom = p;
74996   pFKey->pNextFrom = p->pFKey;
74997   z = (char*)&pFKey->aCol[nCol];
74998   pFKey->zTo = z;
74999   memcpy(z, pTo->z, pTo->n);
75000   z[pTo->n] = 0;
75001   sqlite3Dequote(z);
75002   z += pTo->n+1;
75003   pFKey->nCol = nCol;
75004   if( pFromCol==0 ){
75005     pFKey->aCol[0].iFrom = p->nCol-1;
75006   }else{
75007     for(i=0; i<nCol; i++){
75008       int j;
75009       for(j=0; j<p->nCol; j++){
75010         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
75011           pFKey->aCol[i].iFrom = j;
75012           break;
75013         }
75014       }
75015       if( j>=p->nCol ){
75016         sqlite3ErrorMsg(pParse, 
75017           "unknown column \"%s\" in foreign key definition", 
75018           pFromCol->a[i].zName);
75019         goto fk_end;
75020       }
75021     }
75022   }
75023   if( pToCol ){
75024     for(i=0; i<nCol; i++){
75025       int n = sqlite3Strlen30(pToCol->a[i].zName);
75026       pFKey->aCol[i].zCol = z;
75027       memcpy(z, pToCol->a[i].zName, n);
75028       z[n] = 0;
75029       z += n+1;
75030     }
75031   }
75032   pFKey->isDeferred = 0;
75033   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
75034   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
75035
75036   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
75037       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
75038   );
75039   if( pNextTo==pFKey ){
75040     db->mallocFailed = 1;
75041     goto fk_end;
75042   }
75043   if( pNextTo ){
75044     assert( pNextTo->pPrevTo==0 );
75045     pFKey->pNextTo = pNextTo;
75046     pNextTo->pPrevTo = pFKey;
75047   }
75048
75049   /* Link the foreign key to the table as the last step.
75050   */
75051   p->pFKey = pFKey;
75052   pFKey = 0;
75053
75054 fk_end:
75055   sqlite3DbFree(db, pFKey);
75056 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
75057   sqlite3ExprListDelete(db, pFromCol);
75058   sqlite3ExprListDelete(db, pToCol);
75059 }
75060
75061 /*
75062 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
75063 ** clause is seen as part of a foreign key definition.  The isDeferred
75064 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
75065 ** The behavior of the most recently created foreign key is adjusted
75066 ** accordingly.
75067 */
75068 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
75069 #ifndef SQLITE_OMIT_FOREIGN_KEY
75070   Table *pTab;
75071   FKey *pFKey;
75072   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
75073   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
75074   pFKey->isDeferred = (u8)isDeferred;
75075 #endif
75076 }
75077
75078 /*
75079 ** Generate code that will erase and refill index *pIdx.  This is
75080 ** used to initialize a newly created index or to recompute the
75081 ** content of an index in response to a REINDEX command.
75082 **
75083 ** if memRootPage is not negative, it means that the index is newly
75084 ** created.  The register specified by memRootPage contains the
75085 ** root page number of the index.  If memRootPage is negative, then
75086 ** the index already exists and must be cleared before being refilled and
75087 ** the root page number of the index is taken from pIndex->tnum.
75088 */
75089 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
75090   Table *pTab = pIndex->pTable;  /* The table that is indexed */
75091   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
75092   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
75093   int addr1;                     /* Address of top of loop */
75094   int tnum;                      /* Root page of index */
75095   Vdbe *v;                       /* Generate code into this virtual machine */
75096   KeyInfo *pKey;                 /* KeyInfo for index */
75097   int regIdxKey;                 /* Registers containing the index key */
75098   int regRecord;                 /* Register holding assemblied index record */
75099   sqlite3 *db = pParse->db;      /* The database connection */
75100   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
75101
75102 #ifndef SQLITE_OMIT_AUTHORIZATION
75103   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
75104       db->aDb[iDb].zName ) ){
75105     return;
75106   }
75107 #endif
75108
75109   /* Require a write-lock on the table to perform this operation */
75110   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
75111
75112   v = sqlite3GetVdbe(pParse);
75113   if( v==0 ) return;
75114   if( memRootPage>=0 ){
75115     tnum = memRootPage;
75116   }else{
75117     tnum = pIndex->tnum;
75118     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
75119   }
75120   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
75121   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
75122                     (char *)pKey, P4_KEYINFO_HANDOFF);
75123   if( memRootPage>=0 ){
75124     sqlite3VdbeChangeP5(v, 1);
75125   }
75126   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75127   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
75128   regRecord = sqlite3GetTempReg(pParse);
75129   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
75130   if( pIndex->onError!=OE_None ){
75131     const int regRowid = regIdxKey + pIndex->nColumn;
75132     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
75133     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
75134
75135     /* The registers accessed by the OP_IsUnique opcode were allocated
75136     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
75137     ** call above. Just before that function was freed they were released
75138     ** (made available to the compiler for reuse) using 
75139     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
75140     ** opcode use the values stored within seems dangerous. However, since
75141     ** we can be sure that no other temp registers have been allocated
75142     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
75143     */
75144     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
75145     sqlite3HaltConstraint(
75146         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
75147   }
75148   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
75149   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75150   sqlite3ReleaseTempReg(pParse, regRecord);
75151   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
75152   sqlite3VdbeJumpHere(v, addr1);
75153   sqlite3VdbeAddOp1(v, OP_Close, iTab);
75154   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
75155 }
75156
75157 /*
75158 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
75159 ** and pTblList is the name of the table that is to be indexed.  Both will 
75160 ** be NULL for a primary key or an index that is created to satisfy a
75161 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
75162 ** as the table to be indexed.  pParse->pNewTable is a table that is
75163 ** currently being constructed by a CREATE TABLE statement.
75164 **
75165 ** pList is a list of columns to be indexed.  pList will be NULL if this
75166 ** is a primary key or unique-constraint on the most recent column added
75167 ** to the table currently under construction.  
75168 **
75169 ** If the index is created successfully, return a pointer to the new Index
75170 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
75171 ** as the tables primary key (Index.autoIndex==2).
75172 */
75173 SQLITE_PRIVATE Index *sqlite3CreateIndex(
75174   Parse *pParse,     /* All information about this parse */
75175   Token *pName1,     /* First part of index name. May be NULL */
75176   Token *pName2,     /* Second part of index name. May be NULL */
75177   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
75178   ExprList *pList,   /* A list of columns to be indexed */
75179   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
75180   Token *pStart,     /* The CREATE token that begins this statement */
75181   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
75182   int sortOrder,     /* Sort order of primary key when pList==NULL */
75183   int ifNotExist     /* Omit error if index already exists */
75184 ){
75185   Index *pRet = 0;     /* Pointer to return */
75186   Table *pTab = 0;     /* Table to be indexed */
75187   Index *pIndex = 0;   /* The index to be created */
75188   char *zName = 0;     /* Name of the index */
75189   int nName;           /* Number of characters in zName */
75190   int i, j;
75191   Token nullId;        /* Fake token for an empty ID list */
75192   DbFixer sFix;        /* For assigning database names to pTable */
75193   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
75194   sqlite3 *db = pParse->db;
75195   Db *pDb;             /* The specific table containing the indexed database */
75196   int iDb;             /* Index of the database that is being written */
75197   Token *pName = 0;    /* Unqualified name of the index to create */
75198   struct ExprList_item *pListItem; /* For looping over pList */
75199   int nCol;
75200   int nExtra = 0;
75201   char *zExtra;
75202
75203   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
75204   assert( pParse->nErr==0 );      /* Never called with prior errors */
75205   if( db->mallocFailed || IN_DECLARE_VTAB ){
75206     goto exit_create_index;
75207   }
75208   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75209     goto exit_create_index;
75210   }
75211
75212   /*
75213   ** Find the table that is to be indexed.  Return early if not found.
75214   */
75215   if( pTblName!=0 ){
75216
75217     /* Use the two-part index name to determine the database 
75218     ** to search for the table. 'Fix' the table name to this db
75219     ** before looking up the table.
75220     */
75221     assert( pName1 && pName2 );
75222     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75223     if( iDb<0 ) goto exit_create_index;
75224
75225 #ifndef SQLITE_OMIT_TEMPDB
75226     /* If the index name was unqualified, check if the the table
75227     ** is a temp table. If so, set the database to 1. Do not do this
75228     ** if initialising a database schema.
75229     */
75230     if( !db->init.busy ){
75231       pTab = sqlite3SrcListLookup(pParse, pTblName);
75232       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
75233         iDb = 1;
75234       }
75235     }
75236 #endif
75237
75238     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
75239         sqlite3FixSrcList(&sFix, pTblName)
75240     ){
75241       /* Because the parser constructs pTblName from a single identifier,
75242       ** sqlite3FixSrcList can never fail. */
75243       assert(0);
75244     }
75245     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
75246         pTblName->a[0].zDatabase);
75247     if( !pTab || db->mallocFailed ) goto exit_create_index;
75248     assert( db->aDb[iDb].pSchema==pTab->pSchema );
75249   }else{
75250     assert( pName==0 );
75251     pTab = pParse->pNewTable;
75252     if( !pTab ) goto exit_create_index;
75253     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75254   }
75255   pDb = &db->aDb[iDb];
75256
75257   assert( pTab!=0 );
75258   assert( pParse->nErr==0 );
75259   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
75260        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
75261     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
75262     goto exit_create_index;
75263   }
75264 #ifndef SQLITE_OMIT_VIEW
75265   if( pTab->pSelect ){
75266     sqlite3ErrorMsg(pParse, "views may not be indexed");
75267     goto exit_create_index;
75268   }
75269 #endif
75270 #ifndef SQLITE_OMIT_VIRTUALTABLE
75271   if( IsVirtual(pTab) ){
75272     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
75273     goto exit_create_index;
75274   }
75275 #endif
75276
75277   /*
75278   ** Find the name of the index.  Make sure there is not already another
75279   ** index or table with the same name.  
75280   **
75281   ** Exception:  If we are reading the names of permanent indices from the
75282   ** sqlite_master table (because some other process changed the schema) and
75283   ** one of the index names collides with the name of a temporary table or
75284   ** index, then we will continue to process this index.
75285   **
75286   ** If pName==0 it means that we are
75287   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
75288   ** own name.
75289   */
75290   if( pName ){
75291     zName = sqlite3NameFromToken(db, pName);
75292     if( zName==0 ) goto exit_create_index;
75293     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
75294       goto exit_create_index;
75295     }
75296     if( !db->init.busy ){
75297       if( sqlite3FindTable(db, zName, 0)!=0 ){
75298         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
75299         goto exit_create_index;
75300       }
75301     }
75302     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
75303       if( !ifNotExist ){
75304         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
75305       }
75306       goto exit_create_index;
75307     }
75308   }else{
75309     int n;
75310     Index *pLoop;
75311     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
75312     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
75313     if( zName==0 ){
75314       goto exit_create_index;
75315     }
75316   }
75317
75318   /* Check for authorization to create an index.
75319   */
75320 #ifndef SQLITE_OMIT_AUTHORIZATION
75321   {
75322     const char *zDb = pDb->zName;
75323     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
75324       goto exit_create_index;
75325     }
75326     i = SQLITE_CREATE_INDEX;
75327     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
75328     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
75329       goto exit_create_index;
75330     }
75331   }
75332 #endif
75333
75334   /* If pList==0, it means this routine was called to make a primary
75335   ** key out of the last column added to the table under construction.
75336   ** So create a fake list to simulate this.
75337   */
75338   if( pList==0 ){
75339     nullId.z = pTab->aCol[pTab->nCol-1].zName;
75340     nullId.n = sqlite3Strlen30((char*)nullId.z);
75341     pList = sqlite3ExprListAppend(pParse, 0, 0);
75342     if( pList==0 ) goto exit_create_index;
75343     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
75344     pList->a[0].sortOrder = (u8)sortOrder;
75345   }
75346
75347   /* Figure out how many bytes of space are required to store explicitly
75348   ** specified collation sequence names.
75349   */
75350   for(i=0; i<pList->nExpr; i++){
75351     Expr *pExpr = pList->a[i].pExpr;
75352     if( pExpr ){
75353       CollSeq *pColl = pExpr->pColl;
75354       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
75355       ** failure we have quit before reaching this point. */
75356       if( ALWAYS(pColl) ){
75357         nExtra += (1 + sqlite3Strlen30(pColl->zName));
75358       }
75359     }
75360   }
75361
75362   /* 
75363   ** Allocate the index structure. 
75364   */
75365   nName = sqlite3Strlen30(zName);
75366   nCol = pList->nExpr;
75367   pIndex = sqlite3DbMallocZero(db, 
75368       sizeof(Index) +              /* Index structure  */
75369       sizeof(int)*nCol +           /* Index.aiColumn   */
75370       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
75371       sizeof(char *)*nCol +        /* Index.azColl     */
75372       sizeof(u8)*nCol +            /* Index.aSortOrder */
75373       nName + 1 +                  /* Index.zName      */
75374       nExtra                       /* Collation sequence names */
75375   );
75376   if( db->mallocFailed ){
75377     goto exit_create_index;
75378   }
75379   pIndex->azColl = (char**)(&pIndex[1]);
75380   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
75381   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
75382   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
75383   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
75384   zExtra = (char *)(&pIndex->zName[nName+1]);
75385   memcpy(pIndex->zName, zName, nName+1);
75386   pIndex->pTable = pTab;
75387   pIndex->nColumn = pList->nExpr;
75388   pIndex->onError = (u8)onError;
75389   pIndex->autoIndex = (u8)(pName==0);
75390   pIndex->pSchema = db->aDb[iDb].pSchema;
75391
75392   /* Check to see if we should honor DESC requests on index columns
75393   */
75394   if( pDb->pSchema->file_format>=4 ){
75395     sortOrderMask = -1;   /* Honor DESC */
75396   }else{
75397     sortOrderMask = 0;    /* Ignore DESC */
75398   }
75399
75400   /* Scan the names of the columns of the table to be indexed and
75401   ** load the column indices into the Index structure.  Report an error
75402   ** if any column is not found.
75403   **
75404   ** TODO:  Add a test to make sure that the same column is not named
75405   ** more than once within the same index.  Only the first instance of
75406   ** the column will ever be used by the optimizer.  Note that using the
75407   ** same column more than once cannot be an error because that would 
75408   ** break backwards compatibility - it needs to be a warning.
75409   */
75410   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
75411     const char *zColName = pListItem->zName;
75412     Column *pTabCol;
75413     int requestedSortOrder;
75414     char *zColl;                   /* Collation sequence name */
75415
75416     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
75417       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
75418     }
75419     if( j>=pTab->nCol ){
75420       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
75421         pTab->zName, zColName);
75422       pParse->checkSchema = 1;
75423       goto exit_create_index;
75424     }
75425     pIndex->aiColumn[i] = j;
75426     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
75427     ** the way the "idxlist" non-terminal is constructed by the parser,
75428     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
75429     ** must exist or else there must have been an OOM error.  But if there
75430     ** was an OOM error, we would never reach this point. */
75431     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
75432       int nColl;
75433       zColl = pListItem->pExpr->pColl->zName;
75434       nColl = sqlite3Strlen30(zColl) + 1;
75435       assert( nExtra>=nColl );
75436       memcpy(zExtra, zColl, nColl);
75437       zColl = zExtra;
75438       zExtra += nColl;
75439       nExtra -= nColl;
75440     }else{
75441       zColl = pTab->aCol[j].zColl;
75442       if( !zColl ){
75443         zColl = db->pDfltColl->zName;
75444       }
75445     }
75446     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
75447       goto exit_create_index;
75448     }
75449     pIndex->azColl[i] = zColl;
75450     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
75451     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
75452   }
75453   sqlite3DefaultRowEst(pIndex);
75454
75455   if( pTab==pParse->pNewTable ){
75456     /* This routine has been called to create an automatic index as a
75457     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
75458     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
75459     ** i.e. one of:
75460     **
75461     ** CREATE TABLE t(x PRIMARY KEY, y);
75462     ** CREATE TABLE t(x, y, UNIQUE(x, y));
75463     **
75464     ** Either way, check to see if the table already has such an index. If
75465     ** so, don't bother creating this one. This only applies to
75466     ** automatically created indices. Users can do as they wish with
75467     ** explicit indices.
75468     **
75469     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
75470     ** (and thus suppressing the second one) even if they have different
75471     ** sort orders.
75472     **
75473     ** If there are different collating sequences or if the columns of
75474     ** the constraint occur in different orders, then the constraints are
75475     ** considered distinct and both result in separate indices.
75476     */
75477     Index *pIdx;
75478     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75479       int k;
75480       assert( pIdx->onError!=OE_None );
75481       assert( pIdx->autoIndex );
75482       assert( pIndex->onError!=OE_None );
75483
75484       if( pIdx->nColumn!=pIndex->nColumn ) continue;
75485       for(k=0; k<pIdx->nColumn; k++){
75486         const char *z1;
75487         const char *z2;
75488         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
75489         z1 = pIdx->azColl[k];
75490         z2 = pIndex->azColl[k];
75491         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
75492       }
75493       if( k==pIdx->nColumn ){
75494         if( pIdx->onError!=pIndex->onError ){
75495           /* This constraint creates the same index as a previous
75496           ** constraint specified somewhere in the CREATE TABLE statement.
75497           ** However the ON CONFLICT clauses are different. If both this 
75498           ** constraint and the previous equivalent constraint have explicit
75499           ** ON CONFLICT clauses this is an error. Otherwise, use the
75500           ** explicitly specified behaviour for the index.
75501           */
75502           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
75503             sqlite3ErrorMsg(pParse, 
75504                 "conflicting ON CONFLICT clauses specified", 0);
75505           }
75506           if( pIdx->onError==OE_Default ){
75507             pIdx->onError = pIndex->onError;
75508           }
75509         }
75510         goto exit_create_index;
75511       }
75512     }
75513   }
75514
75515   /* Link the new Index structure to its table and to the other
75516   ** in-memory database structures. 
75517   */
75518   if( db->init.busy ){
75519     Index *p;
75520     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
75521                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
75522                           pIndex);
75523     if( p ){
75524       assert( p==pIndex );  /* Malloc must have failed */
75525       db->mallocFailed = 1;
75526       goto exit_create_index;
75527     }
75528     db->flags |= SQLITE_InternChanges;
75529     if( pTblName!=0 ){
75530       pIndex->tnum = db->init.newTnum;
75531     }
75532   }
75533
75534   /* If the db->init.busy is 0 then create the index on disk.  This
75535   ** involves writing the index into the master table and filling in the
75536   ** index with the current table contents.
75537   **
75538   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
75539   ** command.  db->init.busy is 1 when a database is opened and 
75540   ** CREATE INDEX statements are read out of the master table.  In
75541   ** the latter case the index already exists on disk, which is why
75542   ** we don't want to recreate it.
75543   **
75544   ** If pTblName==0 it means this index is generated as a primary key
75545   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
75546   ** has just been created, it contains no data and the index initialization
75547   ** step can be skipped.
75548   */
75549   else{ /* if( db->init.busy==0 ) */
75550     Vdbe *v;
75551     char *zStmt;
75552     int iMem = ++pParse->nMem;
75553
75554     v = sqlite3GetVdbe(pParse);
75555     if( v==0 ) goto exit_create_index;
75556
75557
75558     /* Create the rootpage for the index
75559     */
75560     sqlite3BeginWriteOperation(pParse, 1, iDb);
75561     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
75562
75563     /* Gather the complete text of the CREATE INDEX statement into
75564     ** the zStmt variable
75565     */
75566     if( pStart ){
75567       assert( pEnd!=0 );
75568       /* A named index with an explicit CREATE INDEX statement */
75569       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
75570         onError==OE_None ? "" : " UNIQUE",
75571         pEnd->z - pName->z + 1,
75572         pName->z);
75573     }else{
75574       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
75575       /* zStmt = sqlite3MPrintf(""); */
75576       zStmt = 0;
75577     }
75578
75579     /* Add an entry in sqlite_master for this index
75580     */
75581     sqlite3NestedParse(pParse, 
75582         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
75583         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75584         pIndex->zName,
75585         pTab->zName,
75586         iMem,
75587         zStmt
75588     );
75589     sqlite3DbFree(db, zStmt);
75590
75591     /* Fill the index with data and reparse the schema. Code an OP_Expire
75592     ** to invalidate all pre-compiled statements.
75593     */
75594     if( pTblName ){
75595       sqlite3RefillIndex(pParse, pIndex, iMem);
75596       sqlite3ChangeCookie(pParse, iDb);
75597       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
75598          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
75599       sqlite3VdbeAddOp1(v, OP_Expire, 0);
75600     }
75601   }
75602
75603   /* When adding an index to the list of indices for a table, make
75604   ** sure all indices labeled OE_Replace come after all those labeled
75605   ** OE_Ignore.  This is necessary for the correct constraint check
75606   ** processing (in sqlite3GenerateConstraintChecks()) as part of
75607   ** UPDATE and INSERT statements.  
75608   */
75609   if( db->init.busy || pTblName==0 ){
75610     if( onError!=OE_Replace || pTab->pIndex==0
75611          || pTab->pIndex->onError==OE_Replace){
75612       pIndex->pNext = pTab->pIndex;
75613       pTab->pIndex = pIndex;
75614     }else{
75615       Index *pOther = pTab->pIndex;
75616       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
75617         pOther = pOther->pNext;
75618       }
75619       pIndex->pNext = pOther->pNext;
75620       pOther->pNext = pIndex;
75621     }
75622     pRet = pIndex;
75623     pIndex = 0;
75624   }
75625
75626   /* Clean up before exiting */
75627 exit_create_index:
75628   if( pIndex ){
75629     sqlite3_free(pIndex->zColAff);
75630     sqlite3DbFree(db, pIndex);
75631   }
75632   sqlite3ExprListDelete(db, pList);
75633   sqlite3SrcListDelete(db, pTblName);
75634   sqlite3DbFree(db, zName);
75635   return pRet;
75636 }
75637
75638 /*
75639 ** Fill the Index.aiRowEst[] array with default information - information
75640 ** to be used when we have not run the ANALYZE command.
75641 **
75642 ** aiRowEst[0] is suppose to contain the number of elements in the index.
75643 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
75644 ** number of rows in the table that match any particular value of the
75645 ** first column of the index.  aiRowEst[2] is an estimate of the number
75646 ** of rows that match any particular combiniation of the first 2 columns
75647 ** of the index.  And so forth.  It must always be the case that
75648 *
75649 **           aiRowEst[N]<=aiRowEst[N-1]
75650 **           aiRowEst[N]>=1
75651 **
75652 ** Apart from that, we have little to go on besides intuition as to
75653 ** how aiRowEst[] should be initialized.  The numbers generated here
75654 ** are based on typical values found in actual indices.
75655 */
75656 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
75657   unsigned *a = pIdx->aiRowEst;
75658   int i;
75659   assert( a!=0 );
75660   a[0] = 1000000;
75661   for(i=pIdx->nColumn; i>=5; i--){
75662     a[i] = 5;
75663   }
75664   while( i>=1 ){
75665     a[i] = 11 - i;
75666     i--;
75667   }
75668   if( pIdx->onError!=OE_None ){
75669     a[pIdx->nColumn] = 1;
75670   }
75671 }
75672
75673 /*
75674 ** This routine will drop an existing named index.  This routine
75675 ** implements the DROP INDEX statement.
75676 */
75677 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
75678   Index *pIndex;
75679   Vdbe *v;
75680   sqlite3 *db = pParse->db;
75681   int iDb;
75682
75683   assert( pParse->nErr==0 );   /* Never called with prior errors */
75684   if( db->mallocFailed ){
75685     goto exit_drop_index;
75686   }
75687   assert( pName->nSrc==1 );
75688   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75689     goto exit_drop_index;
75690   }
75691   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
75692   if( pIndex==0 ){
75693     if( !ifExists ){
75694       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
75695     }
75696     pParse->checkSchema = 1;
75697     goto exit_drop_index;
75698   }
75699   if( pIndex->autoIndex ){
75700     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
75701       "or PRIMARY KEY constraint cannot be dropped", 0);
75702     goto exit_drop_index;
75703   }
75704   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
75705 #ifndef SQLITE_OMIT_AUTHORIZATION
75706   {
75707     int code = SQLITE_DROP_INDEX;
75708     Table *pTab = pIndex->pTable;
75709     const char *zDb = db->aDb[iDb].zName;
75710     const char *zTab = SCHEMA_TABLE(iDb);
75711     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
75712       goto exit_drop_index;
75713     }
75714     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
75715     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
75716       goto exit_drop_index;
75717     }
75718   }
75719 #endif
75720
75721   /* Generate code to remove the index and from the master table */
75722   v = sqlite3GetVdbe(pParse);
75723   if( v ){
75724     sqlite3BeginWriteOperation(pParse, 1, iDb);
75725     sqlite3NestedParse(pParse,
75726        "DELETE FROM %Q.%s WHERE name=%Q",
75727        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75728        pIndex->zName
75729     );
75730     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
75731       sqlite3NestedParse(pParse,
75732         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
75733         db->aDb[iDb].zName, pIndex->zName
75734       );
75735     }
75736     sqlite3ChangeCookie(pParse, iDb);
75737     destroyRootPage(pParse, pIndex->tnum, iDb);
75738     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
75739   }
75740
75741 exit_drop_index:
75742   sqlite3SrcListDelete(db, pName);
75743 }
75744
75745 /*
75746 ** pArray is a pointer to an array of objects.  Each object in the
75747 ** array is szEntry bytes in size.  This routine allocates a new
75748 ** object on the end of the array.
75749 **
75750 ** *pnEntry is the number of entries already in use.  *pnAlloc is
75751 ** the previously allocated size of the array.  initSize is the
75752 ** suggested initial array size allocation.
75753 **
75754 ** The index of the new entry is returned in *pIdx.
75755 **
75756 ** This routine returns a pointer to the array of objects.  This
75757 ** might be the same as the pArray parameter or it might be a different
75758 ** pointer if the array was resized.
75759 */
75760 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
75761   sqlite3 *db,      /* Connection to notify of malloc failures */
75762   void *pArray,     /* Array of objects.  Might be reallocated */
75763   int szEntry,      /* Size of each object in the array */
75764   int initSize,     /* Suggested initial allocation, in elements */
75765   int *pnEntry,     /* Number of objects currently in use */
75766   int *pnAlloc,     /* Current size of the allocation, in elements */
75767   int *pIdx         /* Write the index of a new slot here */
75768 ){
75769   char *z;
75770   if( *pnEntry >= *pnAlloc ){
75771     void *pNew;
75772     int newSize;
75773     newSize = (*pnAlloc)*2 + initSize;
75774     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
75775     if( pNew==0 ){
75776       *pIdx = -1;
75777       return pArray;
75778     }
75779     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
75780     pArray = pNew;
75781   }
75782   z = (char*)pArray;
75783   memset(&z[*pnEntry * szEntry], 0, szEntry);
75784   *pIdx = *pnEntry;
75785   ++*pnEntry;
75786   return pArray;
75787 }
75788
75789 /*
75790 ** Append a new element to the given IdList.  Create a new IdList if
75791 ** need be.
75792 **
75793 ** A new IdList is returned, or NULL if malloc() fails.
75794 */
75795 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
75796   int i;
75797   if( pList==0 ){
75798     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
75799     if( pList==0 ) return 0;
75800     pList->nAlloc = 0;
75801   }
75802   pList->a = sqlite3ArrayAllocate(
75803       db,
75804       pList->a,
75805       sizeof(pList->a[0]),
75806       5,
75807       &pList->nId,
75808       &pList->nAlloc,
75809       &i
75810   );
75811   if( i<0 ){
75812     sqlite3IdListDelete(db, pList);
75813     return 0;
75814   }
75815   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
75816   return pList;
75817 }
75818
75819 /*
75820 ** Delete an IdList.
75821 */
75822 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
75823   int i;
75824   if( pList==0 ) return;
75825   for(i=0; i<pList->nId; i++){
75826     sqlite3DbFree(db, pList->a[i].zName);
75827   }
75828   sqlite3DbFree(db, pList->a);
75829   sqlite3DbFree(db, pList);
75830 }
75831
75832 /*
75833 ** Return the index in pList of the identifier named zId.  Return -1
75834 ** if not found.
75835 */
75836 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
75837   int i;
75838   if( pList==0 ) return -1;
75839   for(i=0; i<pList->nId; i++){
75840     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
75841   }
75842   return -1;
75843 }
75844
75845 /*
75846 ** Expand the space allocated for the given SrcList object by
75847 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
75848 ** New slots are zeroed.
75849 **
75850 ** For example, suppose a SrcList initially contains two entries: A,B.
75851 ** To append 3 new entries onto the end, do this:
75852 **
75853 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
75854 **
75855 ** After the call above it would contain:  A, B, nil, nil, nil.
75856 ** If the iStart argument had been 1 instead of 2, then the result
75857 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
75858 ** the iStart value would be 0.  The result then would
75859 ** be: nil, nil, nil, A, B.
75860 **
75861 ** If a memory allocation fails the SrcList is unchanged.  The
75862 ** db->mallocFailed flag will be set to true.
75863 */
75864 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
75865   sqlite3 *db,       /* Database connection to notify of OOM errors */
75866   SrcList *pSrc,     /* The SrcList to be enlarged */
75867   int nExtra,        /* Number of new slots to add to pSrc->a[] */
75868   int iStart         /* Index in pSrc->a[] of first new slot */
75869 ){
75870   int i;
75871
75872   /* Sanity checking on calling parameters */
75873   assert( iStart>=0 );
75874   assert( nExtra>=1 );
75875   assert( pSrc!=0 );
75876   assert( iStart<=pSrc->nSrc );
75877
75878   /* Allocate additional space if needed */
75879   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
75880     SrcList *pNew;
75881     int nAlloc = pSrc->nSrc+nExtra;
75882     int nGot;
75883     pNew = sqlite3DbRealloc(db, pSrc,
75884                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
75885     if( pNew==0 ){
75886       assert( db->mallocFailed );
75887       return pSrc;
75888     }
75889     pSrc = pNew;
75890     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
75891     pSrc->nAlloc = (u16)nGot;
75892   }
75893
75894   /* Move existing slots that come after the newly inserted slots
75895   ** out of the way */
75896   for(i=pSrc->nSrc-1; i>=iStart; i--){
75897     pSrc->a[i+nExtra] = pSrc->a[i];
75898   }
75899   pSrc->nSrc += (i16)nExtra;
75900
75901   /* Zero the newly allocated slots */
75902   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
75903   for(i=iStart; i<iStart+nExtra; i++){
75904     pSrc->a[i].iCursor = -1;
75905   }
75906
75907   /* Return a pointer to the enlarged SrcList */
75908   return pSrc;
75909 }
75910
75911
75912 /*
75913 ** Append a new table name to the given SrcList.  Create a new SrcList if
75914 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
75915 **
75916 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
75917 ** SrcList might be the same as the SrcList that was input or it might be
75918 ** a new one.  If an OOM error does occurs, then the prior value of pList
75919 ** that is input to this routine is automatically freed.
75920 **
75921 ** If pDatabase is not null, it means that the table has an optional
75922 ** database name prefix.  Like this:  "database.table".  The pDatabase
75923 ** points to the table name and the pTable points to the database name.
75924 ** The SrcList.a[].zName field is filled with the table name which might
75925 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
75926 ** SrcList.a[].zDatabase is filled with the database name from pTable,
75927 ** or with NULL if no database is specified.
75928 **
75929 ** In other words, if call like this:
75930 **
75931 **         sqlite3SrcListAppend(D,A,B,0);
75932 **
75933 ** Then B is a table name and the database name is unspecified.  If called
75934 ** like this:
75935 **
75936 **         sqlite3SrcListAppend(D,A,B,C);
75937 **
75938 ** Then C is the table name and B is the database name.  If C is defined
75939 ** then so is B.  In other words, we never have a case where:
75940 **
75941 **         sqlite3SrcListAppend(D,A,0,C);
75942 **
75943 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
75944 ** before being added to the SrcList.
75945 */
75946 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
75947   sqlite3 *db,        /* Connection to notify of malloc failures */
75948   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
75949   Token *pTable,      /* Table to append */
75950   Token *pDatabase    /* Database of the table */
75951 ){
75952   struct SrcList_item *pItem;
75953   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
75954   if( pList==0 ){
75955     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
75956     if( pList==0 ) return 0;
75957     pList->nAlloc = 1;
75958   }
75959   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
75960   if( db->mallocFailed ){
75961     sqlite3SrcListDelete(db, pList);
75962     return 0;
75963   }
75964   pItem = &pList->a[pList->nSrc-1];
75965   if( pDatabase && pDatabase->z==0 ){
75966     pDatabase = 0;
75967   }
75968   if( pDatabase ){
75969     Token *pTemp = pDatabase;
75970     pDatabase = pTable;
75971     pTable = pTemp;
75972   }
75973   pItem->zName = sqlite3NameFromToken(db, pTable);
75974   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
75975   return pList;
75976 }
75977
75978 /*
75979 ** Assign VdbeCursor index numbers to all tables in a SrcList
75980 */
75981 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
75982   int i;
75983   struct SrcList_item *pItem;
75984   assert(pList || pParse->db->mallocFailed );
75985   if( pList ){
75986     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
75987       if( pItem->iCursor>=0 ) break;
75988       pItem->iCursor = pParse->nTab++;
75989       if( pItem->pSelect ){
75990         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
75991       }
75992     }
75993   }
75994 }
75995
75996 /*
75997 ** Delete an entire SrcList including all its substructure.
75998 */
75999 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
76000   int i;
76001   struct SrcList_item *pItem;
76002   if( pList==0 ) return;
76003   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
76004     sqlite3DbFree(db, pItem->zDatabase);
76005     sqlite3DbFree(db, pItem->zName);
76006     sqlite3DbFree(db, pItem->zAlias);
76007     sqlite3DbFree(db, pItem->zIndex);
76008     sqlite3DeleteTable(pItem->pTab);
76009     sqlite3SelectDelete(db, pItem->pSelect);
76010     sqlite3ExprDelete(db, pItem->pOn);
76011     sqlite3IdListDelete(db, pItem->pUsing);
76012   }
76013   sqlite3DbFree(db, pList);
76014 }
76015
76016 /*
76017 ** This routine is called by the parser to add a new term to the
76018 ** end of a growing FROM clause.  The "p" parameter is the part of
76019 ** the FROM clause that has already been constructed.  "p" is NULL
76020 ** if this is the first term of the FROM clause.  pTable and pDatabase
76021 ** are the name of the table and database named in the FROM clause term.
76022 ** pDatabase is NULL if the database name qualifier is missing - the
76023 ** usual case.  If the term has a alias, then pAlias points to the
76024 ** alias token.  If the term is a subquery, then pSubquery is the
76025 ** SELECT statement that the subquery encodes.  The pTable and
76026 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
76027 ** parameters are the content of the ON and USING clauses.
76028 **
76029 ** Return a new SrcList which encodes is the FROM with the new
76030 ** term added.
76031 */
76032 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
76033   Parse *pParse,          /* Parsing context */
76034   SrcList *p,             /* The left part of the FROM clause already seen */
76035   Token *pTable,          /* Name of the table to add to the FROM clause */
76036   Token *pDatabase,       /* Name of the database containing pTable */
76037   Token *pAlias,          /* The right-hand side of the AS subexpression */
76038   Select *pSubquery,      /* A subquery used in place of a table name */
76039   Expr *pOn,              /* The ON clause of a join */
76040   IdList *pUsing          /* The USING clause of a join */
76041 ){
76042   struct SrcList_item *pItem;
76043   sqlite3 *db = pParse->db;
76044   if( !p && (pOn || pUsing) ){
76045     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
76046       (pOn ? "ON" : "USING")
76047     );
76048     goto append_from_error;
76049   }
76050   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
76051   if( p==0 || NEVER(p->nSrc==0) ){
76052     goto append_from_error;
76053   }
76054   pItem = &p->a[p->nSrc-1];
76055   assert( pAlias!=0 );
76056   if( pAlias->n ){
76057     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
76058   }
76059   pItem->pSelect = pSubquery;
76060   pItem->pOn = pOn;
76061   pItem->pUsing = pUsing;
76062   return p;
76063
76064  append_from_error:
76065   assert( p==0 );
76066   sqlite3ExprDelete(db, pOn);
76067   sqlite3IdListDelete(db, pUsing);
76068   sqlite3SelectDelete(db, pSubquery);
76069   return 0;
76070 }
76071
76072 /*
76073 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
76074 ** element of the source-list passed as the second argument.
76075 */
76076 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
76077   assert( pIndexedBy!=0 );
76078   if( p && ALWAYS(p->nSrc>0) ){
76079     struct SrcList_item *pItem = &p->a[p->nSrc-1];
76080     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
76081     if( pIndexedBy->n==1 && !pIndexedBy->z ){
76082       /* A "NOT INDEXED" clause was supplied. See parse.y 
76083       ** construct "indexed_opt" for details. */
76084       pItem->notIndexed = 1;
76085     }else{
76086       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
76087     }
76088   }
76089 }
76090
76091 /*
76092 ** When building up a FROM clause in the parser, the join operator
76093 ** is initially attached to the left operand.  But the code generator
76094 ** expects the join operator to be on the right operand.  This routine
76095 ** Shifts all join operators from left to right for an entire FROM
76096 ** clause.
76097 **
76098 ** Example: Suppose the join is like this:
76099 **
76100 **           A natural cross join B
76101 **
76102 ** The operator is "natural cross join".  The A and B operands are stored
76103 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
76104 ** operator with A.  This routine shifts that operator over to B.
76105 */
76106 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
76107   if( p && p->a ){
76108     int i;
76109     for(i=p->nSrc-1; i>0; i--){
76110       p->a[i].jointype = p->a[i-1].jointype;
76111     }
76112     p->a[0].jointype = 0;
76113   }
76114 }
76115
76116 /*
76117 ** Begin a transaction
76118 */
76119 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
76120   sqlite3 *db;
76121   Vdbe *v;
76122   int i;
76123
76124   assert( pParse!=0 );
76125   db = pParse->db;
76126   assert( db!=0 );
76127 /*  if( db->aDb[0].pBt==0 ) return; */
76128   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
76129     return;
76130   }
76131   v = sqlite3GetVdbe(pParse);
76132   if( !v ) return;
76133   if( type!=TK_DEFERRED ){
76134     for(i=0; i<db->nDb; i++){
76135       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
76136       sqlite3VdbeUsesBtree(v, i);
76137     }
76138   }
76139   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
76140 }
76141
76142 /*
76143 ** Commit a transaction
76144 */
76145 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
76146   sqlite3 *db;
76147   Vdbe *v;
76148
76149   assert( pParse!=0 );
76150   db = pParse->db;
76151   assert( db!=0 );
76152 /*  if( db->aDb[0].pBt==0 ) return; */
76153   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
76154     return;
76155   }
76156   v = sqlite3GetVdbe(pParse);
76157   if( v ){
76158     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
76159   }
76160 }
76161
76162 /*
76163 ** Rollback a transaction
76164 */
76165 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
76166   sqlite3 *db;
76167   Vdbe *v;
76168
76169   assert( pParse!=0 );
76170   db = pParse->db;
76171   assert( db!=0 );
76172 /*  if( db->aDb[0].pBt==0 ) return; */
76173   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
76174     return;
76175   }
76176   v = sqlite3GetVdbe(pParse);
76177   if( v ){
76178     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
76179   }
76180 }
76181
76182 /*
76183 ** This function is called by the parser when it parses a command to create,
76184 ** release or rollback an SQL savepoint. 
76185 */
76186 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
76187   char *zName = sqlite3NameFromToken(pParse->db, pName);
76188   if( zName ){
76189     Vdbe *v = sqlite3GetVdbe(pParse);
76190 #ifndef SQLITE_OMIT_AUTHORIZATION
76191     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
76192     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
76193 #endif
76194     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
76195       sqlite3DbFree(pParse->db, zName);
76196       return;
76197     }
76198     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
76199   }
76200 }
76201
76202 /*
76203 ** Make sure the TEMP database is open and available for use.  Return
76204 ** the number of errors.  Leave any error messages in the pParse structure.
76205 */
76206 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
76207   sqlite3 *db = pParse->db;
76208   if( db->aDb[1].pBt==0 && !pParse->explain ){
76209     int rc;
76210     Btree *pBt;
76211     static const int flags = 
76212           SQLITE_OPEN_READWRITE |
76213           SQLITE_OPEN_CREATE |
76214           SQLITE_OPEN_EXCLUSIVE |
76215           SQLITE_OPEN_DELETEONCLOSE |
76216           SQLITE_OPEN_TEMP_DB;
76217
76218     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
76219     if( rc!=SQLITE_OK ){
76220       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
76221         "file for storing temporary tables");
76222       pParse->rc = rc;
76223       return 1;
76224     }
76225     db->aDb[1].pBt = pBt;
76226     assert( db->aDb[1].pSchema );
76227     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
76228       db->mallocFailed = 1;
76229       return 1;
76230     }
76231   }
76232   return 0;
76233 }
76234
76235 /*
76236 ** Generate VDBE code that will verify the schema cookie and start
76237 ** a read-transaction for all named database files.
76238 **
76239 ** It is important that all schema cookies be verified and all
76240 ** read transactions be started before anything else happens in
76241 ** the VDBE program.  But this routine can be called after much other
76242 ** code has been generated.  So here is what we do:
76243 **
76244 ** The first time this routine is called, we code an OP_Goto that
76245 ** will jump to a subroutine at the end of the program.  Then we
76246 ** record every database that needs its schema verified in the
76247 ** pParse->cookieMask field.  Later, after all other code has been
76248 ** generated, the subroutine that does the cookie verifications and
76249 ** starts the transactions will be coded and the OP_Goto P2 value
76250 ** will be made to point to that subroutine.  The generation of the
76251 ** cookie verification subroutine code happens in sqlite3FinishCoding().
76252 **
76253 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
76254 ** schema on any databases.  This can be used to position the OP_Goto
76255 ** early in the code, before we know if any database tables will be used.
76256 */
76257 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
76258   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76259
76260   if( pToplevel->cookieGoto==0 ){
76261     Vdbe *v = sqlite3GetVdbe(pToplevel);
76262     if( v==0 ) return;  /* This only happens if there was a prior error */
76263     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
76264   }
76265   if( iDb>=0 ){
76266     sqlite3 *db = pToplevel->db;
76267     int mask;
76268
76269     assert( iDb<db->nDb );
76270     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
76271     assert( iDb<SQLITE_MAX_ATTACHED+2 );
76272     mask = 1<<iDb;
76273     if( (pToplevel->cookieMask & mask)==0 ){
76274       pToplevel->cookieMask |= mask;
76275       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
76276       if( !OMIT_TEMPDB && iDb==1 ){
76277         sqlite3OpenTempDatabase(pToplevel);
76278       }
76279     }
76280   }
76281 }
76282
76283 /*
76284 ** Generate VDBE code that prepares for doing an operation that
76285 ** might change the database.
76286 **
76287 ** This routine starts a new transaction if we are not already within
76288 ** a transaction.  If we are already within a transaction, then a checkpoint
76289 ** is set if the setStatement parameter is true.  A checkpoint should
76290 ** be set for operations that might fail (due to a constraint) part of
76291 ** the way through and which will need to undo some writes without having to
76292 ** rollback the whole transaction.  For operations where all constraints
76293 ** can be checked before any changes are made to the database, it is never
76294 ** necessary to undo a write and the checkpoint should not be set.
76295 */
76296 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
76297   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76298   sqlite3CodeVerifySchema(pParse, iDb);
76299   pToplevel->writeMask |= 1<<iDb;
76300   pToplevel->isMultiWrite |= setStatement;
76301 }
76302
76303 /*
76304 ** Indicate that the statement currently under construction might write
76305 ** more than one entry (example: deleting one row then inserting another,
76306 ** inserting multiple rows in a table, or inserting a row and index entries.)
76307 ** If an abort occurs after some of these writes have completed, then it will
76308 ** be necessary to undo the completed writes.
76309 */
76310 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
76311   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76312   pToplevel->isMultiWrite = 1;
76313 }
76314
76315 /* 
76316 ** The code generator calls this routine if is discovers that it is
76317 ** possible to abort a statement prior to completion.  In order to 
76318 ** perform this abort without corrupting the database, we need to make
76319 ** sure that the statement is protected by a statement transaction.
76320 **
76321 ** Technically, we only need to set the mayAbort flag if the
76322 ** isMultiWrite flag was previously set.  There is a time dependency
76323 ** such that the abort must occur after the multiwrite.  This makes
76324 ** some statements involving the REPLACE conflict resolution algorithm
76325 ** go a little faster.  But taking advantage of this time dependency
76326 ** makes it more difficult to prove that the code is correct (in 
76327 ** particular, it prevents us from writing an effective
76328 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
76329 ** to take the safe route and skip the optimization.
76330 */
76331 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
76332   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76333   pToplevel->mayAbort = 1;
76334 }
76335
76336 /*
76337 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
76338 ** error. The onError parameter determines which (if any) of the statement
76339 ** and/or current transaction is rolled back.
76340 */
76341 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
76342   Vdbe *v = sqlite3GetVdbe(pParse);
76343   if( onError==OE_Abort ){
76344     sqlite3MayAbort(pParse);
76345   }
76346   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
76347 }
76348
76349 /*
76350 ** Check to see if pIndex uses the collating sequence pColl.  Return
76351 ** true if it does and false if it does not.
76352 */
76353 #ifndef SQLITE_OMIT_REINDEX
76354 static int collationMatch(const char *zColl, Index *pIndex){
76355   int i;
76356   assert( zColl!=0 );
76357   for(i=0; i<pIndex->nColumn; i++){
76358     const char *z = pIndex->azColl[i];
76359     assert( z!=0 );
76360     if( 0==sqlite3StrICmp(z, zColl) ){
76361       return 1;
76362     }
76363   }
76364   return 0;
76365 }
76366 #endif
76367
76368 /*
76369 ** Recompute all indices of pTab that use the collating sequence pColl.
76370 ** If pColl==0 then recompute all indices of pTab.
76371 */
76372 #ifndef SQLITE_OMIT_REINDEX
76373 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
76374   Index *pIndex;              /* An index associated with pTab */
76375
76376   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
76377     if( zColl==0 || collationMatch(zColl, pIndex) ){
76378       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76379       sqlite3BeginWriteOperation(pParse, 0, iDb);
76380       sqlite3RefillIndex(pParse, pIndex, -1);
76381     }
76382   }
76383 }
76384 #endif
76385
76386 /*
76387 ** Recompute all indices of all tables in all databases where the
76388 ** indices use the collating sequence pColl.  If pColl==0 then recompute
76389 ** all indices everywhere.
76390 */
76391 #ifndef SQLITE_OMIT_REINDEX
76392 static void reindexDatabases(Parse *pParse, char const *zColl){
76393   Db *pDb;                    /* A single database */
76394   int iDb;                    /* The database index number */
76395   sqlite3 *db = pParse->db;   /* The database connection */
76396   HashElem *k;                /* For looping over tables in pDb */
76397   Table *pTab;                /* A table in the database */
76398
76399   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
76400     assert( pDb!=0 );
76401     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
76402       pTab = (Table*)sqliteHashData(k);
76403       reindexTable(pParse, pTab, zColl);
76404     }
76405   }
76406 }
76407 #endif
76408
76409 /*
76410 ** Generate code for the REINDEX command.
76411 **
76412 **        REINDEX                            -- 1
76413 **        REINDEX  <collation>               -- 2
76414 **        REINDEX  ?<database>.?<tablename>  -- 3
76415 **        REINDEX  ?<database>.?<indexname>  -- 4
76416 **
76417 ** Form 1 causes all indices in all attached databases to be rebuilt.
76418 ** Form 2 rebuilds all indices in all databases that use the named
76419 ** collating function.  Forms 3 and 4 rebuild the named index or all
76420 ** indices associated with the named table.
76421 */
76422 #ifndef SQLITE_OMIT_REINDEX
76423 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
76424   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
76425   char *z;                    /* Name of a table or index */
76426   const char *zDb;            /* Name of the database */
76427   Table *pTab;                /* A table in the database */
76428   Index *pIndex;              /* An index associated with pTab */
76429   int iDb;                    /* The database index number */
76430   sqlite3 *db = pParse->db;   /* The database connection */
76431   Token *pObjName;            /* Name of the table or index to be reindexed */
76432
76433   /* Read the database schema. If an error occurs, leave an error message
76434   ** and code in pParse and return NULL. */
76435   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76436     return;
76437   }
76438
76439   if( pName1==0 ){
76440     reindexDatabases(pParse, 0);
76441     return;
76442   }else if( NEVER(pName2==0) || pName2->z==0 ){
76443     char *zColl;
76444     assert( pName1->z );
76445     zColl = sqlite3NameFromToken(pParse->db, pName1);
76446     if( !zColl ) return;
76447     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
76448     if( pColl ){
76449       reindexDatabases(pParse, zColl);
76450       sqlite3DbFree(db, zColl);
76451       return;
76452     }
76453     sqlite3DbFree(db, zColl);
76454   }
76455   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
76456   if( iDb<0 ) return;
76457   z = sqlite3NameFromToken(db, pObjName);
76458   if( z==0 ) return;
76459   zDb = db->aDb[iDb].zName;
76460   pTab = sqlite3FindTable(db, z, zDb);
76461   if( pTab ){
76462     reindexTable(pParse, pTab, 0);
76463     sqlite3DbFree(db, z);
76464     return;
76465   }
76466   pIndex = sqlite3FindIndex(db, z, zDb);
76467   sqlite3DbFree(db, z);
76468   if( pIndex ){
76469     sqlite3BeginWriteOperation(pParse, 0, iDb);
76470     sqlite3RefillIndex(pParse, pIndex, -1);
76471     return;
76472   }
76473   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
76474 }
76475 #endif
76476
76477 /*
76478 ** Return a dynamicly allocated KeyInfo structure that can be used
76479 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
76480 **
76481 ** If successful, a pointer to the new structure is returned. In this case
76482 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
76483 ** pointer. If an error occurs (out of memory or missing collation 
76484 ** sequence), NULL is returned and the state of pParse updated to reflect
76485 ** the error.
76486 */
76487 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
76488   int i;
76489   int nCol = pIdx->nColumn;
76490   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
76491   sqlite3 *db = pParse->db;
76492   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
76493
76494   if( pKey ){
76495     pKey->db = pParse->db;
76496     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
76497     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
76498     for(i=0; i<nCol; i++){
76499       char *zColl = pIdx->azColl[i];
76500       assert( zColl );
76501       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
76502       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
76503     }
76504     pKey->nField = (u16)nCol;
76505   }
76506
76507   if( pParse->nErr ){
76508     sqlite3DbFree(db, pKey);
76509     pKey = 0;
76510   }
76511   return pKey;
76512 }
76513
76514 /************** End of build.c ***********************************************/
76515 /************** Begin file callback.c ****************************************/
76516 /*
76517 ** 2005 May 23 
76518 **
76519 ** The author disclaims copyright to this source code.  In place of
76520 ** a legal notice, here is a blessing:
76521 **
76522 **    May you do good and not evil.
76523 **    May you find forgiveness for yourself and forgive others.
76524 **    May you share freely, never taking more than you give.
76525 **
76526 *************************************************************************
76527 **
76528 ** This file contains functions used to access the internal hash tables
76529 ** of user defined functions and collation sequences.
76530 */
76531
76532
76533 /*
76534 ** Invoke the 'collation needed' callback to request a collation sequence
76535 ** in the encoding enc of name zName, length nName.
76536 */
76537 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
76538   assert( !db->xCollNeeded || !db->xCollNeeded16 );
76539   if( db->xCollNeeded ){
76540     char *zExternal = sqlite3DbStrDup(db, zName);
76541     if( !zExternal ) return;
76542     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
76543     sqlite3DbFree(db, zExternal);
76544   }
76545 #ifndef SQLITE_OMIT_UTF16
76546   if( db->xCollNeeded16 ){
76547     char const *zExternal;
76548     sqlite3_value *pTmp = sqlite3ValueNew(db);
76549     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
76550     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
76551     if( zExternal ){
76552       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
76553     }
76554     sqlite3ValueFree(pTmp);
76555   }
76556 #endif
76557 }
76558
76559 /*
76560 ** This routine is called if the collation factory fails to deliver a
76561 ** collation function in the best encoding but there may be other versions
76562 ** of this collation function (for other text encodings) available. Use one
76563 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
76564 ** possible.
76565 */
76566 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
76567   CollSeq *pColl2;
76568   char *z = pColl->zName;
76569   int i;
76570   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
76571   for(i=0; i<3; i++){
76572     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
76573     if( pColl2->xCmp!=0 ){
76574       memcpy(pColl, pColl2, sizeof(CollSeq));
76575       pColl->xDel = 0;         /* Do not copy the destructor */
76576       return SQLITE_OK;
76577     }
76578   }
76579   return SQLITE_ERROR;
76580 }
76581
76582 /*
76583 ** This function is responsible for invoking the collation factory callback
76584 ** or substituting a collation sequence of a different encoding when the
76585 ** requested collation sequence is not available in the desired encoding.
76586 ** 
76587 ** If it is not NULL, then pColl must point to the database native encoding 
76588 ** collation sequence with name zName, length nName.
76589 **
76590 ** The return value is either the collation sequence to be used in database
76591 ** db for collation type name zName, length nName, or NULL, if no collation
76592 ** sequence can be found.
76593 **
76594 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
76595 */
76596 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
76597   sqlite3* db,          /* The database connection */
76598   u8 enc,               /* The desired encoding for the collating sequence */
76599   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
76600   const char *zName     /* Collating sequence name */
76601 ){
76602   CollSeq *p;
76603
76604   p = pColl;
76605   if( !p ){
76606     p = sqlite3FindCollSeq(db, enc, zName, 0);
76607   }
76608   if( !p || !p->xCmp ){
76609     /* No collation sequence of this type for this encoding is registered.
76610     ** Call the collation factory to see if it can supply us with one.
76611     */
76612     callCollNeeded(db, enc, zName);
76613     p = sqlite3FindCollSeq(db, enc, zName, 0);
76614   }
76615   if( p && !p->xCmp && synthCollSeq(db, p) ){
76616     p = 0;
76617   }
76618   assert( !p || p->xCmp );
76619   return p;
76620 }
76621
76622 /*
76623 ** This routine is called on a collation sequence before it is used to
76624 ** check that it is defined. An undefined collation sequence exists when
76625 ** a database is loaded that contains references to collation sequences
76626 ** that have not been defined by sqlite3_create_collation() etc.
76627 **
76628 ** If required, this routine calls the 'collation needed' callback to
76629 ** request a definition of the collating sequence. If this doesn't work, 
76630 ** an equivalent collating sequence that uses a text encoding different
76631 ** from the main database is substituted, if one is available.
76632 */
76633 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
76634   if( pColl ){
76635     const char *zName = pColl->zName;
76636     sqlite3 *db = pParse->db;
76637     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
76638     if( !p ){
76639       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
76640       pParse->nErr++;
76641       return SQLITE_ERROR;
76642     }
76643     assert( p==pColl );
76644   }
76645   return SQLITE_OK;
76646 }
76647
76648
76649
76650 /*
76651 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
76652 ** specified by zName and nName is not found and parameter 'create' is
76653 ** true, then create a new entry. Otherwise return NULL.
76654 **
76655 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
76656 ** array of three CollSeq structures. The first is the collation sequence
76657 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
76658 **
76659 ** Stored immediately after the three collation sequences is a copy of
76660 ** the collation sequence name. A pointer to this string is stored in
76661 ** each collation sequence structure.
76662 */
76663 static CollSeq *findCollSeqEntry(
76664   sqlite3 *db,          /* Database connection */
76665   const char *zName,    /* Name of the collating sequence */
76666   int create            /* Create a new entry if true */
76667 ){
76668   CollSeq *pColl;
76669   int nName = sqlite3Strlen30(zName);
76670   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
76671
76672   if( 0==pColl && create ){
76673     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
76674     if( pColl ){
76675       CollSeq *pDel = 0;
76676       pColl[0].zName = (char*)&pColl[3];
76677       pColl[0].enc = SQLITE_UTF8;
76678       pColl[1].zName = (char*)&pColl[3];
76679       pColl[1].enc = SQLITE_UTF16LE;
76680       pColl[2].zName = (char*)&pColl[3];
76681       pColl[2].enc = SQLITE_UTF16BE;
76682       memcpy(pColl[0].zName, zName, nName);
76683       pColl[0].zName[nName] = 0;
76684       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
76685
76686       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
76687       ** return the pColl pointer to be deleted (because it wasn't added
76688       ** to the hash table).
76689       */
76690       assert( pDel==0 || pDel==pColl );
76691       if( pDel!=0 ){
76692         db->mallocFailed = 1;
76693         sqlite3DbFree(db, pDel);
76694         pColl = 0;
76695       }
76696     }
76697   }
76698   return pColl;
76699 }
76700
76701 /*
76702 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
76703 ** Return the CollSeq* pointer for the collation sequence named zName
76704 ** for the encoding 'enc' from the database 'db'.
76705 **
76706 ** If the entry specified is not found and 'create' is true, then create a
76707 ** new entry.  Otherwise return NULL.
76708 **
76709 ** A separate function sqlite3LocateCollSeq() is a wrapper around
76710 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
76711 ** if necessary and generates an error message if the collating sequence
76712 ** cannot be found.
76713 **
76714 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
76715 */
76716 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
76717   sqlite3 *db,
76718   u8 enc,
76719   const char *zName,
76720   int create
76721 ){
76722   CollSeq *pColl;
76723   if( zName ){
76724     pColl = findCollSeqEntry(db, zName, create);
76725   }else{
76726     pColl = db->pDfltColl;
76727   }
76728   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
76729   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
76730   if( pColl ) pColl += enc-1;
76731   return pColl;
76732 }
76733
76734 /* During the search for the best function definition, this procedure
76735 ** is called to test how well the function passed as the first argument
76736 ** matches the request for a function with nArg arguments in a system
76737 ** that uses encoding enc. The value returned indicates how well the
76738 ** request is matched. A higher value indicates a better match.
76739 **
76740 ** The returned value is always between 0 and 6, as follows:
76741 **
76742 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
76743 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
76744 **    encoding is requested, or vice versa.
76745 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
76746 **    requested, or vice versa.
76747 ** 3: A variable arguments function using the same text encoding.
76748 ** 4: A function with the exact number of arguments requested that
76749 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
76750 ** 5: A function with the exact number of arguments requested that
76751 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
76752 ** 6: An exact match.
76753 **
76754 */
76755 static int matchQuality(FuncDef *p, int nArg, u8 enc){
76756   int match = 0;
76757   if( p->nArg==-1 || p->nArg==nArg 
76758    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
76759   ){
76760     match = 1;
76761     if( p->nArg==nArg || nArg==-1 ){
76762       match = 4;
76763     }
76764     if( enc==p->iPrefEnc ){
76765       match += 2;
76766     }
76767     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
76768              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
76769       match += 1;
76770     }
76771   }
76772   return match;
76773 }
76774
76775 /*
76776 ** Search a FuncDefHash for a function with the given name.  Return
76777 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
76778 */
76779 static FuncDef *functionSearch(
76780   FuncDefHash *pHash,  /* Hash table to search */
76781   int h,               /* Hash of the name */
76782   const char *zFunc,   /* Name of function */
76783   int nFunc            /* Number of bytes in zFunc */
76784 ){
76785   FuncDef *p;
76786   for(p=pHash->a[h]; p; p=p->pHash){
76787     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
76788       return p;
76789     }
76790   }
76791   return 0;
76792 }
76793
76794 /*
76795 ** Insert a new FuncDef into a FuncDefHash hash table.
76796 */
76797 SQLITE_PRIVATE void sqlite3FuncDefInsert(
76798   FuncDefHash *pHash,  /* The hash table into which to insert */
76799   FuncDef *pDef        /* The function definition to insert */
76800 ){
76801   FuncDef *pOther;
76802   int nName = sqlite3Strlen30(pDef->zName);
76803   u8 c1 = (u8)pDef->zName[0];
76804   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
76805   pOther = functionSearch(pHash, h, pDef->zName, nName);
76806   if( pOther ){
76807     assert( pOther!=pDef && pOther->pNext!=pDef );
76808     pDef->pNext = pOther->pNext;
76809     pOther->pNext = pDef;
76810   }else{
76811     pDef->pNext = 0;
76812     pDef->pHash = pHash->a[h];
76813     pHash->a[h] = pDef;
76814   }
76815 }
76816   
76817   
76818
76819 /*
76820 ** Locate a user function given a name, a number of arguments and a flag
76821 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
76822 ** pointer to the FuncDef structure that defines that function, or return
76823 ** NULL if the function does not exist.
76824 **
76825 ** If the createFlag argument is true, then a new (blank) FuncDef
76826 ** structure is created and liked into the "db" structure if a
76827 ** no matching function previously existed.  When createFlag is true
76828 ** and the nArg parameter is -1, then only a function that accepts
76829 ** any number of arguments will be returned.
76830 **
76831 ** If createFlag is false and nArg is -1, then the first valid
76832 ** function found is returned.  A function is valid if either xFunc
76833 ** or xStep is non-zero.
76834 **
76835 ** If createFlag is false, then a function with the required name and
76836 ** number of arguments may be returned even if the eTextRep flag does not
76837 ** match that requested.
76838 */
76839 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
76840   sqlite3 *db,       /* An open database */
76841   const char *zName, /* Name of the function.  Not null-terminated */
76842   int nName,         /* Number of characters in the name */
76843   int nArg,          /* Number of arguments.  -1 means any number */
76844   u8 enc,            /* Preferred text encoding */
76845   int createFlag     /* Create new entry if true and does not otherwise exist */
76846 ){
76847   FuncDef *p;         /* Iterator variable */
76848   FuncDef *pBest = 0; /* Best match found so far */
76849   int bestScore = 0;  /* Score of best match */
76850   int h;              /* Hash value */
76851
76852
76853   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
76854   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
76855
76856   /* First search for a match amongst the application-defined functions.
76857   */
76858   p = functionSearch(&db->aFunc, h, zName, nName);
76859   while( p ){
76860     int score = matchQuality(p, nArg, enc);
76861     if( score>bestScore ){
76862       pBest = p;
76863       bestScore = score;
76864     }
76865     p = p->pNext;
76866   }
76867
76868   /* If no match is found, search the built-in functions.
76869   **
76870   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
76871   ** functions even if a prior app-defined function was found.  And give
76872   ** priority to built-in functions.
76873   **
76874   ** Except, if createFlag is true, that means that we are trying to
76875   ** install a new function.  Whatever FuncDef structure is returned will
76876   ** have fields overwritten with new information appropriate for the
76877   ** new function.  But the FuncDefs for built-in functions are read-only.
76878   ** So we must not search for built-ins when creating a new function.
76879   */ 
76880   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
76881     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
76882     bestScore = 0;
76883     p = functionSearch(pHash, h, zName, nName);
76884     while( p ){
76885       int score = matchQuality(p, nArg, enc);
76886       if( score>bestScore ){
76887         pBest = p;
76888         bestScore = score;
76889       }
76890       p = p->pNext;
76891     }
76892   }
76893
76894   /* If the createFlag parameter is true and the search did not reveal an
76895   ** exact match for the name, number of arguments and encoding, then add a
76896   ** new entry to the hash table and return it.
76897   */
76898   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
76899       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
76900     pBest->zName = (char *)&pBest[1];
76901     pBest->nArg = (u16)nArg;
76902     pBest->iPrefEnc = enc;
76903     memcpy(pBest->zName, zName, nName);
76904     pBest->zName[nName] = 0;
76905     sqlite3FuncDefInsert(&db->aFunc, pBest);
76906   }
76907
76908   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
76909     return pBest;
76910   }
76911   return 0;
76912 }
76913
76914 /*
76915 ** Free all resources held by the schema structure. The void* argument points
76916 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
76917 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
76918 ** of the schema hash tables).
76919 **
76920 ** The Schema.cache_size variable is not cleared.
76921 */
76922 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
76923   Hash temp1;
76924   Hash temp2;
76925   HashElem *pElem;
76926   Schema *pSchema = (Schema *)p;
76927
76928   temp1 = pSchema->tblHash;
76929   temp2 = pSchema->trigHash;
76930   sqlite3HashInit(&pSchema->trigHash);
76931   sqlite3HashClear(&pSchema->idxHash);
76932   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
76933     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
76934   }
76935   sqlite3HashClear(&temp2);
76936   sqlite3HashInit(&pSchema->tblHash);
76937   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
76938     Table *pTab = sqliteHashData(pElem);
76939     assert( pTab->dbMem==0 );
76940     sqlite3DeleteTable(pTab);
76941   }
76942   sqlite3HashClear(&temp1);
76943   sqlite3HashClear(&pSchema->fkeyHash);
76944   pSchema->pSeqTab = 0;
76945   pSchema->flags &= ~DB_SchemaLoaded;
76946 }
76947
76948 /*
76949 ** Find and return the schema associated with a BTree.  Create
76950 ** a new one if necessary.
76951 */
76952 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
76953   Schema * p;
76954   if( pBt ){
76955     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
76956   }else{
76957     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
76958   }
76959   if( !p ){
76960     db->mallocFailed = 1;
76961   }else if ( 0==p->file_format ){
76962     sqlite3HashInit(&p->tblHash);
76963     sqlite3HashInit(&p->idxHash);
76964     sqlite3HashInit(&p->trigHash);
76965     sqlite3HashInit(&p->fkeyHash);
76966     p->enc = SQLITE_UTF8;
76967   }
76968   return p;
76969 }
76970
76971 /************** End of callback.c ********************************************/
76972 /************** Begin file delete.c ******************************************/
76973 /*
76974 ** 2001 September 15
76975 **
76976 ** The author disclaims copyright to this source code.  In place of
76977 ** a legal notice, here is a blessing:
76978 **
76979 **    May you do good and not evil.
76980 **    May you find forgiveness for yourself and forgive others.
76981 **    May you share freely, never taking more than you give.
76982 **
76983 *************************************************************************
76984 ** This file contains C code routines that are called by the parser
76985 ** in order to generate code for DELETE FROM statements.
76986 */
76987
76988 /*
76989 ** Look up every table that is named in pSrc.  If any table is not found,
76990 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
76991 ** are found, return a pointer to the last table.
76992 */
76993 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
76994   struct SrcList_item *pItem = pSrc->a;
76995   Table *pTab;
76996   assert( pItem && pSrc->nSrc==1 );
76997   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
76998   sqlite3DeleteTable(pItem->pTab);
76999   pItem->pTab = pTab;
77000   if( pTab ){
77001     pTab->nRef++;
77002   }
77003   if( sqlite3IndexedByLookup(pParse, pItem) ){
77004     pTab = 0;
77005   }
77006   return pTab;
77007 }
77008
77009 /*
77010 ** Check to make sure the given table is writable.  If it is not
77011 ** writable, generate an error message and return 1.  If it is
77012 ** writable return 0;
77013 */
77014 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
77015   /* A table is not writable under the following circumstances:
77016   **
77017   **   1) It is a virtual table and no implementation of the xUpdate method
77018   **      has been provided, or
77019   **   2) It is a system table (i.e. sqlite_master), this call is not
77020   **      part of a nested parse and writable_schema pragma has not 
77021   **      been specified.
77022   **
77023   ** In either case leave an error message in pParse and return non-zero.
77024   */
77025   if( ( IsVirtual(pTab) 
77026      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
77027    || ( (pTab->tabFlags & TF_Readonly)!=0
77028      && (pParse->db->flags & SQLITE_WriteSchema)==0
77029      && pParse->nested==0 )
77030   ){
77031     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
77032     return 1;
77033   }
77034
77035 #ifndef SQLITE_OMIT_VIEW
77036   if( !viewOk && pTab->pSelect ){
77037     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
77038     return 1;
77039   }
77040 #endif
77041   return 0;
77042 }
77043
77044
77045 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
77046 /*
77047 ** Evaluate a view and store its result in an ephemeral table.  The
77048 ** pWhere argument is an optional WHERE clause that restricts the
77049 ** set of rows in the view that are to be added to the ephemeral table.
77050 */
77051 SQLITE_PRIVATE void sqlite3MaterializeView(
77052   Parse *pParse,       /* Parsing context */
77053   Table *pView,        /* View definition */
77054   Expr *pWhere,        /* Optional WHERE clause to be added */
77055   int iCur             /* Cursor number for ephemerial table */
77056 ){
77057   SelectDest dest;
77058   Select *pDup;
77059   sqlite3 *db = pParse->db;
77060
77061   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
77062   if( pWhere ){
77063     SrcList *pFrom;
77064     
77065     pWhere = sqlite3ExprDup(db, pWhere, 0);
77066     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
77067     if( pFrom ){
77068       assert( pFrom->nSrc==1 );
77069       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
77070       pFrom->a[0].pSelect = pDup;
77071       assert( pFrom->a[0].pOn==0 );
77072       assert( pFrom->a[0].pUsing==0 );
77073     }else{
77074       sqlite3SelectDelete(db, pDup);
77075     }
77076     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
77077   }
77078   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
77079   sqlite3Select(pParse, pDup, &dest);
77080   sqlite3SelectDelete(db, pDup);
77081 }
77082 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
77083
77084 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
77085 /*
77086 ** Generate an expression tree to implement the WHERE, ORDER BY,
77087 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
77088 **
77089 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
77090 **                            \__________________________/
77091 **                               pLimitWhere (pInClause)
77092 */
77093 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
77094   Parse *pParse,               /* The parser context */
77095   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
77096   Expr *pWhere,                /* The WHERE clause.  May be null */
77097   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
77098   Expr *pLimit,                /* The LIMIT clause.  May be null */
77099   Expr *pOffset,               /* The OFFSET clause.  May be null */
77100   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
77101 ){
77102   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
77103   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
77104   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
77105   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
77106   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
77107   Select *pSelect = NULL;      /* Complete SELECT tree */
77108
77109   /* Check that there isn't an ORDER BY without a LIMIT clause.
77110   */
77111   if( pOrderBy && (pLimit == 0) ) {
77112     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
77113     pParse->parseError = 1;
77114     goto limit_where_cleanup_2;
77115   }
77116
77117   /* We only need to generate a select expression if there
77118   ** is a limit/offset term to enforce.
77119   */
77120   if( pLimit == 0 ) {
77121     /* if pLimit is null, pOffset will always be null as well. */
77122     assert( pOffset == 0 );
77123     return pWhere;
77124   }
77125
77126   /* Generate a select expression tree to enforce the limit/offset 
77127   ** term for the DELETE or UPDATE statement.  For example:
77128   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
77129   ** becomes:
77130   **   DELETE FROM table_a WHERE rowid IN ( 
77131   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
77132   **   );
77133   */
77134
77135   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
77136   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
77137   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
77138   if( pEList == 0 ) goto limit_where_cleanup_2;
77139
77140   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
77141   ** and the SELECT subtree. */
77142   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
77143   if( pSelectSrc == 0 ) {
77144     sqlite3ExprListDelete(pParse->db, pEList);
77145     goto limit_where_cleanup_2;
77146   }
77147
77148   /* generate the SELECT expression tree. */
77149   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
77150                              pOrderBy,0,pLimit,pOffset);
77151   if( pSelect == 0 ) return 0;
77152
77153   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
77154   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
77155   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
77156   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
77157   if( pInClause == 0 ) goto limit_where_cleanup_1;
77158
77159   pInClause->x.pSelect = pSelect;
77160   pInClause->flags |= EP_xIsSelect;
77161   sqlite3ExprSetHeight(pParse, pInClause);
77162   return pInClause;
77163
77164   /* something went wrong. clean up anything allocated. */
77165 limit_where_cleanup_1:
77166   sqlite3SelectDelete(pParse->db, pSelect);
77167   return 0;
77168
77169 limit_where_cleanup_2:
77170   sqlite3ExprDelete(pParse->db, pWhere);
77171   sqlite3ExprListDelete(pParse->db, pOrderBy);
77172   sqlite3ExprDelete(pParse->db, pLimit);
77173   sqlite3ExprDelete(pParse->db, pOffset);
77174   return 0;
77175 }
77176 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
77177
77178 /*
77179 ** Generate code for a DELETE FROM statement.
77180 **
77181 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
77182 **                 \________/       \________________/
77183 **                  pTabList              pWhere
77184 */
77185 SQLITE_PRIVATE void sqlite3DeleteFrom(
77186   Parse *pParse,         /* The parser context */
77187   SrcList *pTabList,     /* The table from which we should delete things */
77188   Expr *pWhere           /* The WHERE clause.  May be null */
77189 ){
77190   Vdbe *v;               /* The virtual database engine */
77191   Table *pTab;           /* The table from which records will be deleted */
77192   const char *zDb;       /* Name of database holding pTab */
77193   int end, addr = 0;     /* A couple addresses of generated code */
77194   int i;                 /* Loop counter */
77195   WhereInfo *pWInfo;     /* Information about the WHERE clause */
77196   Index *pIdx;           /* For looping over indices of the table */
77197   int iCur;              /* VDBE Cursor number for pTab */
77198   sqlite3 *db;           /* Main database structure */
77199   AuthContext sContext;  /* Authorization context */
77200   NameContext sNC;       /* Name context to resolve expressions in */
77201   int iDb;               /* Database number */
77202   int memCnt = -1;       /* Memory cell used for change counting */
77203   int rcauth;            /* Value returned by authorization callback */
77204
77205 #ifndef SQLITE_OMIT_TRIGGER
77206   int isView;                  /* True if attempting to delete from a view */
77207   Trigger *pTrigger;           /* List of table triggers, if required */
77208 #endif
77209
77210   memset(&sContext, 0, sizeof(sContext));
77211   db = pParse->db;
77212   if( pParse->nErr || db->mallocFailed ){
77213     goto delete_from_cleanup;
77214   }
77215   assert( pTabList->nSrc==1 );
77216
77217   /* Locate the table which we want to delete.  This table has to be
77218   ** put in an SrcList structure because some of the subroutines we
77219   ** will be calling are designed to work with multiple tables and expect
77220   ** an SrcList* parameter instead of just a Table* parameter.
77221   */
77222   pTab = sqlite3SrcListLookup(pParse, pTabList);
77223   if( pTab==0 )  goto delete_from_cleanup;
77224
77225   /* Figure out if we have any triggers and if the table being
77226   ** deleted from is a view
77227   */
77228 #ifndef SQLITE_OMIT_TRIGGER
77229   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
77230   isView = pTab->pSelect!=0;
77231 #else
77232 # define pTrigger 0
77233 # define isView 0
77234 #endif
77235 #ifdef SQLITE_OMIT_VIEW
77236 # undef isView
77237 # define isView 0
77238 #endif
77239
77240   /* If pTab is really a view, make sure it has been initialized.
77241   */
77242   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
77243     goto delete_from_cleanup;
77244   }
77245
77246   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
77247     goto delete_from_cleanup;
77248   }
77249   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77250   assert( iDb<db->nDb );
77251   zDb = db->aDb[iDb].zName;
77252   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
77253   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
77254   if( rcauth==SQLITE_DENY ){
77255     goto delete_from_cleanup;
77256   }
77257   assert(!isView || pTrigger);
77258
77259   /* Assign  cursor number to the table and all its indices.
77260   */
77261   assert( pTabList->nSrc==1 );
77262   iCur = pTabList->a[0].iCursor = pParse->nTab++;
77263   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77264     pParse->nTab++;
77265   }
77266
77267   /* Start the view context
77268   */
77269   if( isView ){
77270     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
77271   }
77272
77273   /* Begin generating code.
77274   */
77275   v = sqlite3GetVdbe(pParse);
77276   if( v==0 ){
77277     goto delete_from_cleanup;
77278   }
77279   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
77280   sqlite3BeginWriteOperation(pParse, 1, iDb);
77281
77282   /* If we are trying to delete from a view, realize that view into
77283   ** a ephemeral table.
77284   */
77285 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
77286   if( isView ){
77287     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
77288   }
77289 #endif
77290
77291   /* Resolve the column names in the WHERE clause.
77292   */
77293   memset(&sNC, 0, sizeof(sNC));
77294   sNC.pParse = pParse;
77295   sNC.pSrcList = pTabList;
77296   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
77297     goto delete_from_cleanup;
77298   }
77299
77300   /* Initialize the counter of the number of rows deleted, if
77301   ** we are counting rows.
77302   */
77303   if( db->flags & SQLITE_CountRows ){
77304     memCnt = ++pParse->nMem;
77305     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
77306   }
77307
77308 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
77309   /* Special case: A DELETE without a WHERE clause deletes everything.
77310   ** It is easier just to erase the whole table. Prior to version 3.6.5,
77311   ** this optimization caused the row change count (the value returned by 
77312   ** API function sqlite3_count_changes) to be set incorrectly.  */
77313   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
77314    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
77315   ){
77316     assert( !isView );
77317     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
77318                       pTab->zName, P4_STATIC);
77319     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77320       assert( pIdx->pSchema==pTab->pSchema );
77321       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
77322     }
77323   }else
77324 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
77325   /* The usual case: There is a WHERE clause so we have to scan through
77326   ** the table and pick which records to delete.
77327   */
77328   {
77329     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
77330     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
77331     int regRowid;                   /* Actual register containing rowids */
77332
77333     /* Collect rowids of every row to be deleted.
77334     */
77335     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
77336     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
77337     if( pWInfo==0 ) goto delete_from_cleanup;
77338     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
77339     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
77340     if( db->flags & SQLITE_CountRows ){
77341       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
77342     }
77343     sqlite3WhereEnd(pWInfo);
77344
77345     /* Delete every item whose key was written to the list during the
77346     ** database scan.  We have to delete items after the scan is complete
77347     ** because deleting an item can change the scan order.  */
77348     end = sqlite3VdbeMakeLabel(v);
77349
77350     /* Unless this is a view, open cursors for the table we are 
77351     ** deleting from and all its indices. If this is a view, then the
77352     ** only effect this statement has is to fire the INSTEAD OF 
77353     ** triggers.  */
77354     if( !isView ){
77355       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
77356     }
77357
77358     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
77359
77360     /* Delete the row */
77361 #ifndef SQLITE_OMIT_VIRTUALTABLE
77362     if( IsVirtual(pTab) ){
77363       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
77364       sqlite3VtabMakeWritable(pParse, pTab);
77365       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
77366       sqlite3MayAbort(pParse);
77367     }else
77368 #endif
77369     {
77370       int count = (pParse->nested==0);    /* True to count changes */
77371       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
77372     }
77373
77374     /* End of the delete loop */
77375     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
77376     sqlite3VdbeResolveLabel(v, end);
77377
77378     /* Close the cursors open on the table and its indexes. */
77379     if( !isView && !IsVirtual(pTab) ){
77380       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77381         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
77382       }
77383       sqlite3VdbeAddOp1(v, OP_Close, iCur);
77384     }
77385   }
77386
77387   /* Update the sqlite_sequence table by storing the content of the
77388   ** maximum rowid counter values recorded while inserting into
77389   ** autoincrement tables.
77390   */
77391   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
77392     sqlite3AutoincrementEnd(pParse);
77393   }
77394
77395   /* Return the number of rows that were deleted. If this routine is 
77396   ** generating code because of a call to sqlite3NestedParse(), do not
77397   ** invoke the callback function.
77398   */
77399   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
77400     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
77401     sqlite3VdbeSetNumCols(v, 1);
77402     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
77403   }
77404
77405 delete_from_cleanup:
77406   sqlite3AuthContextPop(&sContext);
77407   sqlite3SrcListDelete(db, pTabList);
77408   sqlite3ExprDelete(db, pWhere);
77409   return;
77410 }
77411 /* Make sure "isView" and other macros defined above are undefined. Otherwise
77412 ** thely may interfere with compilation of other functions in this file
77413 ** (or in another file, if this file becomes part of the amalgamation).  */
77414 #ifdef isView
77415  #undef isView
77416 #endif
77417 #ifdef pTrigger
77418  #undef pTrigger
77419 #endif
77420
77421 /*
77422 ** This routine generates VDBE code that causes a single row of a
77423 ** single table to be deleted.
77424 **
77425 ** The VDBE must be in a particular state when this routine is called.
77426 ** These are the requirements:
77427 **
77428 **   1.  A read/write cursor pointing to pTab, the table containing the row
77429 **       to be deleted, must be opened as cursor number $iCur.
77430 **
77431 **   2.  Read/write cursors for all indices of pTab must be open as
77432 **       cursor number base+i for the i-th index.
77433 **
77434 **   3.  The record number of the row to be deleted must be stored in
77435 **       memory cell iRowid.
77436 **
77437 ** This routine generates code to remove both the table record and all 
77438 ** index entries that point to that record.
77439 */
77440 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
77441   Parse *pParse,     /* Parsing context */
77442   Table *pTab,       /* Table containing the row to be deleted */
77443   int iCur,          /* Cursor number for the table */
77444   int iRowid,        /* Memory cell that contains the rowid to delete */
77445   int count,         /* If non-zero, increment the row change counter */
77446   Trigger *pTrigger, /* List of triggers to (potentially) fire */
77447   int onconf         /* Default ON CONFLICT policy for triggers */
77448 ){
77449   Vdbe *v = pParse->pVdbe;        /* Vdbe */
77450   int iOld = 0;                   /* First register in OLD.* array */
77451   int iLabel;                     /* Label resolved to end of generated code */
77452
77453   /* Vdbe is guaranteed to have been allocated by this stage. */
77454   assert( v );
77455
77456   /* Seek cursor iCur to the row to delete. If this row no longer exists 
77457   ** (this can happen if a trigger program has already deleted it), do
77458   ** not attempt to delete it or fire any DELETE triggers.  */
77459   iLabel = sqlite3VdbeMakeLabel(v);
77460   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77461  
77462   /* If there are any triggers to fire, allocate a range of registers to
77463   ** use for the old.* references in the triggers.  */
77464   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
77465     u32 mask;                     /* Mask of OLD.* columns in use */
77466     int iCol;                     /* Iterator used while populating OLD.* */
77467
77468     /* TODO: Could use temporary registers here. Also could attempt to
77469     ** avoid copying the contents of the rowid register.  */
77470     mask = sqlite3TriggerColmask(
77471         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
77472     );
77473     mask |= sqlite3FkOldmask(pParse, pTab);
77474     iOld = pParse->nMem+1;
77475     pParse->nMem += (1 + pTab->nCol);
77476
77477     /* Populate the OLD.* pseudo-table register array. These values will be 
77478     ** used by any BEFORE and AFTER triggers that exist.  */
77479     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
77480     for(iCol=0; iCol<pTab->nCol; iCol++){
77481       if( mask==0xffffffff || mask&(1<<iCol) ){
77482         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
77483       }
77484     }
77485
77486     /* Invoke BEFORE DELETE trigger programs. */
77487     sqlite3CodeRowTrigger(pParse, pTrigger, 
77488         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
77489     );
77490
77491     /* Seek the cursor to the row to be deleted again. It may be that
77492     ** the BEFORE triggers coded above have already removed the row
77493     ** being deleted. Do not attempt to delete the row a second time, and 
77494     ** do not fire AFTER triggers.  */
77495     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77496
77497     /* Do FK processing. This call checks that any FK constraints that
77498     ** refer to this table (i.e. constraints attached to other tables) 
77499     ** are not violated by deleting this row.  */
77500     sqlite3FkCheck(pParse, pTab, iOld, 0);
77501   }
77502
77503   /* Delete the index and table entries. Skip this step if pTab is really
77504   ** a view (in which case the only effect of the DELETE statement is to
77505   ** fire the INSTEAD OF triggers).  */ 
77506   if( pTab->pSelect==0 ){
77507     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
77508     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
77509     if( count ){
77510       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
77511     }
77512   }
77513
77514   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
77515   ** handle rows (possibly in other tables) that refer via a foreign key
77516   ** to the row just deleted. */ 
77517   sqlite3FkActions(pParse, pTab, 0, iOld);
77518
77519   /* Invoke AFTER DELETE trigger programs. */
77520   sqlite3CodeRowTrigger(pParse, pTrigger, 
77521       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
77522   );
77523
77524   /* Jump here if the row had already been deleted before any BEFORE
77525   ** trigger programs were invoked. Or if a trigger program throws a 
77526   ** RAISE(IGNORE) exception.  */
77527   sqlite3VdbeResolveLabel(v, iLabel);
77528 }
77529
77530 /*
77531 ** This routine generates VDBE code that causes the deletion of all
77532 ** index entries associated with a single row of a single table.
77533 **
77534 ** The VDBE must be in a particular state when this routine is called.
77535 ** These are the requirements:
77536 **
77537 **   1.  A read/write cursor pointing to pTab, the table containing the row
77538 **       to be deleted, must be opened as cursor number "iCur".
77539 **
77540 **   2.  Read/write cursors for all indices of pTab must be open as
77541 **       cursor number iCur+i for the i-th index.
77542 **
77543 **   3.  The "iCur" cursor must be pointing to the row that is to be
77544 **       deleted.
77545 */
77546 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
77547   Parse *pParse,     /* Parsing and code generating context */
77548   Table *pTab,       /* Table containing the row to be deleted */
77549   int iCur,          /* Cursor number for the table */
77550   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
77551 ){
77552   int i;
77553   Index *pIdx;
77554   int r1;
77555
77556   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77557     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
77558     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
77559     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
77560   }
77561 }
77562
77563 /*
77564 ** Generate code that will assemble an index key and put it in register
77565 ** regOut.  The key with be for index pIdx which is an index on pTab.
77566 ** iCur is the index of a cursor open on the pTab table and pointing to
77567 ** the entry that needs indexing.
77568 **
77569 ** Return a register number which is the first in a block of
77570 ** registers that holds the elements of the index key.  The
77571 ** block of registers has already been deallocated by the time
77572 ** this routine returns.
77573 */
77574 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
77575   Parse *pParse,     /* Parsing context */
77576   Index *pIdx,       /* The index for which to generate a key */
77577   int iCur,          /* Cursor number for the pIdx->pTable table */
77578   int regOut,        /* Write the new index key to this register */
77579   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
77580 ){
77581   Vdbe *v = pParse->pVdbe;
77582   int j;
77583   Table *pTab = pIdx->pTable;
77584   int regBase;
77585   int nCol;
77586
77587   nCol = pIdx->nColumn;
77588   regBase = sqlite3GetTempRange(pParse, nCol+1);
77589   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
77590   for(j=0; j<nCol; j++){
77591     int idx = pIdx->aiColumn[j];
77592     if( idx==pTab->iPKey ){
77593       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
77594     }else{
77595       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
77596       sqlite3ColumnDefault(v, pTab, idx, -1);
77597     }
77598   }
77599   if( doMakeRec ){
77600     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
77601     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
77602   }
77603   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
77604   return regBase;
77605 }
77606
77607 /************** End of delete.c **********************************************/
77608 /************** Begin file func.c ********************************************/
77609 /*
77610 ** 2002 February 23
77611 **
77612 ** The author disclaims copyright to this source code.  In place of
77613 ** a legal notice, here is a blessing:
77614 **
77615 **    May you do good and not evil.
77616 **    May you find forgiveness for yourself and forgive others.
77617 **    May you share freely, never taking more than you give.
77618 **
77619 *************************************************************************
77620 ** This file contains the C functions that implement various SQL
77621 ** functions of SQLite.  
77622 **
77623 ** There is only one exported symbol in this file - the function
77624 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
77625 ** All other code has file scope.
77626 */
77627
77628 /*
77629 ** Return the collating function associated with a function.
77630 */
77631 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
77632   return context->pColl;
77633 }
77634
77635 /*
77636 ** Implementation of the non-aggregate min() and max() functions
77637 */
77638 static void minmaxFunc(
77639   sqlite3_context *context,
77640   int argc,
77641   sqlite3_value **argv
77642 ){
77643   int i;
77644   int mask;    /* 0 for min() or 0xffffffff for max() */
77645   int iBest;
77646   CollSeq *pColl;
77647
77648   assert( argc>1 );
77649   mask = sqlite3_user_data(context)==0 ? 0 : -1;
77650   pColl = sqlite3GetFuncCollSeq(context);
77651   assert( pColl );
77652   assert( mask==-1 || mask==0 );
77653   iBest = 0;
77654   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77655   for(i=1; i<argc; i++){
77656     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
77657     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
77658       testcase( mask==0 );
77659       iBest = i;
77660     }
77661   }
77662   sqlite3_result_value(context, argv[iBest]);
77663 }
77664
77665 /*
77666 ** Return the type of the argument.
77667 */
77668 static void typeofFunc(
77669   sqlite3_context *context,
77670   int NotUsed,
77671   sqlite3_value **argv
77672 ){
77673   const char *z = 0;
77674   UNUSED_PARAMETER(NotUsed);
77675   switch( sqlite3_value_type(argv[0]) ){
77676     case SQLITE_INTEGER: z = "integer"; break;
77677     case SQLITE_TEXT:    z = "text";    break;
77678     case SQLITE_FLOAT:   z = "real";    break;
77679     case SQLITE_BLOB:    z = "blob";    break;
77680     default:             z = "null";    break;
77681   }
77682   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
77683 }
77684
77685
77686 /*
77687 ** Implementation of the length() function
77688 */
77689 static void lengthFunc(
77690   sqlite3_context *context,
77691   int argc,
77692   sqlite3_value **argv
77693 ){
77694   int len;
77695
77696   assert( argc==1 );
77697   UNUSED_PARAMETER(argc);
77698   switch( sqlite3_value_type(argv[0]) ){
77699     case SQLITE_BLOB:
77700     case SQLITE_INTEGER:
77701     case SQLITE_FLOAT: {
77702       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
77703       break;
77704     }
77705     case SQLITE_TEXT: {
77706       const unsigned char *z = sqlite3_value_text(argv[0]);
77707       if( z==0 ) return;
77708       len = 0;
77709       while( *z ){
77710         len++;
77711         SQLITE_SKIP_UTF8(z);
77712       }
77713       sqlite3_result_int(context, len);
77714       break;
77715     }
77716     default: {
77717       sqlite3_result_null(context);
77718       break;
77719     }
77720   }
77721 }
77722
77723 /*
77724 ** Implementation of the abs() function.
77725 **
77726 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
77727 ** the numeric argument X. 
77728 */
77729 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77730   assert( argc==1 );
77731   UNUSED_PARAMETER(argc);
77732   switch( sqlite3_value_type(argv[0]) ){
77733     case SQLITE_INTEGER: {
77734       i64 iVal = sqlite3_value_int64(argv[0]);
77735       if( iVal<0 ){
77736         if( (iVal<<1)==0 ){
77737           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
77738           ** abs(X) throws an integer overflow error since there is no
77739           ** equivalent positive 64-bit two complement value. */
77740           sqlite3_result_error(context, "integer overflow", -1);
77741           return;
77742         }
77743         iVal = -iVal;
77744       } 
77745       sqlite3_result_int64(context, iVal);
77746       break;
77747     }
77748     case SQLITE_NULL: {
77749       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
77750       sqlite3_result_null(context);
77751       break;
77752     }
77753     default: {
77754       /* Because sqlite3_value_double() returns 0.0 if the argument is not
77755       ** something that can be converted into a number, we have:
77756       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
77757       ** cannot be converted to a numeric value. 
77758       */
77759       double rVal = sqlite3_value_double(argv[0]);
77760       if( rVal<0 ) rVal = -rVal;
77761       sqlite3_result_double(context, rVal);
77762       break;
77763     }
77764   }
77765 }
77766
77767 /*
77768 ** Implementation of the substr() function.
77769 **
77770 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
77771 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
77772 ** of x.  If x is text, then we actually count UTF-8 characters.
77773 ** If x is a blob, then we count bytes.
77774 **
77775 ** If p1 is negative, then we begin abs(p1) from the end of x[].
77776 **
77777 ** If p2 is negative, return the p2 characters preceeding p1.
77778 */
77779 static void substrFunc(
77780   sqlite3_context *context,
77781   int argc,
77782   sqlite3_value **argv
77783 ){
77784   const unsigned char *z;
77785   const unsigned char *z2;
77786   int len;
77787   int p0type;
77788   i64 p1, p2;
77789   int negP2 = 0;
77790
77791   assert( argc==3 || argc==2 );
77792   if( sqlite3_value_type(argv[1])==SQLITE_NULL
77793    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
77794   ){
77795     return;
77796   }
77797   p0type = sqlite3_value_type(argv[0]);
77798   p1 = sqlite3_value_int(argv[1]);
77799   if( p0type==SQLITE_BLOB ){
77800     len = sqlite3_value_bytes(argv[0]);
77801     z = sqlite3_value_blob(argv[0]);
77802     if( z==0 ) return;
77803     assert( len==sqlite3_value_bytes(argv[0]) );
77804   }else{
77805     z = sqlite3_value_text(argv[0]);
77806     if( z==0 ) return;
77807     len = 0;
77808     if( p1<0 ){
77809       for(z2=z; *z2; len++){
77810         SQLITE_SKIP_UTF8(z2);
77811       }
77812     }
77813   }
77814   if( argc==3 ){
77815     p2 = sqlite3_value_int(argv[2]);
77816     if( p2<0 ){
77817       p2 = -p2;
77818       negP2 = 1;
77819     }
77820   }else{
77821     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
77822   }
77823   if( p1<0 ){
77824     p1 += len;
77825     if( p1<0 ){
77826       p2 += p1;
77827       if( p2<0 ) p2 = 0;
77828       p1 = 0;
77829     }
77830   }else if( p1>0 ){
77831     p1--;
77832   }else if( p2>0 ){
77833     p2--;
77834   }
77835   if( negP2 ){
77836     p1 -= p2;
77837     if( p1<0 ){
77838       p2 += p1;
77839       p1 = 0;
77840     }
77841   }
77842   assert( p1>=0 && p2>=0 );
77843   if( p0type!=SQLITE_BLOB ){
77844     while( *z && p1 ){
77845       SQLITE_SKIP_UTF8(z);
77846       p1--;
77847     }
77848     for(z2=z; *z2 && p2; p2--){
77849       SQLITE_SKIP_UTF8(z2);
77850     }
77851     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
77852   }else{
77853     if( p1+p2>len ){
77854       p2 = len-p1;
77855       if( p2<0 ) p2 = 0;
77856     }
77857     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
77858   }
77859 }
77860
77861 /*
77862 ** Implementation of the round() function
77863 */
77864 #ifndef SQLITE_OMIT_FLOATING_POINT
77865 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77866   int n = 0;
77867   double r;
77868   char *zBuf;
77869   assert( argc==1 || argc==2 );
77870   if( argc==2 ){
77871     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
77872     n = sqlite3_value_int(argv[1]);
77873     if( n>30 ) n = 30;
77874     if( n<0 ) n = 0;
77875   }
77876   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77877   r = sqlite3_value_double(argv[0]);
77878   /* If Y==0 and X will fit in a 64-bit int,
77879   ** handle the rounding directly,
77880   ** otherwise use printf.
77881   */
77882   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
77883     r = (double)((sqlite_int64)(r+0.5));
77884   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
77885     r = -(double)((sqlite_int64)((-r)+0.5));
77886   }else{
77887     zBuf = sqlite3_mprintf("%.*f",n,r);
77888     if( zBuf==0 ){
77889       sqlite3_result_error_nomem(context);
77890       return;
77891     }
77892     sqlite3AtoF(zBuf, &r);
77893     sqlite3_free(zBuf);
77894   }
77895   sqlite3_result_double(context, r);
77896 }
77897 #endif
77898
77899 /*
77900 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
77901 ** allocation fails, call sqlite3_result_error_nomem() to notify
77902 ** the database handle that malloc() has failed and return NULL.
77903 ** If nByte is larger than the maximum string or blob length, then
77904 ** raise an SQLITE_TOOBIG exception and return NULL.
77905 */
77906 static void *contextMalloc(sqlite3_context *context, i64 nByte){
77907   char *z;
77908   sqlite3 *db = sqlite3_context_db_handle(context);
77909   assert( nByte>0 );
77910   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
77911   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
77912   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77913     sqlite3_result_error_toobig(context);
77914     z = 0;
77915   }else{
77916     z = sqlite3Malloc((int)nByte);
77917     if( !z ){
77918       sqlite3_result_error_nomem(context);
77919     }
77920   }
77921   return z;
77922 }
77923
77924 /*
77925 ** Implementation of the upper() and lower() SQL functions.
77926 */
77927 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77928   char *z1;
77929   const char *z2;
77930   int i, n;
77931   UNUSED_PARAMETER(argc);
77932   z2 = (char*)sqlite3_value_text(argv[0]);
77933   n = sqlite3_value_bytes(argv[0]);
77934   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77935   assert( z2==(char*)sqlite3_value_text(argv[0]) );
77936   if( z2 ){
77937     z1 = contextMalloc(context, ((i64)n)+1);
77938     if( z1 ){
77939       memcpy(z1, z2, n+1);
77940       for(i=0; z1[i]; i++){
77941         z1[i] = (char)sqlite3Toupper(z1[i]);
77942       }
77943       sqlite3_result_text(context, z1, -1, sqlite3_free);
77944     }
77945   }
77946 }
77947 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77948   u8 *z1;
77949   const char *z2;
77950   int i, n;
77951   UNUSED_PARAMETER(argc);
77952   z2 = (char*)sqlite3_value_text(argv[0]);
77953   n = sqlite3_value_bytes(argv[0]);
77954   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77955   assert( z2==(char*)sqlite3_value_text(argv[0]) );
77956   if( z2 ){
77957     z1 = contextMalloc(context, ((i64)n)+1);
77958     if( z1 ){
77959       memcpy(z1, z2, n+1);
77960       for(i=0; z1[i]; i++){
77961         z1[i] = sqlite3Tolower(z1[i]);
77962       }
77963       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
77964     }
77965   }
77966 }
77967
77968
77969 #if 0  /* This function is never used. */
77970 /*
77971 ** The COALESCE() and IFNULL() functions used to be implemented as shown
77972 ** here.  But now they are implemented as VDBE code so that unused arguments
77973 ** do not have to be computed.  This legacy implementation is retained as
77974 ** comment.
77975 */
77976 /*
77977 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
77978 ** All three do the same thing.  They return the first non-NULL
77979 ** argument.
77980 */
77981 static void ifnullFunc(
77982   sqlite3_context *context,
77983   int argc,
77984   sqlite3_value **argv
77985 ){
77986   int i;
77987   for(i=0; i<argc; i++){
77988     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
77989       sqlite3_result_value(context, argv[i]);
77990       break;
77991     }
77992   }
77993 }
77994 #endif /* NOT USED */
77995 #define ifnullFunc versionFunc   /* Substitute function - never called */
77996
77997 /*
77998 ** Implementation of random().  Return a random integer.  
77999 */
78000 static void randomFunc(
78001   sqlite3_context *context,
78002   int NotUsed,
78003   sqlite3_value **NotUsed2
78004 ){
78005   sqlite_int64 r;
78006   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78007   sqlite3_randomness(sizeof(r), &r);
78008   if( r<0 ){
78009     /* We need to prevent a random number of 0x8000000000000000 
78010     ** (or -9223372036854775808) since when you do abs() of that
78011     ** number of you get the same value back again.  To do this
78012     ** in a way that is testable, mask the sign bit off of negative
78013     ** values, resulting in a positive value.  Then take the 
78014     ** 2s complement of that positive value.  The end result can
78015     ** therefore be no less than -9223372036854775807.
78016     */
78017     r = -(r ^ (((sqlite3_int64)1)<<63));
78018   }
78019   sqlite3_result_int64(context, r);
78020 }
78021
78022 /*
78023 ** Implementation of randomblob(N).  Return a random blob
78024 ** that is N bytes long.
78025 */
78026 static void randomBlob(
78027   sqlite3_context *context,
78028   int argc,
78029   sqlite3_value **argv
78030 ){
78031   int n;
78032   unsigned char *p;
78033   assert( argc==1 );
78034   UNUSED_PARAMETER(argc);
78035   n = sqlite3_value_int(argv[0]);
78036   if( n<1 ){
78037     n = 1;
78038   }
78039   p = contextMalloc(context, n);
78040   if( p ){
78041     sqlite3_randomness(n, p);
78042     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
78043   }
78044 }
78045
78046 /*
78047 ** Implementation of the last_insert_rowid() SQL function.  The return
78048 ** value is the same as the sqlite3_last_insert_rowid() API function.
78049 */
78050 static void last_insert_rowid(
78051   sqlite3_context *context, 
78052   int NotUsed, 
78053   sqlite3_value **NotUsed2
78054 ){
78055   sqlite3 *db = sqlite3_context_db_handle(context);
78056   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78057   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
78058   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
78059   ** function. */
78060   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
78061 }
78062
78063 /*
78064 ** Implementation of the changes() SQL function.
78065 **
78066 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
78067 ** around the sqlite3_changes() C/C++ function and hence follows the same
78068 ** rules for counting changes.
78069 */
78070 static void changes(
78071   sqlite3_context *context,
78072   int NotUsed,
78073   sqlite3_value **NotUsed2
78074 ){
78075   sqlite3 *db = sqlite3_context_db_handle(context);
78076   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78077   sqlite3_result_int(context, sqlite3_changes(db));
78078 }
78079
78080 /*
78081 ** Implementation of the total_changes() SQL function.  The return value is
78082 ** the same as the sqlite3_total_changes() API function.
78083 */
78084 static void total_changes(
78085   sqlite3_context *context,
78086   int NotUsed,
78087   sqlite3_value **NotUsed2
78088 ){
78089   sqlite3 *db = sqlite3_context_db_handle(context);
78090   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78091   /* IMP: R-52756-41993 This function is a wrapper around the
78092   ** sqlite3_total_changes() C/C++ interface. */
78093   sqlite3_result_int(context, sqlite3_total_changes(db));
78094 }
78095
78096 /*
78097 ** A structure defining how to do GLOB-style comparisons.
78098 */
78099 struct compareInfo {
78100   u8 matchAll;
78101   u8 matchOne;
78102   u8 matchSet;
78103   u8 noCase;
78104 };
78105
78106 /*
78107 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
78108 ** character is exactly one byte in size.  Also, all characters are
78109 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
78110 ** whereas only characters less than 0x80 do in ASCII.
78111 */
78112 #if defined(SQLITE_EBCDIC)
78113 # define sqlite3Utf8Read(A,C)    (*(A++))
78114 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
78115 #else
78116 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
78117 #endif
78118
78119 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
78120 /* The correct SQL-92 behavior is for the LIKE operator to ignore
78121 ** case.  Thus  'a' LIKE 'A' would be true. */
78122 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
78123 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
78124 ** is case sensitive causing 'a' LIKE 'A' to be false */
78125 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
78126
78127 /*
78128 ** Compare two UTF-8 strings for equality where the first string can
78129 ** potentially be a "glob" expression.  Return true (1) if they
78130 ** are the same and false (0) if they are different.
78131 **
78132 ** Globbing rules:
78133 **
78134 **      '*'       Matches any sequence of zero or more characters.
78135 **
78136 **      '?'       Matches exactly one character.
78137 **
78138 **     [...]      Matches one character from the enclosed list of
78139 **                characters.
78140 **
78141 **     [^...]     Matches one character not in the enclosed list.
78142 **
78143 ** With the [...] and [^...] matching, a ']' character can be included
78144 ** in the list by making it the first character after '[' or '^'.  A
78145 ** range of characters can be specified using '-'.  Example:
78146 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
78147 ** it the last character in the list.
78148 **
78149 ** This routine is usually quick, but can be N**2 in the worst case.
78150 **
78151 ** Hints: to match '*' or '?', put them in "[]".  Like this:
78152 **
78153 **         abc[*]xyz        Matches "abc*xyz" only
78154 */
78155 static int patternCompare(
78156   const u8 *zPattern,              /* The glob pattern */
78157   const u8 *zString,               /* The string to compare against the glob */
78158   const struct compareInfo *pInfo, /* Information about how to do the compare */
78159   const int esc                    /* The escape character */
78160 ){
78161   int c, c2;
78162   int invert;
78163   int seen;
78164   u8 matchOne = pInfo->matchOne;
78165   u8 matchAll = pInfo->matchAll;
78166   u8 matchSet = pInfo->matchSet;
78167   u8 noCase = pInfo->noCase; 
78168   int prevEscape = 0;     /* True if the previous character was 'escape' */
78169
78170   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
78171     if( !prevEscape && c==matchAll ){
78172       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
78173                || c == matchOne ){
78174         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
78175           return 0;
78176         }
78177       }
78178       if( c==0 ){
78179         return 1;
78180       }else if( c==esc ){
78181         c = sqlite3Utf8Read(zPattern, &zPattern);
78182         if( c==0 ){
78183           return 0;
78184         }
78185       }else if( c==matchSet ){
78186         assert( esc==0 );         /* This is GLOB, not LIKE */
78187         assert( matchSet<0x80 );  /* '[' is a single-byte character */
78188         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
78189           SQLITE_SKIP_UTF8(zString);
78190         }
78191         return *zString!=0;
78192       }
78193       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
78194         if( noCase ){
78195           GlogUpperToLower(c2);
78196           GlogUpperToLower(c);
78197           while( c2 != 0 && c2 != c ){
78198             c2 = sqlite3Utf8Read(zString, &zString);
78199             GlogUpperToLower(c2);
78200           }
78201         }else{
78202           while( c2 != 0 && c2 != c ){
78203             c2 = sqlite3Utf8Read(zString, &zString);
78204           }
78205         }
78206         if( c2==0 ) return 0;
78207         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
78208       }
78209       return 0;
78210     }else if( !prevEscape && c==matchOne ){
78211       if( sqlite3Utf8Read(zString, &zString)==0 ){
78212         return 0;
78213       }
78214     }else if( c==matchSet ){
78215       int prior_c = 0;
78216       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
78217       seen = 0;
78218       invert = 0;
78219       c = sqlite3Utf8Read(zString, &zString);
78220       if( c==0 ) return 0;
78221       c2 = sqlite3Utf8Read(zPattern, &zPattern);
78222       if( c2=='^' ){
78223         invert = 1;
78224         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78225       }
78226       if( c2==']' ){
78227         if( c==']' ) seen = 1;
78228         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78229       }
78230       while( c2 && c2!=']' ){
78231         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
78232           c2 = sqlite3Utf8Read(zPattern, &zPattern);
78233           if( c>=prior_c && c<=c2 ) seen = 1;
78234           prior_c = 0;
78235         }else{
78236           if( c==c2 ){
78237             seen = 1;
78238           }
78239           prior_c = c2;
78240         }
78241         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78242       }
78243       if( c2==0 || (seen ^ invert)==0 ){
78244         return 0;
78245       }
78246     }else if( esc==c && !prevEscape ){
78247       prevEscape = 1;
78248     }else{
78249       c2 = sqlite3Utf8Read(zString, &zString);
78250       if( noCase ){
78251         GlogUpperToLower(c);
78252         GlogUpperToLower(c2);
78253       }
78254       if( c!=c2 ){
78255         return 0;
78256       }
78257       prevEscape = 0;
78258     }
78259   }
78260   return *zString==0;
78261 }
78262
78263 /*
78264 ** Count the number of times that the LIKE operator (or GLOB which is
78265 ** just a variation of LIKE) gets called.  This is used for testing
78266 ** only.
78267 */
78268 #ifdef SQLITE_TEST
78269 SQLITE_API int sqlite3_like_count = 0;
78270 #endif
78271
78272
78273 /*
78274 ** Implementation of the like() SQL function.  This function implements
78275 ** the build-in LIKE operator.  The first argument to the function is the
78276 ** pattern and the second argument is the string.  So, the SQL statements:
78277 **
78278 **       A LIKE B
78279 **
78280 ** is implemented as like(B,A).
78281 **
78282 ** This same function (with a different compareInfo structure) computes
78283 ** the GLOB operator.
78284 */
78285 static void likeFunc(
78286   sqlite3_context *context, 
78287   int argc, 
78288   sqlite3_value **argv
78289 ){
78290   const unsigned char *zA, *zB;
78291   int escape = 0;
78292   int nPat;
78293   sqlite3 *db = sqlite3_context_db_handle(context);
78294
78295   zB = sqlite3_value_text(argv[0]);
78296   zA = sqlite3_value_text(argv[1]);
78297
78298   /* Limit the length of the LIKE or GLOB pattern to avoid problems
78299   ** of deep recursion and N*N behavior in patternCompare().
78300   */
78301   nPat = sqlite3_value_bytes(argv[0]);
78302   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
78303   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
78304   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
78305     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
78306     return;
78307   }
78308   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
78309
78310   if( argc==3 ){
78311     /* The escape character string must consist of a single UTF-8 character.
78312     ** Otherwise, return an error.
78313     */
78314     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
78315     if( zEsc==0 ) return;
78316     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
78317       sqlite3_result_error(context, 
78318           "ESCAPE expression must be a single character", -1);
78319       return;
78320     }
78321     escape = sqlite3Utf8Read(zEsc, &zEsc);
78322   }
78323   if( zA && zB ){
78324     struct compareInfo *pInfo = sqlite3_user_data(context);
78325 #ifdef SQLITE_TEST
78326     sqlite3_like_count++;
78327 #endif
78328     
78329     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
78330   }
78331 }
78332
78333 /*
78334 ** Implementation of the NULLIF(x,y) function.  The result is the first
78335 ** argument if the arguments are different.  The result is NULL if the
78336 ** arguments are equal to each other.
78337 */
78338 static void nullifFunc(
78339   sqlite3_context *context,
78340   int NotUsed,
78341   sqlite3_value **argv
78342 ){
78343   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
78344   UNUSED_PARAMETER(NotUsed);
78345   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
78346     sqlite3_result_value(context, argv[0]);
78347   }
78348 }
78349
78350 /*
78351 ** Implementation of the sqlite_version() function.  The result is the version
78352 ** of the SQLite library that is running.
78353 */
78354 static void versionFunc(
78355   sqlite3_context *context,
78356   int NotUsed,
78357   sqlite3_value **NotUsed2
78358 ){
78359   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78360   /* IMP: R-48699-48617 This function is an SQL wrapper around the
78361   ** sqlite3_libversion() C-interface. */
78362   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
78363 }
78364
78365 /*
78366 ** Implementation of the sqlite_source_id() function. The result is a string
78367 ** that identifies the particular version of the source code used to build
78368 ** SQLite.
78369 */
78370 static void sourceidFunc(
78371   sqlite3_context *context,
78372   int NotUsed,
78373   sqlite3_value **NotUsed2
78374 ){
78375   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78376   /* IMP: R-24470-31136 This function is an SQL wrapper around the
78377   ** sqlite3_sourceid() C interface. */
78378   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
78379 }
78380
78381 /*
78382 ** Implementation of the sqlite_compileoption_used() function.
78383 ** The result is an integer that identifies if the compiler option
78384 ** was used to build SQLite.
78385 */
78386 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78387 static void compileoptionusedFunc(
78388   sqlite3_context *context,
78389   int argc,
78390   sqlite3_value **argv
78391 ){
78392   const char *zOptName;
78393   assert( argc==1 );
78394   UNUSED_PARAMETER(argc);
78395   /* IMP: R-xxxx This function is an SQL wrapper around the
78396   ** sqlite3_compileoption_used() C interface. */
78397   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
78398     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
78399   }
78400 }
78401 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78402
78403 /*
78404 ** Implementation of the sqlite_compileoption_get() function. 
78405 ** The result is a string that identifies the compiler options 
78406 ** used to build SQLite.
78407 */
78408 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78409 static void compileoptiongetFunc(
78410   sqlite3_context *context,
78411   int argc,
78412   sqlite3_value **argv
78413 ){
78414   int n;
78415   assert( argc==1 );
78416   UNUSED_PARAMETER(argc);
78417   /* IMP: R-xxxx This function is an SQL wrapper around the
78418   ** sqlite3_compileoption_get() C interface. */
78419   n = sqlite3_value_int(argv[0]);
78420   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
78421 }
78422 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78423
78424 /* Array for converting from half-bytes (nybbles) into ASCII hex
78425 ** digits. */
78426 static const char hexdigits[] = {
78427   '0', '1', '2', '3', '4', '5', '6', '7',
78428   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
78429 };
78430
78431 /*
78432 ** EXPERIMENTAL - This is not an official function.  The interface may
78433 ** change.  This function may disappear.  Do not write code that depends
78434 ** on this function.
78435 **
78436 ** Implementation of the QUOTE() function.  This function takes a single
78437 ** argument.  If the argument is numeric, the return value is the same as
78438 ** the argument.  If the argument is NULL, the return value is the string
78439 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
78440 ** single-quote escapes.
78441 */
78442 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78443   assert( argc==1 );
78444   UNUSED_PARAMETER(argc);
78445   switch( sqlite3_value_type(argv[0]) ){
78446     case SQLITE_INTEGER:
78447     case SQLITE_FLOAT: {
78448       sqlite3_result_value(context, argv[0]);
78449       break;
78450     }
78451     case SQLITE_BLOB: {
78452       char *zText = 0;
78453       char const *zBlob = sqlite3_value_blob(argv[0]);
78454       int nBlob = sqlite3_value_bytes(argv[0]);
78455       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
78456       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
78457       if( zText ){
78458         int i;
78459         for(i=0; i<nBlob; i++){
78460           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
78461           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
78462         }
78463         zText[(nBlob*2)+2] = '\'';
78464         zText[(nBlob*2)+3] = '\0';
78465         zText[0] = 'X';
78466         zText[1] = '\'';
78467         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
78468         sqlite3_free(zText);
78469       }
78470       break;
78471     }
78472     case SQLITE_TEXT: {
78473       int i,j;
78474       u64 n;
78475       const unsigned char *zArg = sqlite3_value_text(argv[0]);
78476       char *z;
78477
78478       if( zArg==0 ) return;
78479       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
78480       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
78481       if( z ){
78482         z[0] = '\'';
78483         for(i=0, j=1; zArg[i]; i++){
78484           z[j++] = zArg[i];
78485           if( zArg[i]=='\'' ){
78486             z[j++] = '\'';
78487           }
78488         }
78489         z[j++] = '\'';
78490         z[j] = 0;
78491         sqlite3_result_text(context, z, j, sqlite3_free);
78492       }
78493       break;
78494     }
78495     default: {
78496       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
78497       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
78498       break;
78499     }
78500   }
78501 }
78502
78503 /*
78504 ** The hex() function.  Interpret the argument as a blob.  Return
78505 ** a hexadecimal rendering as text.
78506 */
78507 static void hexFunc(
78508   sqlite3_context *context,
78509   int argc,
78510   sqlite3_value **argv
78511 ){
78512   int i, n;
78513   const unsigned char *pBlob;
78514   char *zHex, *z;
78515   assert( argc==1 );
78516   UNUSED_PARAMETER(argc);
78517   pBlob = sqlite3_value_blob(argv[0]);
78518   n = sqlite3_value_bytes(argv[0]);
78519   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
78520   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
78521   if( zHex ){
78522     for(i=0; i<n; i++, pBlob++){
78523       unsigned char c = *pBlob;
78524       *(z++) = hexdigits[(c>>4)&0xf];
78525       *(z++) = hexdigits[c&0xf];
78526     }
78527     *z = 0;
78528     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
78529   }
78530 }
78531
78532 /*
78533 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
78534 */
78535 static void zeroblobFunc(
78536   sqlite3_context *context,
78537   int argc,
78538   sqlite3_value **argv
78539 ){
78540   i64 n;
78541   sqlite3 *db = sqlite3_context_db_handle(context);
78542   assert( argc==1 );
78543   UNUSED_PARAMETER(argc);
78544   n = sqlite3_value_int64(argv[0]);
78545   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
78546   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
78547   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78548     sqlite3_result_error_toobig(context);
78549   }else{
78550     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
78551   }
78552 }
78553
78554 /*
78555 ** The replace() function.  Three arguments are all strings: call
78556 ** them A, B, and C. The result is also a string which is derived
78557 ** from A by replacing every occurance of B with C.  The match
78558 ** must be exact.  Collating sequences are not used.
78559 */
78560 static void replaceFunc(
78561   sqlite3_context *context,
78562   int argc,
78563   sqlite3_value **argv
78564 ){
78565   const unsigned char *zStr;        /* The input string A */
78566   const unsigned char *zPattern;    /* The pattern string B */
78567   const unsigned char *zRep;        /* The replacement string C */
78568   unsigned char *zOut;              /* The output */
78569   int nStr;                /* Size of zStr */
78570   int nPattern;            /* Size of zPattern */
78571   int nRep;                /* Size of zRep */
78572   i64 nOut;                /* Maximum size of zOut */
78573   int loopLimit;           /* Last zStr[] that might match zPattern[] */
78574   int i, j;                /* Loop counters */
78575
78576   assert( argc==3 );
78577   UNUSED_PARAMETER(argc);
78578   zStr = sqlite3_value_text(argv[0]);
78579   if( zStr==0 ) return;
78580   nStr = sqlite3_value_bytes(argv[0]);
78581   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
78582   zPattern = sqlite3_value_text(argv[1]);
78583   if( zPattern==0 ){
78584     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
78585             || sqlite3_context_db_handle(context)->mallocFailed );
78586     return;
78587   }
78588   if( zPattern[0]==0 ){
78589     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
78590     sqlite3_result_value(context, argv[0]);
78591     return;
78592   }
78593   nPattern = sqlite3_value_bytes(argv[1]);
78594   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
78595   zRep = sqlite3_value_text(argv[2]);
78596   if( zRep==0 ) return;
78597   nRep = sqlite3_value_bytes(argv[2]);
78598   assert( zRep==sqlite3_value_text(argv[2]) );
78599   nOut = nStr + 1;
78600   assert( nOut<SQLITE_MAX_LENGTH );
78601   zOut = contextMalloc(context, (i64)nOut);
78602   if( zOut==0 ){
78603     return;
78604   }
78605   loopLimit = nStr - nPattern;  
78606   for(i=j=0; i<=loopLimit; i++){
78607     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
78608       zOut[j++] = zStr[i];
78609     }else{
78610       u8 *zOld;
78611       sqlite3 *db = sqlite3_context_db_handle(context);
78612       nOut += nRep - nPattern;
78613       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
78614       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
78615       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78616         sqlite3_result_error_toobig(context);
78617         sqlite3DbFree(db, zOut);
78618         return;
78619       }
78620       zOld = zOut;
78621       zOut = sqlite3_realloc(zOut, (int)nOut);
78622       if( zOut==0 ){
78623         sqlite3_result_error_nomem(context);
78624         sqlite3DbFree(db, zOld);
78625         return;
78626       }
78627       memcpy(&zOut[j], zRep, nRep);
78628       j += nRep;
78629       i += nPattern-1;
78630     }
78631   }
78632   assert( j+nStr-i+1==nOut );
78633   memcpy(&zOut[j], &zStr[i], nStr-i);
78634   j += nStr - i;
78635   assert( j<=nOut );
78636   zOut[j] = 0;
78637   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
78638 }
78639
78640 /*
78641 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
78642 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
78643 */
78644 static void trimFunc(
78645   sqlite3_context *context,
78646   int argc,
78647   sqlite3_value **argv
78648 ){
78649   const unsigned char *zIn;         /* Input string */
78650   const unsigned char *zCharSet;    /* Set of characters to trim */
78651   int nIn;                          /* Number of bytes in input */
78652   int flags;                        /* 1: trimleft  2: trimright  3: trim */
78653   int i;                            /* Loop counter */
78654   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
78655   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
78656   int nChar;                        /* Number of characters in zCharSet */
78657
78658   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
78659     return;
78660   }
78661   zIn = sqlite3_value_text(argv[0]);
78662   if( zIn==0 ) return;
78663   nIn = sqlite3_value_bytes(argv[0]);
78664   assert( zIn==sqlite3_value_text(argv[0]) );
78665   if( argc==1 ){
78666     static const unsigned char lenOne[] = { 1 };
78667     static unsigned char * const azOne[] = { (u8*)" " };
78668     nChar = 1;
78669     aLen = (u8*)lenOne;
78670     azChar = (unsigned char **)azOne;
78671     zCharSet = 0;
78672   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
78673     return;
78674   }else{
78675     const unsigned char *z;
78676     for(z=zCharSet, nChar=0; *z; nChar++){
78677       SQLITE_SKIP_UTF8(z);
78678     }
78679     if( nChar>0 ){
78680       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
78681       if( azChar==0 ){
78682         return;
78683       }
78684       aLen = (unsigned char*)&azChar[nChar];
78685       for(z=zCharSet, nChar=0; *z; nChar++){
78686         azChar[nChar] = (unsigned char *)z;
78687         SQLITE_SKIP_UTF8(z);
78688         aLen[nChar] = (u8)(z - azChar[nChar]);
78689       }
78690     }
78691   }
78692   if( nChar>0 ){
78693     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
78694     if( flags & 1 ){
78695       while( nIn>0 ){
78696         int len = 0;
78697         for(i=0; i<nChar; i++){
78698           len = aLen[i];
78699           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
78700         }
78701         if( i>=nChar ) break;
78702         zIn += len;
78703         nIn -= len;
78704       }
78705     }
78706     if( flags & 2 ){
78707       while( nIn>0 ){
78708         int len = 0;
78709         for(i=0; i<nChar; i++){
78710           len = aLen[i];
78711           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
78712         }
78713         if( i>=nChar ) break;
78714         nIn -= len;
78715       }
78716     }
78717     if( zCharSet ){
78718       sqlite3_free(azChar);
78719     }
78720   }
78721   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
78722 }
78723
78724
78725 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
78726 ** is only available if the SQLITE_SOUNDEX compile-time option is used
78727 ** when SQLite is built.
78728 */
78729 #ifdef SQLITE_SOUNDEX
78730 /*
78731 ** Compute the soundex encoding of a word.
78732 **
78733 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
78734 ** soundex encoding of the string X. 
78735 */
78736 static void soundexFunc(
78737   sqlite3_context *context,
78738   int argc,
78739   sqlite3_value **argv
78740 ){
78741   char zResult[8];
78742   const u8 *zIn;
78743   int i, j;
78744   static const unsigned char iCode[] = {
78745     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78746     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78747     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78748     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78749     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78750     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78751     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78752     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78753   };
78754   assert( argc==1 );
78755   zIn = (u8*)sqlite3_value_text(argv[0]);
78756   if( zIn==0 ) zIn = (u8*)"";
78757   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
78758   if( zIn[i] ){
78759     u8 prevcode = iCode[zIn[i]&0x7f];
78760     zResult[0] = sqlite3Toupper(zIn[i]);
78761     for(j=1; j<4 && zIn[i]; i++){
78762       int code = iCode[zIn[i]&0x7f];
78763       if( code>0 ){
78764         if( code!=prevcode ){
78765           prevcode = code;
78766           zResult[j++] = code + '0';
78767         }
78768       }else{
78769         prevcode = 0;
78770       }
78771     }
78772     while( j<4 ){
78773       zResult[j++] = '0';
78774     }
78775     zResult[j] = 0;
78776     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
78777   }else{
78778     /* IMP: R-64894-50321 The string "?000" is returned if the argument
78779     ** is NULL or contains no ASCII alphabetic characters. */
78780     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
78781   }
78782 }
78783 #endif /* SQLITE_SOUNDEX */
78784
78785 #ifndef SQLITE_OMIT_LOAD_EXTENSION
78786 /*
78787 ** A function that loads a shared-library extension then returns NULL.
78788 */
78789 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
78790   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
78791   const char *zProc;
78792   sqlite3 *db = sqlite3_context_db_handle(context);
78793   char *zErrMsg = 0;
78794
78795   if( argc==2 ){
78796     zProc = (const char *)sqlite3_value_text(argv[1]);
78797   }else{
78798     zProc = 0;
78799   }
78800   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
78801     sqlite3_result_error(context, zErrMsg, -1);
78802     sqlite3_free(zErrMsg);
78803   }
78804 }
78805 #endif
78806
78807
78808 /*
78809 ** An instance of the following structure holds the context of a
78810 ** sum() or avg() aggregate computation.
78811 */
78812 typedef struct SumCtx SumCtx;
78813 struct SumCtx {
78814   double rSum;      /* Floating point sum */
78815   i64 iSum;         /* Integer sum */   
78816   i64 cnt;          /* Number of elements summed */
78817   u8 overflow;      /* True if integer overflow seen */
78818   u8 approx;        /* True if non-integer value was input to the sum */
78819 };
78820
78821 /*
78822 ** Routines used to compute the sum, average, and total.
78823 **
78824 ** The SUM() function follows the (broken) SQL standard which means
78825 ** that it returns NULL if it sums over no inputs.  TOTAL returns
78826 ** 0.0 in that case.  In addition, TOTAL always returns a float where
78827 ** SUM might return an integer if it never encounters a floating point
78828 ** value.  TOTAL never fails, but SUM might through an exception if
78829 ** it overflows an integer.
78830 */
78831 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78832   SumCtx *p;
78833   int type;
78834   assert( argc==1 );
78835   UNUSED_PARAMETER(argc);
78836   p = sqlite3_aggregate_context(context, sizeof(*p));
78837   type = sqlite3_value_numeric_type(argv[0]);
78838   if( p && type!=SQLITE_NULL ){
78839     p->cnt++;
78840     if( type==SQLITE_INTEGER ){
78841       i64 v = sqlite3_value_int64(argv[0]);
78842       p->rSum += v;
78843       if( (p->approx|p->overflow)==0 ){
78844         i64 iNewSum = p->iSum + v;
78845         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
78846         int s2 = (int)(v       >> (sizeof(i64)*8-1));
78847         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
78848         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
78849         p->iSum = iNewSum;
78850       }
78851     }else{
78852       p->rSum += sqlite3_value_double(argv[0]);
78853       p->approx = 1;
78854     }
78855   }
78856 }
78857 static void sumFinalize(sqlite3_context *context){
78858   SumCtx *p;
78859   p = sqlite3_aggregate_context(context, 0);
78860   if( p && p->cnt>0 ){
78861     if( p->overflow ){
78862       sqlite3_result_error(context,"integer overflow",-1);
78863     }else if( p->approx ){
78864       sqlite3_result_double(context, p->rSum);
78865     }else{
78866       sqlite3_result_int64(context, p->iSum);
78867     }
78868   }
78869 }
78870 static void avgFinalize(sqlite3_context *context){
78871   SumCtx *p;
78872   p = sqlite3_aggregate_context(context, 0);
78873   if( p && p->cnt>0 ){
78874     sqlite3_result_double(context, p->rSum/(double)p->cnt);
78875   }
78876 }
78877 static void totalFinalize(sqlite3_context *context){
78878   SumCtx *p;
78879   p = sqlite3_aggregate_context(context, 0);
78880   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78881   sqlite3_result_double(context, p ? p->rSum : (double)0);
78882 }
78883
78884 /*
78885 ** The following structure keeps track of state information for the
78886 ** count() aggregate function.
78887 */
78888 typedef struct CountCtx CountCtx;
78889 struct CountCtx {
78890   i64 n;
78891 };
78892
78893 /*
78894 ** Routines to implement the count() aggregate function.
78895 */
78896 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78897   CountCtx *p;
78898   p = sqlite3_aggregate_context(context, sizeof(*p));
78899   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
78900     p->n++;
78901   }
78902
78903 #ifndef SQLITE_OMIT_DEPRECATED
78904   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
78905   ** sure it still operates correctly, verify that its count agrees with our 
78906   ** internal count when using count(*) and when the total count can be
78907   ** expressed as a 32-bit integer. */
78908   assert( argc==1 || p==0 || p->n>0x7fffffff
78909           || p->n==sqlite3_aggregate_count(context) );
78910 #endif
78911 }   
78912 static void countFinalize(sqlite3_context *context){
78913   CountCtx *p;
78914   p = sqlite3_aggregate_context(context, 0);
78915   sqlite3_result_int64(context, p ? p->n : 0);
78916 }
78917
78918 /*
78919 ** Routines to implement min() and max() aggregate functions.
78920 */
78921 static void minmaxStep(
78922   sqlite3_context *context, 
78923   int NotUsed, 
78924   sqlite3_value **argv
78925 ){
78926   Mem *pArg  = (Mem *)argv[0];
78927   Mem *pBest;
78928   UNUSED_PARAMETER(NotUsed);
78929
78930   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78931   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
78932   if( !pBest ) return;
78933
78934   if( pBest->flags ){
78935     int max;
78936     int cmp;
78937     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
78938     /* This step function is used for both the min() and max() aggregates,
78939     ** the only difference between the two being that the sense of the
78940     ** comparison is inverted. For the max() aggregate, the
78941     ** sqlite3_user_data() function returns (void *)-1. For min() it
78942     ** returns (void *)db, where db is the sqlite3* database pointer.
78943     ** Therefore the next statement sets variable 'max' to 1 for the max()
78944     ** aggregate, or 0 for min().
78945     */
78946     max = sqlite3_user_data(context)!=0;
78947     cmp = sqlite3MemCompare(pBest, pArg, pColl);
78948     if( (max && cmp<0) || (!max && cmp>0) ){
78949       sqlite3VdbeMemCopy(pBest, pArg);
78950     }
78951   }else{
78952     sqlite3VdbeMemCopy(pBest, pArg);
78953   }
78954 }
78955 static void minMaxFinalize(sqlite3_context *context){
78956   sqlite3_value *pRes;
78957   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
78958   if( pRes ){
78959     if( ALWAYS(pRes->flags) ){
78960       sqlite3_result_value(context, pRes);
78961     }
78962     sqlite3VdbeMemRelease(pRes);
78963   }
78964 }
78965
78966 /*
78967 ** group_concat(EXPR, ?SEPARATOR?)
78968 */
78969 static void groupConcatStep(
78970   sqlite3_context *context,
78971   int argc,
78972   sqlite3_value **argv
78973 ){
78974   const char *zVal;
78975   StrAccum *pAccum;
78976   const char *zSep;
78977   int nVal, nSep;
78978   assert( argc==1 || argc==2 );
78979   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78980   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
78981
78982   if( pAccum ){
78983     sqlite3 *db = sqlite3_context_db_handle(context);
78984     int firstTerm = pAccum->useMalloc==0;
78985     pAccum->useMalloc = 1;
78986     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
78987     if( !firstTerm ){
78988       if( argc==2 ){
78989         zSep = (char*)sqlite3_value_text(argv[1]);
78990         nSep = sqlite3_value_bytes(argv[1]);
78991       }else{
78992         zSep = ",";
78993         nSep = 1;
78994       }
78995       sqlite3StrAccumAppend(pAccum, zSep, nSep);
78996     }
78997     zVal = (char*)sqlite3_value_text(argv[0]);
78998     nVal = sqlite3_value_bytes(argv[0]);
78999     sqlite3StrAccumAppend(pAccum, zVal, nVal);
79000   }
79001 }
79002 static void groupConcatFinalize(sqlite3_context *context){
79003   StrAccum *pAccum;
79004   pAccum = sqlite3_aggregate_context(context, 0);
79005   if( pAccum ){
79006     if( pAccum->tooBig ){
79007       sqlite3_result_error_toobig(context);
79008     }else if( pAccum->mallocFailed ){
79009       sqlite3_result_error_nomem(context);
79010     }else{    
79011       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
79012                           sqlite3_free);
79013     }
79014   }
79015 }
79016
79017 /*
79018 ** This routine does per-connection function registration.  Most
79019 ** of the built-in functions above are part of the global function set.
79020 ** This routine only deals with those that are not global.
79021 */
79022 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
79023   int rc = sqlite3_overload_function(db, "MATCH", 2);
79024   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
79025   if( rc==SQLITE_NOMEM ){
79026     db->mallocFailed = 1;
79027   }
79028 }
79029
79030 /*
79031 ** Set the LIKEOPT flag on the 2-argument function with the given name.
79032 */
79033 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
79034   FuncDef *pDef;
79035   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
79036                              2, SQLITE_UTF8, 0);
79037   if( ALWAYS(pDef) ){
79038     pDef->flags = flagVal;
79039   }
79040 }
79041
79042 /*
79043 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
79044 ** parameter determines whether or not the LIKE operator is case
79045 ** sensitive.  GLOB is always case sensitive.
79046 */
79047 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
79048   struct compareInfo *pInfo;
79049   if( caseSensitive ){
79050     pInfo = (struct compareInfo*)&likeInfoAlt;
79051   }else{
79052     pInfo = (struct compareInfo*)&likeInfoNorm;
79053   }
79054   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79055   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79056   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
79057       (struct compareInfo*)&globInfo, likeFunc, 0,0);
79058   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
79059   setLikeOptFlag(db, "like", 
79060       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
79061 }
79062
79063 /*
79064 ** pExpr points to an expression which implements a function.  If
79065 ** it is appropriate to apply the LIKE optimization to that function
79066 ** then set aWc[0] through aWc[2] to the wildcard characters and
79067 ** return TRUE.  If the function is not a LIKE-style function then
79068 ** return FALSE.
79069 */
79070 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
79071   FuncDef *pDef;
79072   if( pExpr->op!=TK_FUNCTION 
79073    || !pExpr->x.pList 
79074    || pExpr->x.pList->nExpr!=2
79075   ){
79076     return 0;
79077   }
79078   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79079   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
79080                              sqlite3Strlen30(pExpr->u.zToken),
79081                              2, SQLITE_UTF8, 0);
79082   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
79083     return 0;
79084   }
79085
79086   /* The memcpy() statement assumes that the wildcard characters are
79087   ** the first three statements in the compareInfo structure.  The
79088   ** asserts() that follow verify that assumption
79089   */
79090   memcpy(aWc, pDef->pUserData, 3);
79091   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
79092   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
79093   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
79094   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
79095   return 1;
79096 }
79097
79098 /*
79099 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
79100 ** to the global function hash table.  This occurs at start-time (as
79101 ** a consequence of calling sqlite3_initialize()).
79102 **
79103 ** After this routine runs
79104 */
79105 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
79106   /*
79107   ** The following array holds FuncDef structures for all of the functions
79108   ** defined in this file.
79109   **
79110   ** The array cannot be constant since changes are made to the
79111   ** FuncDef.pHash elements at start-time.  The elements of this array
79112   ** are read-only after initialization is complete.
79113   */
79114   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
79115     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
79116     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
79117     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
79118     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
79119     FUNCTION(trim,               1, 3, 0, trimFunc         ),
79120     FUNCTION(trim,               2, 3, 0, trimFunc         ),
79121     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
79122     FUNCTION(min,                0, 0, 1, 0                ),
79123     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
79124     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
79125     FUNCTION(max,                0, 1, 1, 0                ),
79126     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
79127     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
79128     FUNCTION(length,             1, 0, 0, lengthFunc       ),
79129     FUNCTION(substr,             2, 0, 0, substrFunc       ),
79130     FUNCTION(substr,             3, 0, 0, substrFunc       ),
79131     FUNCTION(abs,                1, 0, 0, absFunc          ),
79132 #ifndef SQLITE_OMIT_FLOATING_POINT
79133     FUNCTION(round,              1, 0, 0, roundFunc        ),
79134     FUNCTION(round,              2, 0, 0, roundFunc        ),
79135 #endif
79136     FUNCTION(upper,              1, 0, 0, upperFunc        ),
79137     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
79138     FUNCTION(coalesce,           1, 0, 0, 0                ),
79139     FUNCTION(coalesce,           0, 0, 0, 0                ),
79140 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
79141     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
79142     FUNCTION(hex,                1, 0, 0, hexFunc          ),
79143 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
79144     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
79145     FUNCTION(random,             0, 0, 0, randomFunc       ),
79146     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
79147     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
79148     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
79149     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
79150 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79151     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
79152     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
79153 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79154     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
79155     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
79156     FUNCTION(changes,            0, 0, 0, changes          ),
79157     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
79158     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
79159     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
79160   #ifdef SQLITE_SOUNDEX
79161     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
79162   #endif
79163   #ifndef SQLITE_OMIT_LOAD_EXTENSION
79164     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
79165     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
79166   #endif
79167     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
79168     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
79169     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
79170  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
79171     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
79172     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
79173     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
79174     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
79175   
79176     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79177   #ifdef SQLITE_CASE_SENSITIVE_LIKE
79178     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79179     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79180   #else
79181     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
79182     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
79183   #endif
79184   };
79185
79186   int i;
79187   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79188   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
79189
79190   for(i=0; i<ArraySize(aBuiltinFunc); i++){
79191     sqlite3FuncDefInsert(pHash, &aFunc[i]);
79192   }
79193   sqlite3RegisterDateTimeFunctions();
79194 #ifndef SQLITE_OMIT_ALTERTABLE
79195   sqlite3AlterFunctions();
79196 #endif
79197 }
79198
79199 /************** End of func.c ************************************************/
79200 /************** Begin file fkey.c ********************************************/
79201 /*
79202 **
79203 ** The author disclaims copyright to this source code.  In place of
79204 ** a legal notice, here is a blessing:
79205 **
79206 **    May you do good and not evil.
79207 **    May you find forgiveness for yourself and forgive others.
79208 **    May you share freely, never taking more than you give.
79209 **
79210 *************************************************************************
79211 ** This file contains code used by the compiler to add foreign key
79212 ** support to compiled SQL statements.
79213 */
79214
79215 #ifndef SQLITE_OMIT_FOREIGN_KEY
79216 #ifndef SQLITE_OMIT_TRIGGER
79217
79218 /*
79219 ** Deferred and Immediate FKs
79220 ** --------------------------
79221 **
79222 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
79223 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
79224 ** is returned and the current statement transaction rolled back. If a 
79225 ** deferred foreign key constraint is violated, no action is taken 
79226 ** immediately. However if the application attempts to commit the 
79227 ** transaction before fixing the constraint violation, the attempt fails.
79228 **
79229 ** Deferred constraints are implemented using a simple counter associated
79230 ** with the database handle. The counter is set to zero each time a 
79231 ** database transaction is opened. Each time a statement is executed 
79232 ** that causes a foreign key violation, the counter is incremented. Each
79233 ** time a statement is executed that removes an existing violation from
79234 ** the database, the counter is decremented. When the transaction is
79235 ** committed, the commit fails if the current value of the counter is
79236 ** greater than zero. This scheme has two big drawbacks:
79237 **
79238 **   * When a commit fails due to a deferred foreign key constraint, 
79239 **     there is no way to tell which foreign constraint is not satisfied,
79240 **     or which row it is not satisfied for.
79241 **
79242 **   * If the database contains foreign key violations when the 
79243 **     transaction is opened, this may cause the mechanism to malfunction.
79244 **
79245 ** Despite these problems, this approach is adopted as it seems simpler
79246 ** than the alternatives.
79247 **
79248 ** INSERT operations:
79249 **
79250 **   I.1) For each FK for which the table is the child table, search
79251 **        the parent table for a match. If none is found increment the
79252 **        constraint counter.
79253 **
79254 **   I.2) For each FK for which the table is the parent table, 
79255 **        search the child table for rows that correspond to the new
79256 **        row in the parent table. Decrement the counter for each row
79257 **        found (as the constraint is now satisfied).
79258 **
79259 ** DELETE operations:
79260 **
79261 **   D.1) For each FK for which the table is the child table, 
79262 **        search the parent table for a row that corresponds to the 
79263 **        deleted row in the child table. If such a row is not found, 
79264 **        decrement the counter.
79265 **
79266 **   D.2) For each FK for which the table is the parent table, search 
79267 **        the child table for rows that correspond to the deleted row 
79268 **        in the parent table. For each found increment the counter.
79269 **
79270 ** UPDATE operations:
79271 **
79272 **   An UPDATE command requires that all 4 steps above are taken, but only
79273 **   for FK constraints for which the affected columns are actually 
79274 **   modified (values must be compared at runtime).
79275 **
79276 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
79277 ** This simplifies the implementation a bit.
79278 **
79279 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
79280 ** resolution is considered to delete rows before the new row is inserted.
79281 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
79282 ** is thrown, even if the FK constraint would be satisfied after the new 
79283 ** row is inserted.
79284 **
79285 ** Immediate constraints are usually handled similarly. The only difference 
79286 ** is that the counter used is stored as part of each individual statement
79287 ** object (struct Vdbe). If, after the statement has run, its immediate
79288 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
79289 ** and the statement transaction is rolled back. An exception is an INSERT
79290 ** statement that inserts a single row only (no triggers). In this case,
79291 ** instead of using a counter, an exception is thrown immediately if the
79292 ** INSERT violates a foreign key constraint. This is necessary as such
79293 ** an INSERT does not open a statement transaction.
79294 **
79295 ** TODO: How should dropping a table be handled? How should renaming a 
79296 ** table be handled?
79297 **
79298 **
79299 ** Query API Notes
79300 ** ---------------
79301 **
79302 ** Before coding an UPDATE or DELETE row operation, the code-generator
79303 ** for those two operations needs to know whether or not the operation
79304 ** requires any FK processing and, if so, which columns of the original
79305 ** row are required by the FK processing VDBE code (i.e. if FKs were
79306 ** implemented using triggers, which of the old.* columns would be 
79307 ** accessed). No information is required by the code-generator before
79308 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
79309 ** generation code to query for this information are:
79310 **
79311 **   sqlite3FkRequired() - Test to see if FK processing is required.
79312 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
79313 **
79314 **
79315 ** Externally accessible module functions
79316 ** --------------------------------------
79317 **
79318 **   sqlite3FkCheck()    - Check for foreign key violations.
79319 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
79320 **   sqlite3FkDelete()   - Delete an FKey structure.
79321 */
79322
79323 /*
79324 ** VDBE Calling Convention
79325 ** -----------------------
79326 **
79327 ** Example:
79328 **
79329 **   For the following INSERT statement:
79330 **
79331 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
79332 **     INSERT INTO t1 VALUES(1, 2, 3.1);
79333 **
79334 **   Register (x):        2    (type integer)
79335 **   Register (x+1):      1    (type integer)
79336 **   Register (x+2):      NULL (type NULL)
79337 **   Register (x+3):      3.1  (type real)
79338 */
79339
79340 /*
79341 ** A foreign key constraint requires that the key columns in the parent
79342 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
79343 ** Given that pParent is the parent table for foreign key constraint pFKey, 
79344 ** search the schema a unique index on the parent key columns. 
79345 **
79346 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
79347 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
79348 ** is set to point to the unique index. 
79349 ** 
79350 ** If the parent key consists of a single column (the foreign key constraint
79351 ** is not a composite foreign key), output variable *paiCol is set to NULL.
79352 ** Otherwise, it is set to point to an allocated array of size N, where
79353 ** N is the number of columns in the parent key. The first element of the
79354 ** array is the index of the child table column that is mapped by the FK
79355 ** constraint to the parent table column stored in the left-most column
79356 ** of index *ppIdx. The second element of the array is the index of the
79357 ** child table column that corresponds to the second left-most column of
79358 ** *ppIdx, and so on.
79359 **
79360 ** If the required index cannot be found, either because:
79361 **
79362 **   1) The named parent key columns do not exist, or
79363 **
79364 **   2) The named parent key columns do exist, but are not subject to a
79365 **      UNIQUE or PRIMARY KEY constraint, or
79366 **
79367 **   3) No parent key columns were provided explicitly as part of the
79368 **      foreign key definition, and the parent table does not have a
79369 **      PRIMARY KEY, or
79370 **
79371 **   4) No parent key columns were provided explicitly as part of the
79372 **      foreign key definition, and the PRIMARY KEY of the parent table 
79373 **      consists of a a different number of columns to the child key in 
79374 **      the child table.
79375 **
79376 ** then non-zero is returned, and a "foreign key mismatch" error loaded
79377 ** into pParse. If an OOM error occurs, non-zero is returned and the
79378 ** pParse->db->mallocFailed flag is set.
79379 */
79380 static int locateFkeyIndex(
79381   Parse *pParse,                  /* Parse context to store any error in */
79382   Table *pParent,                 /* Parent table of FK constraint pFKey */
79383   FKey *pFKey,                    /* Foreign key to find index for */
79384   Index **ppIdx,                  /* OUT: Unique index on parent table */
79385   int **paiCol                    /* OUT: Map of index columns in pFKey */
79386 ){
79387   Index *pIdx = 0;                    /* Value to return via *ppIdx */
79388   int *aiCol = 0;                     /* Value to return via *paiCol */
79389   int nCol = pFKey->nCol;             /* Number of columns in parent key */
79390   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
79391
79392   /* The caller is responsible for zeroing output parameters. */
79393   assert( ppIdx && *ppIdx==0 );
79394   assert( !paiCol || *paiCol==0 );
79395   assert( pParse );
79396
79397   /* If this is a non-composite (single column) foreign key, check if it 
79398   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
79399   ** and *paiCol set to zero and return early. 
79400   **
79401   ** Otherwise, for a composite foreign key (more than one column), allocate
79402   ** space for the aiCol array (returned via output parameter *paiCol).
79403   ** Non-composite foreign keys do not require the aiCol array.
79404   */
79405   if( nCol==1 ){
79406     /* The FK maps to the IPK if any of the following are true:
79407     **
79408     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
79409     **      mapped to the primary key of table pParent, or
79410     **   2) The FK is explicitly mapped to a column declared as INTEGER
79411     **      PRIMARY KEY.
79412     */
79413     if( pParent->iPKey>=0 ){
79414       if( !zKey ) return 0;
79415       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
79416     }
79417   }else if( paiCol ){
79418     assert( nCol>1 );
79419     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
79420     if( !aiCol ) return 1;
79421     *paiCol = aiCol;
79422   }
79423
79424   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
79425     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
79426       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
79427       ** of columns. If each indexed column corresponds to a foreign key
79428       ** column of pFKey, then this index is a winner.  */
79429
79430       if( zKey==0 ){
79431         /* If zKey is NULL, then this foreign key is implicitly mapped to 
79432         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
79433         ** identified by the test (Index.autoIndex==2).  */
79434         if( pIdx->autoIndex==2 ){
79435           if( aiCol ){
79436             int i;
79437             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
79438           }
79439           break;
79440         }
79441       }else{
79442         /* If zKey is non-NULL, then this foreign key was declared to
79443         ** map to an explicit list of columns in table pParent. Check if this
79444         ** index matches those columns. Also, check that the index uses
79445         ** the default collation sequences for each column. */
79446         int i, j;
79447         for(i=0; i<nCol; i++){
79448           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
79449           char *zDfltColl;                  /* Def. collation for column */
79450           char *zIdxCol;                    /* Name of indexed column */
79451
79452           /* If the index uses a collation sequence that is different from
79453           ** the default collation sequence for the column, this index is
79454           ** unusable. Bail out early in this case.  */
79455           zDfltColl = pParent->aCol[iCol].zColl;
79456           if( !zDfltColl ){
79457             zDfltColl = "BINARY";
79458           }
79459           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
79460
79461           zIdxCol = pParent->aCol[iCol].zName;
79462           for(j=0; j<nCol; j++){
79463             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
79464               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
79465               break;
79466             }
79467           }
79468           if( j==nCol ) break;
79469         }
79470         if( i==nCol ) break;      /* pIdx is usable */
79471       }
79472     }
79473   }
79474
79475   if( !pIdx ){
79476     if( !pParse->disableTriggers ){
79477       sqlite3ErrorMsg(pParse, "foreign key mismatch");
79478     }
79479     sqlite3DbFree(pParse->db, aiCol);
79480     return 1;
79481   }
79482
79483   *ppIdx = pIdx;
79484   return 0;
79485 }
79486
79487 /*
79488 ** This function is called when a row is inserted into or deleted from the 
79489 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
79490 ** on the child table of pFKey, this function is invoked twice for each row
79491 ** affected - once to "delete" the old row, and then again to "insert" the
79492 ** new row.
79493 **
79494 ** Each time it is called, this function generates VDBE code to locate the
79495 ** row in the parent table that corresponds to the row being inserted into 
79496 ** or deleted from the child table. If the parent row can be found, no 
79497 ** special action is taken. Otherwise, if the parent row can *not* be
79498 ** found in the parent table:
79499 **
79500 **   Operation | FK type   | Action taken
79501 **   --------------------------------------------------------------------------
79502 **   INSERT      immediate   Increment the "immediate constraint counter".
79503 **
79504 **   DELETE      immediate   Decrement the "immediate constraint counter".
79505 **
79506 **   INSERT      deferred    Increment the "deferred constraint counter".
79507 **
79508 **   DELETE      deferred    Decrement the "deferred constraint counter".
79509 **
79510 ** These operations are identified in the comment at the top of this file 
79511 ** (fkey.c) as "I.1" and "D.1".
79512 */
79513 static void fkLookupParent(
79514   Parse *pParse,        /* Parse context */
79515   int iDb,              /* Index of database housing pTab */
79516   Table *pTab,          /* Parent table of FK pFKey */
79517   Index *pIdx,          /* Unique index on parent key columns in pTab */
79518   FKey *pFKey,          /* Foreign key constraint */
79519   int *aiCol,           /* Map from parent key columns to child table columns */
79520   int regData,          /* Address of array containing child table row */
79521   int nIncr,            /* Increment constraint counter by this */
79522   int isIgnore          /* If true, pretend pTab contains all NULL values */
79523 ){
79524   int i;                                    /* Iterator variable */
79525   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
79526   int iCur = pParse->nTab - 1;              /* Cursor number to use */
79527   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
79528
79529   /* If nIncr is less than zero, then check at runtime if there are any
79530   ** outstanding constraints to resolve. If there are not, there is no need
79531   ** to check if deleting this row resolves any outstanding violations.
79532   **
79533   ** Check if any of the key columns in the child table row are NULL. If 
79534   ** any are, then the constraint is considered satisfied. No need to 
79535   ** search for a matching row in the parent table.  */
79536   if( nIncr<0 ){
79537     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
79538   }
79539   for(i=0; i<pFKey->nCol; i++){
79540     int iReg = aiCol[i] + regData + 1;
79541     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
79542   }
79543
79544   if( isIgnore==0 ){
79545     if( pIdx==0 ){
79546       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
79547       ** column of the parent table (table pTab).  */
79548       int iMustBeInt;               /* Address of MustBeInt instruction */
79549       int regTemp = sqlite3GetTempReg(pParse);
79550   
79551       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
79552       ** apply the affinity of the parent key). If this fails, then there
79553       ** is no matching parent key. Before using MustBeInt, make a copy of
79554       ** the value. Otherwise, the value inserted into the child key column
79555       ** will have INTEGER affinity applied to it, which may not be correct.  */
79556       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
79557       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
79558   
79559       /* If the parent table is the same as the child table, and we are about
79560       ** to increment the constraint-counter (i.e. this is an INSERT operation),
79561       ** then check if the row being inserted matches itself. If so, do not
79562       ** increment the constraint-counter.  */
79563       if( pTab==pFKey->pFrom && nIncr==1 ){
79564         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
79565       }
79566   
79567       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
79568       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
79569       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79570       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
79571       sqlite3VdbeJumpHere(v, iMustBeInt);
79572       sqlite3ReleaseTempReg(pParse, regTemp);
79573     }else{
79574       int nCol = pFKey->nCol;
79575       int regTemp = sqlite3GetTempRange(pParse, nCol);
79576       int regRec = sqlite3GetTempReg(pParse);
79577       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79578   
79579       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
79580       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
79581       for(i=0; i<nCol; i++){
79582         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
79583       }
79584   
79585       /* If the parent table is the same as the child table, and we are about
79586       ** to increment the constraint-counter (i.e. this is an INSERT operation),
79587       ** then check if the row being inserted matches itself. If so, do not
79588       ** increment the constraint-counter.  */
79589       if( pTab==pFKey->pFrom && nIncr==1 ){
79590         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
79591         for(i=0; i<nCol; i++){
79592           int iChild = aiCol[i]+1+regData;
79593           int iParent = pIdx->aiColumn[i]+1+regData;
79594           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
79595         }
79596         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79597       }
79598   
79599       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
79600       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79601       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
79602   
79603       sqlite3ReleaseTempReg(pParse, regRec);
79604       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
79605     }
79606   }
79607
79608   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79609     /* Special case: If this is an INSERT statement that will insert exactly
79610     ** one row into the table, raise a constraint immediately instead of
79611     ** incrementing a counter. This is necessary as the VM code is being
79612     ** generated for will not open a statement transaction.  */
79613     assert( nIncr==1 );
79614     sqlite3HaltConstraint(
79615         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79616     );
79617   }else{
79618     if( nIncr>0 && pFKey->isDeferred==0 ){
79619       sqlite3ParseToplevel(pParse)->mayAbort = 1;
79620     }
79621     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79622   }
79623
79624   sqlite3VdbeResolveLabel(v, iOk);
79625   sqlite3VdbeAddOp1(v, OP_Close, iCur);
79626 }
79627
79628 /*
79629 ** This function is called to generate code executed when a row is deleted
79630 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
79631 ** deferred, when a row is inserted into the same table. When generating
79632 ** code for an SQL UPDATE operation, this function may be called twice -
79633 ** once to "delete" the old row and once to "insert" the new row.
79634 **
79635 ** The code generated by this function scans through the rows in the child
79636 ** table that correspond to the parent table row being deleted or inserted.
79637 ** For each child row found, one of the following actions is taken:
79638 **
79639 **   Operation | FK type   | Action taken
79640 **   --------------------------------------------------------------------------
79641 **   DELETE      immediate   Increment the "immediate constraint counter".
79642 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79643 **                           throw a "foreign key constraint failed" exception.
79644 **
79645 **   INSERT      immediate   Decrement the "immediate constraint counter".
79646 **
79647 **   DELETE      deferred    Increment the "deferred constraint counter".
79648 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79649 **                           throw a "foreign key constraint failed" exception.
79650 **
79651 **   INSERT      deferred    Decrement the "deferred constraint counter".
79652 **
79653 ** These operations are identified in the comment at the top of this file 
79654 ** (fkey.c) as "I.2" and "D.2".
79655 */
79656 static void fkScanChildren(
79657   Parse *pParse,                  /* Parse context */
79658   SrcList *pSrc,                  /* SrcList containing the table to scan */
79659   Table *pTab,
79660   Index *pIdx,                    /* Foreign key index */
79661   FKey *pFKey,                    /* Foreign key relationship */
79662   int *aiCol,                     /* Map from pIdx cols to child table cols */
79663   int regData,                    /* Referenced table data starts here */
79664   int nIncr                       /* Amount to increment deferred counter by */
79665 ){
79666   sqlite3 *db = pParse->db;       /* Database handle */
79667   int i;                          /* Iterator variable */
79668   Expr *pWhere = 0;               /* WHERE clause to scan with */
79669   NameContext sNameContext;       /* Context used to resolve WHERE clause */
79670   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
79671   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
79672   Vdbe *v = sqlite3GetVdbe(pParse);
79673
79674   assert( !pIdx || pIdx->pTable==pTab );
79675
79676   if( nIncr<0 ){
79677     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
79678   }
79679
79680   /* Create an Expr object representing an SQL expression like:
79681   **
79682   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
79683   **
79684   ** The collation sequence used for the comparison should be that of
79685   ** the parent key columns. The affinity of the parent key column should
79686   ** be applied to each child key value before the comparison takes place.
79687   */
79688   for(i=0; i<pFKey->nCol; i++){
79689     Expr *pLeft;                  /* Value from parent table row */
79690     Expr *pRight;                 /* Column ref to child table */
79691     Expr *pEq;                    /* Expression (pLeft = pRight) */
79692     int iCol;                     /* Index of column in child table */ 
79693     const char *zCol;             /* Name of column in child table */
79694
79695     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79696     if( pLeft ){
79697       /* Set the collation sequence and affinity of the LHS of each TK_EQ
79698       ** expression to the parent key column defaults.  */
79699       if( pIdx ){
79700         Column *pCol;
79701         iCol = pIdx->aiColumn[i];
79702         pCol = &pIdx->pTable->aCol[iCol];
79703         pLeft->iTable = regData+iCol+1;
79704         pLeft->affinity = pCol->affinity;
79705         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
79706       }else{
79707         pLeft->iTable = regData;
79708         pLeft->affinity = SQLITE_AFF_INTEGER;
79709       }
79710     }
79711     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
79712     assert( iCol>=0 );
79713     zCol = pFKey->pFrom->aCol[iCol].zName;
79714     pRight = sqlite3Expr(db, TK_ID, zCol);
79715     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
79716     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79717   }
79718
79719   /* If the child table is the same as the parent table, and this scan
79720   ** is taking place as part of a DELETE operation (operation D.2), omit the
79721   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
79722   ** clause, where $rowid is the rowid of the row being deleted.  */
79723   if( pTab==pFKey->pFrom && nIncr>0 ){
79724     Expr *pEq;                    /* Expression (pLeft = pRight) */
79725     Expr *pLeft;                  /* Value from parent table row */
79726     Expr *pRight;                 /* Column ref to child table */
79727     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79728     pRight = sqlite3Expr(db, TK_COLUMN, 0);
79729     if( pLeft && pRight ){
79730       pLeft->iTable = regData;
79731       pLeft->affinity = SQLITE_AFF_INTEGER;
79732       pRight->iTable = pSrc->a[0].iCursor;
79733       pRight->iColumn = -1;
79734     }
79735     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
79736     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79737   }
79738
79739   /* Resolve the references in the WHERE clause. */
79740   memset(&sNameContext, 0, sizeof(NameContext));
79741   sNameContext.pSrcList = pSrc;
79742   sNameContext.pParse = pParse;
79743   sqlite3ResolveExprNames(&sNameContext, pWhere);
79744
79745   /* Create VDBE to loop through the entries in pSrc that match the WHERE
79746   ** clause. If the constraint is not deferred, throw an exception for
79747   ** each row found. Otherwise, for deferred constraints, increment the
79748   ** deferred constraint counter by nIncr for each row selected.  */
79749   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
79750   if( nIncr>0 && pFKey->isDeferred==0 ){
79751     sqlite3ParseToplevel(pParse)->mayAbort = 1;
79752   }
79753   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79754   if( pWInfo ){
79755     sqlite3WhereEnd(pWInfo);
79756   }
79757
79758   /* Clean up the WHERE clause constructed above. */
79759   sqlite3ExprDelete(db, pWhere);
79760   if( iFkIfZero ){
79761     sqlite3VdbeJumpHere(v, iFkIfZero);
79762   }
79763 }
79764
79765 /*
79766 ** This function returns a pointer to the head of a linked list of FK
79767 ** constraints for which table pTab is the parent table. For example,
79768 ** given the following schema:
79769 **
79770 **   CREATE TABLE t1(a PRIMARY KEY);
79771 **   CREATE TABLE t2(b REFERENCES t1(a);
79772 **
79773 ** Calling this function with table "t1" as an argument returns a pointer
79774 ** to the FKey structure representing the foreign key constraint on table
79775 ** "t2". Calling this function with "t2" as the argument would return a
79776 ** NULL pointer (as there are no FK constraints for which t2 is the parent
79777 ** table).
79778 */
79779 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
79780   int nName = sqlite3Strlen30(pTab->zName);
79781   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
79782 }
79783
79784 /*
79785 ** The second argument is a Trigger structure allocated by the 
79786 ** fkActionTrigger() routine. This function deletes the Trigger structure
79787 ** and all of its sub-components.
79788 **
79789 ** The Trigger structure or any of its sub-components may be allocated from
79790 ** the lookaside buffer belonging to database handle dbMem.
79791 */
79792 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
79793   if( p ){
79794     TriggerStep *pStep = p->step_list;
79795     sqlite3ExprDelete(dbMem, pStep->pWhere);
79796     sqlite3ExprListDelete(dbMem, pStep->pExprList);
79797     sqlite3SelectDelete(dbMem, pStep->pSelect);
79798     sqlite3ExprDelete(dbMem, p->pWhen);
79799     sqlite3DbFree(dbMem, p);
79800   }
79801 }
79802
79803 /*
79804 ** This function is called to generate code that runs when table pTab is
79805 ** being dropped from the database. The SrcList passed as the second argument
79806 ** to this function contains a single entry guaranteed to resolve to
79807 ** table pTab.
79808 **
79809 ** Normally, no code is required. However, if either
79810 **
79811 **   (a) The table is the parent table of a FK constraint, or
79812 **   (b) The table is the child table of a deferred FK constraint and it is
79813 **       determined at runtime that there are outstanding deferred FK 
79814 **       constraint violations in the database,
79815 **
79816 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
79817 ** the table from the database. Triggers are disabled while running this
79818 ** DELETE, but foreign key actions are not.
79819 */
79820 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
79821   sqlite3 *db = pParse->db;
79822   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
79823     int iSkip = 0;
79824     Vdbe *v = sqlite3GetVdbe(pParse);
79825
79826     assert( v );                  /* VDBE has already been allocated */
79827     if( sqlite3FkReferences(pTab)==0 ){
79828       /* Search for a deferred foreign key constraint for which this table
79829       ** is the child table. If one cannot be found, return without 
79830       ** generating any VDBE code. If one can be found, then jump over
79831       ** the entire DELETE if there are no outstanding deferred constraints
79832       ** when this statement is run.  */
79833       FKey *p;
79834       for(p=pTab->pFKey; p; p=p->pNextFrom){
79835         if( p->isDeferred ) break;
79836       }
79837       if( !p ) return;
79838       iSkip = sqlite3VdbeMakeLabel(v);
79839       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
79840     }
79841
79842     pParse->disableTriggers = 1;
79843     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
79844     pParse->disableTriggers = 0;
79845
79846     /* If the DELETE has generated immediate foreign key constraint 
79847     ** violations, halt the VDBE and return an error at this point, before
79848     ** any modifications to the schema are made. This is because statement
79849     ** transactions are not able to rollback schema changes.  */
79850     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
79851     sqlite3HaltConstraint(
79852         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79853     );
79854
79855     if( iSkip ){
79856       sqlite3VdbeResolveLabel(v, iSkip);
79857     }
79858   }
79859 }
79860
79861 /*
79862 ** This function is called when inserting, deleting or updating a row of
79863 ** table pTab to generate VDBE code to perform foreign key constraint 
79864 ** processing for the operation.
79865 **
79866 ** For a DELETE operation, parameter regOld is passed the index of the
79867 ** first register in an array of (pTab->nCol+1) registers containing the
79868 ** rowid of the row being deleted, followed by each of the column values
79869 ** of the row being deleted, from left to right. Parameter regNew is passed
79870 ** zero in this case.
79871 **
79872 ** For an INSERT operation, regOld is passed zero and regNew is passed the
79873 ** first register of an array of (pTab->nCol+1) registers containing the new
79874 ** row data.
79875 **
79876 ** For an UPDATE operation, this function is called twice. Once before
79877 ** the original record is deleted from the table using the calling convention
79878 ** described for DELETE. Then again after the original record is deleted
79879 ** but before the new record is inserted using the INSERT convention. 
79880 */
79881 SQLITE_PRIVATE void sqlite3FkCheck(
79882   Parse *pParse,                  /* Parse context */
79883   Table *pTab,                    /* Row is being deleted from this table */ 
79884   int regOld,                     /* Previous row data is stored here */
79885   int regNew                      /* New row data is stored here */
79886 ){
79887   sqlite3 *db = pParse->db;       /* Database handle */
79888   Vdbe *v;                        /* VM to write code to */
79889   FKey *pFKey;                    /* Used to iterate through FKs */
79890   int iDb;                        /* Index of database containing pTab */
79891   const char *zDb;                /* Name of database containing pTab */
79892   int isIgnoreErrors = pParse->disableTriggers;
79893
79894   /* Exactly one of regOld and regNew should be non-zero. */
79895   assert( (regOld==0)!=(regNew==0) );
79896
79897   /* If foreign-keys are disabled, this function is a no-op. */
79898   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
79899
79900   v = sqlite3GetVdbe(pParse);
79901   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79902   zDb = db->aDb[iDb].zName;
79903
79904   /* Loop through all the foreign key constraints for which pTab is the
79905   ** child table (the table that the foreign key definition is part of).  */
79906   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
79907     Table *pTo;                   /* Parent table of foreign key pFKey */
79908     Index *pIdx = 0;              /* Index on key columns in pTo */
79909     int *aiFree = 0;
79910     int *aiCol;
79911     int iCol;
79912     int i;
79913     int isIgnore = 0;
79914
79915     /* Find the parent table of this foreign key. Also find a unique index 
79916     ** on the parent key columns in the parent table. If either of these 
79917     ** schema items cannot be located, set an error in pParse and return 
79918     ** early.  */
79919     if( pParse->disableTriggers ){
79920       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
79921     }else{
79922       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
79923     }
79924     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
79925       if( !isIgnoreErrors || db->mallocFailed ) return;
79926       continue;
79927     }
79928     assert( pFKey->nCol==1 || (aiFree && pIdx) );
79929
79930     if( aiFree ){
79931       aiCol = aiFree;
79932     }else{
79933       iCol = pFKey->aCol[0].iFrom;
79934       aiCol = &iCol;
79935     }
79936     for(i=0; i<pFKey->nCol; i++){
79937       if( aiCol[i]==pTab->iPKey ){
79938         aiCol[i] = -1;
79939       }
79940 #ifndef SQLITE_OMIT_AUTHORIZATION
79941       /* Request permission to read the parent key columns. If the 
79942       ** authorization callback returns SQLITE_IGNORE, behave as if any
79943       ** values read from the parent table are NULL. */
79944       if( db->xAuth ){
79945         int rcauth;
79946         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
79947         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
79948         isIgnore = (rcauth==SQLITE_IGNORE);
79949       }
79950 #endif
79951     }
79952
79953     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
79954     ** a cursor to use to search the unique index on the parent key columns 
79955     ** in the parent table.  */
79956     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
79957     pParse->nTab++;
79958
79959     if( regOld!=0 ){
79960       /* A row is being removed from the child table. Search for the parent.
79961       ** If the parent does not exist, removing the child row resolves an 
79962       ** outstanding foreign key constraint violation. */
79963       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
79964     }
79965     if( regNew!=0 ){
79966       /* A row is being added to the child table. If a parent row cannot
79967       ** be found, adding the child row has violated the FK constraint. */ 
79968       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
79969     }
79970
79971     sqlite3DbFree(db, aiFree);
79972   }
79973
79974   /* Loop through all the foreign key constraints that refer to this table */
79975   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
79976     Index *pIdx = 0;              /* Foreign key index for pFKey */
79977     SrcList *pSrc;
79978     int *aiCol = 0;
79979
79980     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79981       assert( regOld==0 && regNew!=0 );
79982       /* Inserting a single row into a parent table cannot cause an immediate
79983       ** foreign key violation. So do nothing in this case.  */
79984       continue;
79985     }
79986
79987     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
79988       if( !isIgnoreErrors || db->mallocFailed ) return;
79989       continue;
79990     }
79991     assert( aiCol || pFKey->nCol==1 );
79992
79993     /* Create a SrcList structure containing a single table (the table 
79994     ** the foreign key that refers to this table is attached to). This
79995     ** is required for the sqlite3WhereXXX() interface.  */
79996     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
79997     if( pSrc ){
79998       struct SrcList_item *pItem = pSrc->a;
79999       pItem->pTab = pFKey->pFrom;
80000       pItem->zName = pFKey->pFrom->zName;
80001       pItem->pTab->nRef++;
80002       pItem->iCursor = pParse->nTab++;
80003   
80004       if( regNew!=0 ){
80005         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
80006       }
80007       if( regOld!=0 ){
80008         /* If there is a RESTRICT action configured for the current operation
80009         ** on the parent table of this FK, then throw an exception 
80010         ** immediately if the FK constraint is violated, even if this is a
80011         ** deferred trigger. That's what RESTRICT means. To defer checking
80012         ** the constraint, the FK should specify NO ACTION (represented
80013         ** using OE_None). NO ACTION is the default.  */
80014         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
80015       }
80016       pItem->zName = 0;
80017       sqlite3SrcListDelete(db, pSrc);
80018     }
80019     sqlite3DbFree(db, aiCol);
80020   }
80021 }
80022
80023 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
80024
80025 /*
80026 ** This function is called before generating code to update or delete a 
80027 ** row contained in table pTab.
80028 */
80029 SQLITE_PRIVATE u32 sqlite3FkOldmask(
80030   Parse *pParse,                  /* Parse context */
80031   Table *pTab                     /* Table being modified */
80032 ){
80033   u32 mask = 0;
80034   if( pParse->db->flags&SQLITE_ForeignKeys ){
80035     FKey *p;
80036     int i;
80037     for(p=pTab->pFKey; p; p=p->pNextFrom){
80038       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
80039     }
80040     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80041       Index *pIdx = 0;
80042       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
80043       if( pIdx ){
80044         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
80045       }
80046     }
80047   }
80048   return mask;
80049 }
80050
80051 /*
80052 ** This function is called before generating code to update or delete a 
80053 ** row contained in table pTab. If the operation is a DELETE, then
80054 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
80055 ** to an array of size N, where N is the number of columns in table pTab.
80056 ** If the i'th column is not modified by the UPDATE, then the corresponding 
80057 ** entry in the aChange[] array is set to -1. If the column is modified,
80058 ** the value is 0 or greater. Parameter chngRowid is set to true if the
80059 ** UPDATE statement modifies the rowid fields of the table.
80060 **
80061 ** If any foreign key processing will be required, this function returns
80062 ** true. If there is no foreign key related processing, this function 
80063 ** returns false.
80064 */
80065 SQLITE_PRIVATE int sqlite3FkRequired(
80066   Parse *pParse,                  /* Parse context */
80067   Table *pTab,                    /* Table being modified */
80068   int *aChange,                   /* Non-NULL for UPDATE operations */
80069   int chngRowid                   /* True for UPDATE that affects rowid */
80070 ){
80071   if( pParse->db->flags&SQLITE_ForeignKeys ){
80072     if( !aChange ){
80073       /* A DELETE operation. Foreign key processing is required if the 
80074       ** table in question is either the child or parent table for any 
80075       ** foreign key constraint.  */
80076       return (sqlite3FkReferences(pTab) || pTab->pFKey);
80077     }else{
80078       /* This is an UPDATE. Foreign key processing is only required if the
80079       ** operation modifies one or more child or parent key columns. */
80080       int i;
80081       FKey *p;
80082
80083       /* Check if any child key columns are being modified. */
80084       for(p=pTab->pFKey; p; p=p->pNextFrom){
80085         for(i=0; i<p->nCol; i++){
80086           int iChildKey = p->aCol[i].iFrom;
80087           if( aChange[iChildKey]>=0 ) return 1;
80088           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
80089         }
80090       }
80091
80092       /* Check if any parent key columns are being modified. */
80093       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80094         for(i=0; i<p->nCol; i++){
80095           char *zKey = p->aCol[i].zCol;
80096           int iKey;
80097           for(iKey=0; iKey<pTab->nCol; iKey++){
80098             Column *pCol = &pTab->aCol[iKey];
80099             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
80100               if( aChange[iKey]>=0 ) return 1;
80101               if( iKey==pTab->iPKey && chngRowid ) return 1;
80102             }
80103           }
80104         }
80105       }
80106     }
80107   }
80108   return 0;
80109 }
80110
80111 /*
80112 ** This function is called when an UPDATE or DELETE operation is being 
80113 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
80114 ** If the current operation is an UPDATE, then the pChanges parameter is
80115 ** passed a pointer to the list of columns being modified. If it is a
80116 ** DELETE, pChanges is passed a NULL pointer.
80117 **
80118 ** It returns a pointer to a Trigger structure containing a trigger
80119 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
80120 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
80121 ** returned (these actions require no special handling by the triggers
80122 ** sub-system, code for them is created by fkScanChildren()).
80123 **
80124 ** For example, if pFKey is the foreign key and pTab is table "p" in 
80125 ** the following schema:
80126 **
80127 **   CREATE TABLE p(pk PRIMARY KEY);
80128 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
80129 **
80130 ** then the returned trigger structure is equivalent to:
80131 **
80132 **   CREATE TRIGGER ... DELETE ON p BEGIN
80133 **     DELETE FROM c WHERE ck = old.pk;
80134 **   END;
80135 **
80136 ** The returned pointer is cached as part of the foreign key object. It
80137 ** is eventually freed along with the rest of the foreign key object by 
80138 ** sqlite3FkDelete().
80139 */
80140 static Trigger *fkActionTrigger(
80141   Parse *pParse,                  /* Parse context */
80142   Table *pTab,                    /* Table being updated or deleted from */
80143   FKey *pFKey,                    /* Foreign key to get action for */
80144   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
80145 ){
80146   sqlite3 *db = pParse->db;       /* Database handle */
80147   int action;                     /* One of OE_None, OE_Cascade etc. */
80148   Trigger *pTrigger;              /* Trigger definition to return */
80149   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
80150
80151   action = pFKey->aAction[iAction];
80152   pTrigger = pFKey->apTrigger[iAction];
80153
80154   if( action!=OE_None && !pTrigger ){
80155     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
80156     char const *zFrom;            /* Name of child table */
80157     int nFrom;                    /* Length in bytes of zFrom */
80158     Index *pIdx = 0;              /* Parent key index for this FK */
80159     int *aiCol = 0;               /* child table cols -> parent key cols */
80160     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
80161     Expr *pWhere = 0;             /* WHERE clause of trigger step */
80162     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
80163     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
80164     int i;                        /* Iterator variable */
80165     Expr *pWhen = 0;              /* WHEN clause for the trigger */
80166
80167     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
80168     assert( aiCol || pFKey->nCol==1 );
80169
80170     for(i=0; i<pFKey->nCol; i++){
80171       Token tOld = { "old", 3 };  /* Literal "old" token */
80172       Token tNew = { "new", 3 };  /* Literal "new" token */
80173       Token tFromCol;             /* Name of column in child table */
80174       Token tToCol;               /* Name of column in parent table */
80175       int iFromCol;               /* Idx of column in child table */
80176       Expr *pEq;                  /* tFromCol = OLD.tToCol */
80177
80178       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
80179       assert( iFromCol>=0 );
80180       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
80181       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
80182
80183       tToCol.n = sqlite3Strlen30(tToCol.z);
80184       tFromCol.n = sqlite3Strlen30(tFromCol.z);
80185
80186       /* Create the expression "OLD.zToCol = zFromCol". It is important
80187       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
80188       ** that the affinity and collation sequence associated with the
80189       ** parent table are used for the comparison. */
80190       pEq = sqlite3PExpr(pParse, TK_EQ,
80191           sqlite3PExpr(pParse, TK_DOT, 
80192             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
80193             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
80194           , 0),
80195           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
80196       , 0);
80197       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
80198
80199       /* For ON UPDATE, construct the next term of the WHEN clause.
80200       ** The final WHEN clause will be like this:
80201       **
80202       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
80203       */
80204       if( pChanges ){
80205         pEq = sqlite3PExpr(pParse, TK_IS,
80206             sqlite3PExpr(pParse, TK_DOT, 
80207               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
80208               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
80209               0),
80210             sqlite3PExpr(pParse, TK_DOT, 
80211               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
80212               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
80213               0),
80214             0);
80215         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
80216       }
80217   
80218       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
80219         Expr *pNew;
80220         if( action==OE_Cascade ){
80221           pNew = sqlite3PExpr(pParse, TK_DOT, 
80222             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
80223             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
80224           , 0);
80225         }else if( action==OE_SetDflt ){
80226           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
80227           if( pDflt ){
80228             pNew = sqlite3ExprDup(db, pDflt, 0);
80229           }else{
80230             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
80231           }
80232         }else{
80233           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
80234         }
80235         pList = sqlite3ExprListAppend(pParse, pList, pNew);
80236         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
80237       }
80238     }
80239     sqlite3DbFree(db, aiCol);
80240
80241     zFrom = pFKey->pFrom->zName;
80242     nFrom = sqlite3Strlen30(zFrom);
80243
80244     if( action==OE_Restrict ){
80245       Token tFrom;
80246       Expr *pRaise; 
80247
80248       tFrom.z = zFrom;
80249       tFrom.n = nFrom;
80250       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
80251       if( pRaise ){
80252         pRaise->affinity = OE_Abort;
80253       }
80254       pSelect = sqlite3SelectNew(pParse, 
80255           sqlite3ExprListAppend(pParse, 0, pRaise),
80256           sqlite3SrcListAppend(db, 0, &tFrom, 0),
80257           pWhere,
80258           0, 0, 0, 0, 0, 0
80259       );
80260       pWhere = 0;
80261     }
80262
80263     /* In the current implementation, pTab->dbMem==0 for all tables except
80264     ** for temporary tables used to describe subqueries.  And temporary
80265     ** tables do not have foreign key constraints.  Hence, pTab->dbMem
80266     ** should always be 0 there.
80267     */
80268     enableLookaside = db->lookaside.bEnabled;
80269     db->lookaside.bEnabled = 0;
80270
80271     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
80272         sizeof(Trigger) +         /* struct Trigger */
80273         sizeof(TriggerStep) +     /* Single step in trigger program */
80274         nFrom + 1                 /* Space for pStep->target.z */
80275     );
80276     if( pTrigger ){
80277       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
80278       pStep->target.z = (char *)&pStep[1];
80279       pStep->target.n = nFrom;
80280       memcpy((char *)pStep->target.z, zFrom, nFrom);
80281   
80282       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
80283       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
80284       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
80285       if( pWhen ){
80286         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
80287         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
80288       }
80289     }
80290
80291     /* Re-enable the lookaside buffer, if it was disabled earlier. */
80292     db->lookaside.bEnabled = enableLookaside;
80293
80294     sqlite3ExprDelete(db, pWhere);
80295     sqlite3ExprDelete(db, pWhen);
80296     sqlite3ExprListDelete(db, pList);
80297     sqlite3SelectDelete(db, pSelect);
80298     if( db->mallocFailed==1 ){
80299       fkTriggerDelete(db, pTrigger);
80300       return 0;
80301     }
80302
80303     switch( action ){
80304       case OE_Restrict:
80305         pStep->op = TK_SELECT; 
80306         break;
80307       case OE_Cascade: 
80308         if( !pChanges ){ 
80309           pStep->op = TK_DELETE; 
80310           break; 
80311         }
80312       default:
80313         pStep->op = TK_UPDATE;
80314     }
80315     pStep->pTrig = pTrigger;
80316     pTrigger->pSchema = pTab->pSchema;
80317     pTrigger->pTabSchema = pTab->pSchema;
80318     pFKey->apTrigger[iAction] = pTrigger;
80319     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
80320   }
80321
80322   return pTrigger;
80323 }
80324
80325 /*
80326 ** This function is called when deleting or updating a row to implement
80327 ** any required CASCADE, SET NULL or SET DEFAULT actions.
80328 */
80329 SQLITE_PRIVATE void sqlite3FkActions(
80330   Parse *pParse,                  /* Parse context */
80331   Table *pTab,                    /* Table being updated or deleted from */
80332   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
80333   int regOld                      /* Address of array containing old row */
80334 ){
80335   /* If foreign-key support is enabled, iterate through all FKs that 
80336   ** refer to table pTab. If there is an action associated with the FK 
80337   ** for this operation (either update or delete), invoke the associated 
80338   ** trigger sub-program.  */
80339   if( pParse->db->flags&SQLITE_ForeignKeys ){
80340     FKey *pFKey;                  /* Iterator variable */
80341     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
80342       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
80343       if( pAction ){
80344         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
80345       }
80346     }
80347   }
80348 }
80349
80350 #endif /* ifndef SQLITE_OMIT_TRIGGER */
80351
80352 /*
80353 ** Free all memory associated with foreign key definitions attached to
80354 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
80355 ** hash table.
80356 */
80357 SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
80358   FKey *pFKey;                    /* Iterator variable */
80359   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
80360
80361   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
80362
80363     /* Remove the FK from the fkeyHash hash table. */
80364     if( pFKey->pPrevTo ){
80365       pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
80366     }else{
80367       void *data = (void *)pFKey->pNextTo;
80368       const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
80369       sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
80370     }
80371     if( pFKey->pNextTo ){
80372       pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
80373     }
80374
80375     /* Delete any triggers created to implement actions for this FK. */
80376 #ifndef SQLITE_OMIT_TRIGGER
80377     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
80378     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
80379 #endif
80380
80381     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
80382     ** classified as either immediate or deferred.
80383     */
80384     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
80385
80386     pNext = pFKey->pNextFrom;
80387     sqlite3DbFree(pTab->dbMem, pFKey);
80388   }
80389 }
80390 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
80391
80392 /************** End of fkey.c ************************************************/
80393 /************** Begin file insert.c ******************************************/
80394 /*
80395 ** 2001 September 15
80396 **
80397 ** The author disclaims copyright to this source code.  In place of
80398 ** a legal notice, here is a blessing:
80399 **
80400 **    May you do good and not evil.
80401 **    May you find forgiveness for yourself and forgive others.
80402 **    May you share freely, never taking more than you give.
80403 **
80404 *************************************************************************
80405 ** This file contains C code routines that are called by the parser
80406 ** to handle INSERT statements in SQLite.
80407 */
80408
80409 /*
80410 ** Generate code that will open a table for reading.
80411 */
80412 SQLITE_PRIVATE void sqlite3OpenTable(
80413   Parse *p,       /* Generate code into this VDBE */
80414   int iCur,       /* The cursor number of the table */
80415   int iDb,        /* The database index in sqlite3.aDb[] */
80416   Table *pTab,    /* The table to be opened */
80417   int opcode      /* OP_OpenRead or OP_OpenWrite */
80418 ){
80419   Vdbe *v;
80420   if( IsVirtual(pTab) ) return;
80421   v = sqlite3GetVdbe(p);
80422   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
80423   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
80424   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
80425   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
80426   VdbeComment((v, "%s", pTab->zName));
80427 }
80428
80429 /*
80430 ** Return a pointer to the column affinity string associated with index
80431 ** pIdx. A column affinity string has one character for each column in 
80432 ** the table, according to the affinity of the column:
80433 **
80434 **  Character      Column affinity
80435 **  ------------------------------
80436 **  'a'            TEXT
80437 **  'b'            NONE
80438 **  'c'            NUMERIC
80439 **  'd'            INTEGER
80440 **  'e'            REAL
80441 **
80442 ** An extra 'b' is appended to the end of the string to cover the
80443 ** rowid that appears as the last column in every index.
80444 **
80445 ** Memory for the buffer containing the column index affinity string
80446 ** is managed along with the rest of the Index structure. It will be
80447 ** released when sqlite3DeleteIndex() is called.
80448 */
80449 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
80450   if( !pIdx->zColAff ){
80451     /* The first time a column affinity string for a particular index is
80452     ** required, it is allocated and populated here. It is then stored as
80453     ** a member of the Index structure for subsequent use.
80454     **
80455     ** The column affinity string will eventually be deleted by
80456     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80457     ** up.
80458     */
80459     int n;
80460     Table *pTab = pIdx->pTable;
80461     sqlite3 *db = sqlite3VdbeDb(v);
80462     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
80463     if( !pIdx->zColAff ){
80464       db->mallocFailed = 1;
80465       return 0;
80466     }
80467     for(n=0; n<pIdx->nColumn; n++){
80468       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
80469     }
80470     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
80471     pIdx->zColAff[n] = 0;
80472   }
80473  
80474   return pIdx->zColAff;
80475 }
80476
80477 /*
80478 ** Set P4 of the most recently inserted opcode to a column affinity
80479 ** string for table pTab. A column affinity string has one character
80480 ** for each column indexed by the index, according to the affinity of the
80481 ** column:
80482 **
80483 **  Character      Column affinity
80484 **  ------------------------------
80485 **  'a'            TEXT
80486 **  'b'            NONE
80487 **  'c'            NUMERIC
80488 **  'd'            INTEGER
80489 **  'e'            REAL
80490 */
80491 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
80492   /* The first time a column affinity string for a particular table
80493   ** is required, it is allocated and populated here. It is then 
80494   ** stored as a member of the Table structure for subsequent use.
80495   **
80496   ** The column affinity string will eventually be deleted by
80497   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
80498   */
80499   if( !pTab->zColAff ){
80500     char *zColAff;
80501     int i;
80502     sqlite3 *db = sqlite3VdbeDb(v);
80503
80504     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
80505     if( !zColAff ){
80506       db->mallocFailed = 1;
80507       return;
80508     }
80509
80510     for(i=0; i<pTab->nCol; i++){
80511       zColAff[i] = pTab->aCol[i].affinity;
80512     }
80513     zColAff[pTab->nCol] = '\0';
80514
80515     pTab->zColAff = zColAff;
80516   }
80517
80518   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
80519 }
80520
80521 /*
80522 ** Return non-zero if the table pTab in database iDb or any of its indices
80523 ** have been opened at any point in the VDBE program beginning at location
80524 ** iStartAddr throught the end of the program.  This is used to see if 
80525 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
80526 ** run without using temporary table for the results of the SELECT. 
80527 */
80528 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
80529   Vdbe *v = sqlite3GetVdbe(p);
80530   int i;
80531   int iEnd = sqlite3VdbeCurrentAddr(v);
80532 #ifndef SQLITE_OMIT_VIRTUALTABLE
80533   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
80534 #endif
80535
80536   for(i=iStartAddr; i<iEnd; i++){
80537     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
80538     assert( pOp!=0 );
80539     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
80540       Index *pIndex;
80541       int tnum = pOp->p2;
80542       if( tnum==pTab->tnum ){
80543         return 1;
80544       }
80545       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80546         if( tnum==pIndex->tnum ){
80547           return 1;
80548         }
80549       }
80550     }
80551 #ifndef SQLITE_OMIT_VIRTUALTABLE
80552     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
80553       assert( pOp->p4.pVtab!=0 );
80554       assert( pOp->p4type==P4_VTAB );
80555       return 1;
80556     }
80557 #endif
80558   }
80559   return 0;
80560 }
80561
80562 #ifndef SQLITE_OMIT_AUTOINCREMENT
80563 /*
80564 ** Locate or create an AutoincInfo structure associated with table pTab
80565 ** which is in database iDb.  Return the register number for the register
80566 ** that holds the maximum rowid.
80567 **
80568 ** There is at most one AutoincInfo structure per table even if the
80569 ** same table is autoincremented multiple times due to inserts within
80570 ** triggers.  A new AutoincInfo structure is created if this is the
80571 ** first use of table pTab.  On 2nd and subsequent uses, the original
80572 ** AutoincInfo structure is used.
80573 **
80574 ** Three memory locations are allocated:
80575 **
80576 **   (1)  Register to hold the name of the pTab table.
80577 **   (2)  Register to hold the maximum ROWID of pTab.
80578 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
80579 **
80580 ** The 2nd register is the one that is returned.  That is all the
80581 ** insert routine needs to know about.
80582 */
80583 static int autoIncBegin(
80584   Parse *pParse,      /* Parsing context */
80585   int iDb,            /* Index of the database holding pTab */
80586   Table *pTab         /* The table we are writing to */
80587 ){
80588   int memId = 0;      /* Register holding maximum rowid */
80589   if( pTab->tabFlags & TF_Autoincrement ){
80590     Parse *pToplevel = sqlite3ParseToplevel(pParse);
80591     AutoincInfo *pInfo;
80592
80593     pInfo = pToplevel->pAinc;
80594     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
80595     if( pInfo==0 ){
80596       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
80597       if( pInfo==0 ) return 0;
80598       pInfo->pNext = pToplevel->pAinc;
80599       pToplevel->pAinc = pInfo;
80600       pInfo->pTab = pTab;
80601       pInfo->iDb = iDb;
80602       pToplevel->nMem++;                  /* Register to hold name of table */
80603       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
80604       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
80605     }
80606     memId = pInfo->regCtr;
80607   }
80608   return memId;
80609 }
80610
80611 /*
80612 ** This routine generates code that will initialize all of the
80613 ** register used by the autoincrement tracker.  
80614 */
80615 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
80616   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
80617   sqlite3 *db = pParse->db;  /* The database connection */
80618   Db *pDb;                   /* Database only autoinc table */
80619   int memId;                 /* Register holding max rowid */
80620   int addr;                  /* A VDBE address */
80621   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
80622
80623   /* This routine is never called during trigger-generation.  It is
80624   ** only called from the top-level */
80625   assert( pParse->pTriggerTab==0 );
80626   assert( pParse==sqlite3ParseToplevel(pParse) );
80627
80628   assert( v );   /* We failed long ago if this is not so */
80629   for(p = pParse->pAinc; p; p = p->pNext){
80630     pDb = &db->aDb[p->iDb];
80631     memId = p->regCtr;
80632     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
80633     addr = sqlite3VdbeCurrentAddr(v);
80634     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
80635     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
80636     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
80637     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
80638     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
80639     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80640     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
80641     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
80642     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
80643     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
80644     sqlite3VdbeAddOp0(v, OP_Close);
80645   }
80646 }
80647
80648 /*
80649 ** Update the maximum rowid for an autoincrement calculation.
80650 **
80651 ** This routine should be called when the top of the stack holds a
80652 ** new rowid that is about to be inserted.  If that new rowid is
80653 ** larger than the maximum rowid in the memId memory cell, then the
80654 ** memory cell is updated.  The stack is unchanged.
80655 */
80656 static void autoIncStep(Parse *pParse, int memId, int regRowid){
80657   if( memId>0 ){
80658     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
80659   }
80660 }
80661
80662 /*
80663 ** This routine generates the code needed to write autoincrement
80664 ** maximum rowid values back into the sqlite_sequence register.
80665 ** Every statement that might do an INSERT into an autoincrement
80666 ** table (either directly or through triggers) needs to call this
80667 ** routine just before the "exit" code.
80668 */
80669 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
80670   AutoincInfo *p;
80671   Vdbe *v = pParse->pVdbe;
80672   sqlite3 *db = pParse->db;
80673
80674   assert( v );
80675   for(p = pParse->pAinc; p; p = p->pNext){
80676     Db *pDb = &db->aDb[p->iDb];
80677     int j1, j2, j3, j4, j5;
80678     int iRec;
80679     int memId = p->regCtr;
80680
80681     iRec = sqlite3GetTempReg(pParse);
80682     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
80683     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
80684     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
80685     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
80686     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
80687     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
80688     sqlite3VdbeJumpHere(v, j2);
80689     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
80690     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
80691     sqlite3VdbeJumpHere(v, j4);
80692     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80693     sqlite3VdbeJumpHere(v, j1);
80694     sqlite3VdbeJumpHere(v, j5);
80695     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
80696     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
80697     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80698     sqlite3VdbeAddOp0(v, OP_Close);
80699     sqlite3ReleaseTempReg(pParse, iRec);
80700   }
80701 }
80702 #else
80703 /*
80704 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
80705 ** above are all no-ops
80706 */
80707 # define autoIncBegin(A,B,C) (0)
80708 # define autoIncStep(A,B,C)
80709 #endif /* SQLITE_OMIT_AUTOINCREMENT */
80710
80711
80712 /* Forward declaration */
80713 static int xferOptimization(
80714   Parse *pParse,        /* Parser context */
80715   Table *pDest,         /* The table we are inserting into */
80716   Select *pSelect,      /* A SELECT statement to use as the data source */
80717   int onError,          /* How to handle constraint errors */
80718   int iDbDest           /* The database of pDest */
80719 );
80720
80721 /*
80722 ** This routine is call to handle SQL of the following forms:
80723 **
80724 **    insert into TABLE (IDLIST) values(EXPRLIST)
80725 **    insert into TABLE (IDLIST) select
80726 **
80727 ** The IDLIST following the table name is always optional.  If omitted,
80728 ** then a list of all columns for the table is substituted.  The IDLIST
80729 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
80730 **
80731 ** The pList parameter holds EXPRLIST in the first form of the INSERT
80732 ** statement above, and pSelect is NULL.  For the second form, pList is
80733 ** NULL and pSelect is a pointer to the select statement used to generate
80734 ** data for the insert.
80735 **
80736 ** The code generated follows one of four templates.  For a simple
80737 ** select with data coming from a VALUES clause, the code executes
80738 ** once straight down through.  Pseudo-code follows (we call this
80739 ** the "1st template"):
80740 **
80741 **         open write cursor to <table> and its indices
80742 **         puts VALUES clause expressions onto the stack
80743 **         write the resulting record into <table>
80744 **         cleanup
80745 **
80746 ** The three remaining templates assume the statement is of the form
80747 **
80748 **   INSERT INTO <table> SELECT ...
80749 **
80750 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
80751 ** in other words if the SELECT pulls all columns from a single table
80752 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
80753 ** if <table2> and <table1> are distinct tables but have identical
80754 ** schemas, including all the same indices, then a special optimization
80755 ** is invoked that copies raw records from <table2> over to <table1>.
80756 ** See the xferOptimization() function for the implementation of this
80757 ** template.  This is the 2nd template.
80758 **
80759 **         open a write cursor to <table>
80760 **         open read cursor on <table2>
80761 **         transfer all records in <table2> over to <table>
80762 **         close cursors
80763 **         foreach index on <table>
80764 **           open a write cursor on the <table> index
80765 **           open a read cursor on the corresponding <table2> index
80766 **           transfer all records from the read to the write cursors
80767 **           close cursors
80768 **         end foreach
80769 **
80770 ** The 3rd template is for when the second template does not apply
80771 ** and the SELECT clause does not read from <table> at any time.
80772 ** The generated code follows this template:
80773 **
80774 **         EOF <- 0
80775 **         X <- A
80776 **         goto B
80777 **      A: setup for the SELECT
80778 **         loop over the rows in the SELECT
80779 **           load values into registers R..R+n
80780 **           yield X
80781 **         end loop
80782 **         cleanup after the SELECT
80783 **         EOF <- 1
80784 **         yield X
80785 **         goto A
80786 **      B: open write cursor to <table> and its indices
80787 **      C: yield X
80788 **         if EOF goto D
80789 **         insert the select result into <table> from R..R+n
80790 **         goto C
80791 **      D: cleanup
80792 **
80793 ** The 4th template is used if the insert statement takes its
80794 ** values from a SELECT but the data is being inserted into a table
80795 ** that is also read as part of the SELECT.  In the third form,
80796 ** we have to use a intermediate table to store the results of
80797 ** the select.  The template is like this:
80798 **
80799 **         EOF <- 0
80800 **         X <- A
80801 **         goto B
80802 **      A: setup for the SELECT
80803 **         loop over the tables in the SELECT
80804 **           load value into register R..R+n
80805 **           yield X
80806 **         end loop
80807 **         cleanup after the SELECT
80808 **         EOF <- 1
80809 **         yield X
80810 **         halt-error
80811 **      B: open temp table
80812 **      L: yield X
80813 **         if EOF goto M
80814 **         insert row from R..R+n into temp table
80815 **         goto L
80816 **      M: open write cursor to <table> and its indices
80817 **         rewind temp table
80818 **      C: loop over rows of intermediate table
80819 **           transfer values form intermediate table into <table>
80820 **         end loop
80821 **      D: cleanup
80822 */
80823 SQLITE_PRIVATE void sqlite3Insert(
80824   Parse *pParse,        /* Parser context */
80825   SrcList *pTabList,    /* Name of table into which we are inserting */
80826   ExprList *pList,      /* List of values to be inserted */
80827   Select *pSelect,      /* A SELECT statement to use as the data source */
80828   IdList *pColumn,      /* Column names corresponding to IDLIST. */
80829   int onError           /* How to handle constraint errors */
80830 ){
80831   sqlite3 *db;          /* The main database structure */
80832   Table *pTab;          /* The table to insert into.  aka TABLE */
80833   char *zTab;           /* Name of the table into which we are inserting */
80834   const char *zDb;      /* Name of the database holding this table */
80835   int i, j, idx;        /* Loop counters */
80836   Vdbe *v;              /* Generate code into this virtual machine */
80837   Index *pIdx;          /* For looping over indices of the table */
80838   int nColumn;          /* Number of columns in the data */
80839   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
80840   int baseCur = 0;      /* VDBE Cursor number for pTab */
80841   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
80842   int endOfLoop;        /* Label for the end of the insertion loop */
80843   int useTempTable = 0; /* Store SELECT results in intermediate table */
80844   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
80845   int addrInsTop = 0;   /* Jump to label "D" */
80846   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
80847   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
80848   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
80849   int iDb;              /* Index of database holding TABLE */
80850   Db *pDb;              /* The database containing table being inserted into */
80851   int appendFlag = 0;   /* True if the insert is likely to be an append */
80852
80853   /* Register allocations */
80854   int regFromSelect = 0;/* Base register for data coming from SELECT */
80855   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
80856   int regRowCount = 0;  /* Memory cell used for the row counter */
80857   int regIns;           /* Block of regs holding rowid+data being inserted */
80858   int regRowid;         /* registers holding insert rowid */
80859   int regData;          /* register holding first column to insert */
80860   int regRecord;        /* Holds the assemblied row record */
80861   int regEof = 0;       /* Register recording end of SELECT data */
80862   int *aRegIdx = 0;     /* One register allocated to each index */
80863
80864 #ifndef SQLITE_OMIT_TRIGGER
80865   int isView;                 /* True if attempting to insert into a view */
80866   Trigger *pTrigger;          /* List of triggers on pTab, if required */
80867   int tmask;                  /* Mask of trigger times */
80868 #endif
80869
80870   db = pParse->db;
80871   memset(&dest, 0, sizeof(dest));
80872   if( pParse->nErr || db->mallocFailed ){
80873     goto insert_cleanup;
80874   }
80875
80876   /* Locate the table into which we will be inserting new information.
80877   */
80878   assert( pTabList->nSrc==1 );
80879   zTab = pTabList->a[0].zName;
80880   if( NEVER(zTab==0) ) goto insert_cleanup;
80881   pTab = sqlite3SrcListLookup(pParse, pTabList);
80882   if( pTab==0 ){
80883     goto insert_cleanup;
80884   }
80885   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80886   assert( iDb<db->nDb );
80887   pDb = &db->aDb[iDb];
80888   zDb = pDb->zName;
80889   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
80890     goto insert_cleanup;
80891   }
80892
80893   /* Figure out if we have any triggers and if the table being
80894   ** inserted into is a view
80895   */
80896 #ifndef SQLITE_OMIT_TRIGGER
80897   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
80898   isView = pTab->pSelect!=0;
80899 #else
80900 # define pTrigger 0
80901 # define tmask 0
80902 # define isView 0
80903 #endif
80904 #ifdef SQLITE_OMIT_VIEW
80905 # undef isView
80906 # define isView 0
80907 #endif
80908   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
80909
80910   /* If pTab is really a view, make sure it has been initialized.
80911   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
80912   ** module table).
80913   */
80914   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
80915     goto insert_cleanup;
80916   }
80917
80918   /* Ensure that:
80919   *  (a) the table is not read-only, 
80920   *  (b) that if it is a view then ON INSERT triggers exist
80921   */
80922   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
80923     goto insert_cleanup;
80924   }
80925
80926   /* Allocate a VDBE
80927   */
80928   v = sqlite3GetVdbe(pParse);
80929   if( v==0 ) goto insert_cleanup;
80930   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
80931   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
80932
80933 #ifndef SQLITE_OMIT_XFER_OPT
80934   /* If the statement is of the form
80935   **
80936   **       INSERT INTO <table1> SELECT * FROM <table2>;
80937   **
80938   ** Then special optimizations can be applied that make the transfer
80939   ** very fast and which reduce fragmentation of indices.
80940   **
80941   ** This is the 2nd template.
80942   */
80943   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
80944     assert( !pTrigger );
80945     assert( pList==0 );
80946     goto insert_end;
80947   }
80948 #endif /* SQLITE_OMIT_XFER_OPT */
80949
80950   /* If this is an AUTOINCREMENT table, look up the sequence number in the
80951   ** sqlite_sequence table and store it in memory cell regAutoinc.
80952   */
80953   regAutoinc = autoIncBegin(pParse, iDb, pTab);
80954
80955   /* Figure out how many columns of data are supplied.  If the data
80956   ** is coming from a SELECT statement, then generate a co-routine that
80957   ** produces a single row of the SELECT on each invocation.  The
80958   ** co-routine is the common header to the 3rd and 4th templates.
80959   */
80960   if( pSelect ){
80961     /* Data is coming from a SELECT.  Generate code to implement that SELECT
80962     ** as a co-routine.  The code is common to both the 3rd and 4th
80963     ** templates:
80964     **
80965     **         EOF <- 0
80966     **         X <- A
80967     **         goto B
80968     **      A: setup for the SELECT
80969     **         loop over the tables in the SELECT
80970     **           load value into register R..R+n
80971     **           yield X
80972     **         end loop
80973     **         cleanup after the SELECT
80974     **         EOF <- 1
80975     **         yield X
80976     **         halt-error
80977     **
80978     ** On each invocation of the co-routine, it puts a single row of the
80979     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
80980     ** (These output registers are allocated by sqlite3Select().)  When
80981     ** the SELECT completes, it sets the EOF flag stored in regEof.
80982     */
80983     int rc, j1;
80984
80985     regEof = ++pParse->nMem;
80986     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
80987     VdbeComment((v, "SELECT eof flag"));
80988     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
80989     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
80990     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
80991     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
80992     VdbeComment((v, "Jump over SELECT coroutine"));
80993
80994     /* Resolve the expressions in the SELECT statement and execute it. */
80995     rc = sqlite3Select(pParse, pSelect, &dest);
80996     assert( pParse->nErr==0 || rc );
80997     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
80998       goto insert_cleanup;
80999     }
81000     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
81001     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
81002     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
81003     VdbeComment((v, "End of SELECT coroutine"));
81004     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
81005
81006     regFromSelect = dest.iMem;
81007     assert( pSelect->pEList );
81008     nColumn = pSelect->pEList->nExpr;
81009     assert( dest.nMem==nColumn );
81010
81011     /* Set useTempTable to TRUE if the result of the SELECT statement
81012     ** should be written into a temporary table (template 4).  Set to
81013     ** FALSE if each* row of the SELECT can be written directly into
81014     ** the destination table (template 3).
81015     **
81016     ** A temp table must be used if the table being updated is also one
81017     ** of the tables being read by the SELECT statement.  Also use a 
81018     ** temp table in the case of row triggers.
81019     */
81020     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
81021       useTempTable = 1;
81022     }
81023
81024     if( useTempTable ){
81025       /* Invoke the coroutine to extract information from the SELECT
81026       ** and add it to a transient table srcTab.  The code generated
81027       ** here is from the 4th template:
81028       **
81029       **      B: open temp table
81030       **      L: yield X
81031       **         if EOF goto M
81032       **         insert row from R..R+n into temp table
81033       **         goto L
81034       **      M: ...
81035       */
81036       int regRec;          /* Register to hold packed record */
81037       int regTempRowid;    /* Register to hold temp table ROWID */
81038       int addrTop;         /* Label "L" */
81039       int addrIf;          /* Address of jump to M */
81040
81041       srcTab = pParse->nTab++;
81042       regRec = sqlite3GetTempReg(pParse);
81043       regTempRowid = sqlite3GetTempReg(pParse);
81044       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
81045       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
81046       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
81047       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
81048       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
81049       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
81050       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
81051       sqlite3VdbeJumpHere(v, addrIf);
81052       sqlite3ReleaseTempReg(pParse, regRec);
81053       sqlite3ReleaseTempReg(pParse, regTempRowid);
81054     }
81055   }else{
81056     /* This is the case if the data for the INSERT is coming from a VALUES
81057     ** clause
81058     */
81059     NameContext sNC;
81060     memset(&sNC, 0, sizeof(sNC));
81061     sNC.pParse = pParse;
81062     srcTab = -1;
81063     assert( useTempTable==0 );
81064     nColumn = pList ? pList->nExpr : 0;
81065     for(i=0; i<nColumn; i++){
81066       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
81067         goto insert_cleanup;
81068       }
81069     }
81070   }
81071
81072   /* Make sure the number of columns in the source data matches the number
81073   ** of columns to be inserted into the table.
81074   */
81075   if( IsVirtual(pTab) ){
81076     for(i=0; i<pTab->nCol; i++){
81077       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
81078     }
81079   }
81080   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
81081     sqlite3ErrorMsg(pParse, 
81082        "table %S has %d columns but %d values were supplied",
81083        pTabList, 0, pTab->nCol-nHidden, nColumn);
81084     goto insert_cleanup;
81085   }
81086   if( pColumn!=0 && nColumn!=pColumn->nId ){
81087     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
81088     goto insert_cleanup;
81089   }
81090
81091   /* If the INSERT statement included an IDLIST term, then make sure
81092   ** all elements of the IDLIST really are columns of the table and 
81093   ** remember the column indices.
81094   **
81095   ** If the table has an INTEGER PRIMARY KEY column and that column
81096   ** is named in the IDLIST, then record in the keyColumn variable
81097   ** the index into IDLIST of the primary key column.  keyColumn is
81098   ** the index of the primary key as it appears in IDLIST, not as
81099   ** is appears in the original table.  (The index of the primary
81100   ** key in the original table is pTab->iPKey.)
81101   */
81102   if( pColumn ){
81103     for(i=0; i<pColumn->nId; i++){
81104       pColumn->a[i].idx = -1;
81105     }
81106     for(i=0; i<pColumn->nId; i++){
81107       for(j=0; j<pTab->nCol; j++){
81108         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
81109           pColumn->a[i].idx = j;
81110           if( j==pTab->iPKey ){
81111             keyColumn = i;
81112           }
81113           break;
81114         }
81115       }
81116       if( j>=pTab->nCol ){
81117         if( sqlite3IsRowid(pColumn->a[i].zName) ){
81118           keyColumn = i;
81119         }else{
81120           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
81121               pTabList, 0, pColumn->a[i].zName);
81122           pParse->checkSchema = 1;
81123           goto insert_cleanup;
81124         }
81125       }
81126     }
81127   }
81128
81129   /* If there is no IDLIST term but the table has an integer primary
81130   ** key, the set the keyColumn variable to the primary key column index
81131   ** in the original table definition.
81132   */
81133   if( pColumn==0 && nColumn>0 ){
81134     keyColumn = pTab->iPKey;
81135   }
81136     
81137   /* Initialize the count of rows to be inserted
81138   */
81139   if( db->flags & SQLITE_CountRows ){
81140     regRowCount = ++pParse->nMem;
81141     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
81142   }
81143
81144   /* If this is not a view, open the table and and all indices */
81145   if( !isView ){
81146     int nIdx;
81147
81148     baseCur = pParse->nTab;
81149     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
81150     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
81151     if( aRegIdx==0 ){
81152       goto insert_cleanup;
81153     }
81154     for(i=0; i<nIdx; i++){
81155       aRegIdx[i] = ++pParse->nMem;
81156     }
81157   }
81158
81159   /* This is the top of the main insertion loop */
81160   if( useTempTable ){
81161     /* This block codes the top of loop only.  The complete loop is the
81162     ** following pseudocode (template 4):
81163     **
81164     **         rewind temp table
81165     **      C: loop over rows of intermediate table
81166     **           transfer values form intermediate table into <table>
81167     **         end loop
81168     **      D: ...
81169     */
81170     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
81171     addrCont = sqlite3VdbeCurrentAddr(v);
81172   }else if( pSelect ){
81173     /* This block codes the top of loop only.  The complete loop is the
81174     ** following pseudocode (template 3):
81175     **
81176     **      C: yield X
81177     **         if EOF goto D
81178     **         insert the select result into <table> from R..R+n
81179     **         goto C
81180     **      D: ...
81181     */
81182     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
81183     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
81184   }
81185
81186   /* Allocate registers for holding the rowid of the new row,
81187   ** the content of the new row, and the assemblied row record.
81188   */
81189   regRecord = ++pParse->nMem;
81190   regRowid = regIns = pParse->nMem+1;
81191   pParse->nMem += pTab->nCol + 1;
81192   if( IsVirtual(pTab) ){
81193     regRowid++;
81194     pParse->nMem++;
81195   }
81196   regData = regRowid+1;
81197
81198   /* Run the BEFORE and INSTEAD OF triggers, if there are any
81199   */
81200   endOfLoop = sqlite3VdbeMakeLabel(v);
81201   if( tmask & TRIGGER_BEFORE ){
81202     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
81203
81204     /* build the NEW.* reference row.  Note that if there is an INTEGER
81205     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
81206     ** translated into a unique ID for the row.  But on a BEFORE trigger,
81207     ** we do not know what the unique ID will be (because the insert has
81208     ** not happened yet) so we substitute a rowid of -1
81209     */
81210     if( keyColumn<0 ){
81211       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
81212     }else{
81213       int j1;
81214       if( useTempTable ){
81215         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
81216       }else{
81217         assert( pSelect==0 );  /* Otherwise useTempTable is true */
81218         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
81219       }
81220       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
81221       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
81222       sqlite3VdbeJumpHere(v, j1);
81223       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
81224     }
81225
81226     /* Cannot have triggers on a virtual table. If it were possible,
81227     ** this block would have to account for hidden column.
81228     */
81229     assert( !IsVirtual(pTab) );
81230
81231     /* Create the new column data
81232     */
81233     for(i=0; i<pTab->nCol; i++){
81234       if( pColumn==0 ){
81235         j = i;
81236       }else{
81237         for(j=0; j<pColumn->nId; j++){
81238           if( pColumn->a[j].idx==i ) break;
81239         }
81240       }
81241       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
81242         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
81243       }else if( useTempTable ){
81244         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
81245       }else{
81246         assert( pSelect==0 ); /* Otherwise useTempTable is true */
81247         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
81248       }
81249     }
81250
81251     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
81252     ** do not attempt any conversions before assembling the record.
81253     ** If this is a real table, attempt conversions as required by the
81254     ** table column affinities.
81255     */
81256     if( !isView ){
81257       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
81258       sqlite3TableAffinityStr(v, pTab);
81259     }
81260
81261     /* Fire BEFORE or INSTEAD OF triggers */
81262     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
81263         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
81264
81265     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
81266   }
81267
81268   /* Push the record number for the new entry onto the stack.  The
81269   ** record number is a randomly generate integer created by NewRowid
81270   ** except when the table has an INTEGER PRIMARY KEY column, in which
81271   ** case the record number is the same as that column. 
81272   */
81273   if( !isView ){
81274     if( IsVirtual(pTab) ){
81275       /* The row that the VUpdate opcode will delete: none */
81276       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
81277     }
81278     if( keyColumn>=0 ){
81279       if( useTempTable ){
81280         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
81281       }else if( pSelect ){
81282         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
81283       }else{
81284         VdbeOp *pOp;
81285         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
81286         pOp = sqlite3VdbeGetOp(v, -1);
81287         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
81288           appendFlag = 1;
81289           pOp->opcode = OP_NewRowid;
81290           pOp->p1 = baseCur;
81291           pOp->p2 = regRowid;
81292           pOp->p3 = regAutoinc;
81293         }
81294       }
81295       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
81296       ** to generate a unique primary key value.
81297       */
81298       if( !appendFlag ){
81299         int j1;
81300         if( !IsVirtual(pTab) ){
81301           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
81302           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
81303           sqlite3VdbeJumpHere(v, j1);
81304         }else{
81305           j1 = sqlite3VdbeCurrentAddr(v);
81306           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
81307         }
81308         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
81309       }
81310     }else if( IsVirtual(pTab) ){
81311       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
81312     }else{
81313       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
81314       appendFlag = 1;
81315     }
81316     autoIncStep(pParse, regAutoinc, regRowid);
81317
81318     /* Push onto the stack, data for all columns of the new entry, beginning
81319     ** with the first column.
81320     */
81321     nHidden = 0;
81322     for(i=0; i<pTab->nCol; i++){
81323       int iRegStore = regRowid+1+i;
81324       if( i==pTab->iPKey ){
81325         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
81326         ** Whenever this column is read, the record number will be substituted
81327         ** in its place.  So will fill this column with a NULL to avoid
81328         ** taking up data space with information that will never be used. */
81329         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
81330         continue;
81331       }
81332       if( pColumn==0 ){
81333         if( IsHiddenColumn(&pTab->aCol[i]) ){
81334           assert( IsVirtual(pTab) );
81335           j = -1;
81336           nHidden++;
81337         }else{
81338           j = i - nHidden;
81339         }
81340       }else{
81341         for(j=0; j<pColumn->nId; j++){
81342           if( pColumn->a[j].idx==i ) break;
81343         }
81344       }
81345       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
81346         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
81347       }else if( useTempTable ){
81348         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
81349       }else if( pSelect ){
81350         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
81351       }else{
81352         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
81353       }
81354     }
81355
81356     /* Generate code to check constraints and generate index keys and
81357     ** do the insertion.
81358     */
81359 #ifndef SQLITE_OMIT_VIRTUALTABLE
81360     if( IsVirtual(pTab) ){
81361       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81362       sqlite3VtabMakeWritable(pParse, pTab);
81363       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
81364       sqlite3MayAbort(pParse);
81365     }else
81366 #endif
81367     {
81368       int isReplace;    /* Set to true if constraints may cause a replace */
81369       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
81370           keyColumn>=0, 0, onError, endOfLoop, &isReplace
81371       );
81372       sqlite3FkCheck(pParse, pTab, 0, regIns);
81373       sqlite3CompleteInsertion(
81374           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
81375       );
81376     }
81377   }
81378
81379   /* Update the count of rows that are inserted
81380   */
81381   if( (db->flags & SQLITE_CountRows)!=0 ){
81382     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
81383   }
81384
81385   if( pTrigger ){
81386     /* Code AFTER triggers */
81387     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
81388         pTab, regData-2-pTab->nCol, onError, endOfLoop);
81389   }
81390
81391   /* The bottom of the main insertion loop, if the data source
81392   ** is a SELECT statement.
81393   */
81394   sqlite3VdbeResolveLabel(v, endOfLoop);
81395   if( useTempTable ){
81396     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
81397     sqlite3VdbeJumpHere(v, addrInsTop);
81398     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
81399   }else if( pSelect ){
81400     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
81401     sqlite3VdbeJumpHere(v, addrInsTop);
81402   }
81403
81404   if( !IsVirtual(pTab) && !isView ){
81405     /* Close all tables opened */
81406     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
81407     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
81408       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
81409     }
81410   }
81411
81412 insert_end:
81413   /* Update the sqlite_sequence table by storing the content of the
81414   ** maximum rowid counter values recorded while inserting into
81415   ** autoincrement tables.
81416   */
81417   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81418     sqlite3AutoincrementEnd(pParse);
81419   }
81420
81421   /*
81422   ** Return the number of rows inserted. If this routine is 
81423   ** generating code because of a call to sqlite3NestedParse(), do not
81424   ** invoke the callback function.
81425   */
81426   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81427     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
81428     sqlite3VdbeSetNumCols(v, 1);
81429     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
81430   }
81431
81432 insert_cleanup:
81433   sqlite3SrcListDelete(db, pTabList);
81434   sqlite3ExprListDelete(db, pList);
81435   sqlite3SelectDelete(db, pSelect);
81436   sqlite3IdListDelete(db, pColumn);
81437   sqlite3DbFree(db, aRegIdx);
81438 }
81439
81440 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81441 ** thely may interfere with compilation of other functions in this file
81442 ** (or in another file, if this file becomes part of the amalgamation).  */
81443 #ifdef isView
81444  #undef isView
81445 #endif
81446 #ifdef pTrigger
81447  #undef pTrigger
81448 #endif
81449 #ifdef tmask
81450  #undef tmask
81451 #endif
81452
81453
81454 /*
81455 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
81456 **
81457 ** The input is a range of consecutive registers as follows:
81458 **
81459 **    1.  The rowid of the row after the update.
81460 **
81461 **    2.  The data in the first column of the entry after the update.
81462 **
81463 **    i.  Data from middle columns...
81464 **
81465 **    N.  The data in the last column of the entry after the update.
81466 **
81467 ** The regRowid parameter is the index of the register containing (1).
81468 **
81469 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
81470 ** the address of a register containing the rowid before the update takes
81471 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
81472 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
81473 ** indicates that the rowid was explicitly specified as part of the
81474 ** INSERT statement. If rowidChng is false, it means that  the rowid is
81475 ** computed automatically in an insert or that the rowid value is not 
81476 ** modified by an update.
81477 **
81478 ** The code generated by this routine store new index entries into
81479 ** registers identified by aRegIdx[].  No index entry is created for
81480 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
81481 ** the same as the order of indices on the linked list of indices
81482 ** attached to the table.
81483 **
81484 ** This routine also generates code to check constraints.  NOT NULL,
81485 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
81486 ** then the appropriate action is performed.  There are five possible
81487 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
81488 **
81489 **  Constraint type  Action       What Happens
81490 **  ---------------  ----------   ----------------------------------------
81491 **  any              ROLLBACK     The current transaction is rolled back and
81492 **                                sqlite3_exec() returns immediately with a
81493 **                                return code of SQLITE_CONSTRAINT.
81494 **
81495 **  any              ABORT        Back out changes from the current command
81496 **                                only (do not do a complete rollback) then
81497 **                                cause sqlite3_exec() to return immediately
81498 **                                with SQLITE_CONSTRAINT.
81499 **
81500 **  any              FAIL         Sqlite_exec() returns immediately with a
81501 **                                return code of SQLITE_CONSTRAINT.  The
81502 **                                transaction is not rolled back and any
81503 **                                prior changes are retained.
81504 **
81505 **  any              IGNORE       The record number and data is popped from
81506 **                                the stack and there is an immediate jump
81507 **                                to label ignoreDest.
81508 **
81509 **  NOT NULL         REPLACE      The NULL value is replace by the default
81510 **                                value for that column.  If the default value
81511 **                                is NULL, the action is the same as ABORT.
81512 **
81513 **  UNIQUE           REPLACE      The other row that conflicts with the row
81514 **                                being inserted is removed.
81515 **
81516 **  CHECK            REPLACE      Illegal.  The results in an exception.
81517 **
81518 ** Which action to take is determined by the overrideError parameter.
81519 ** Or if overrideError==OE_Default, then the pParse->onError parameter
81520 ** is used.  Or if pParse->onError==OE_Default then the onError value
81521 ** for the constraint is used.
81522 **
81523 ** The calling routine must open a read/write cursor for pTab with
81524 ** cursor number "baseCur".  All indices of pTab must also have open
81525 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
81526 ** Except, if there is no possibility of a REPLACE action then
81527 ** cursors do not need to be open for indices where aRegIdx[i]==0.
81528 */
81529 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
81530   Parse *pParse,      /* The parser context */
81531   Table *pTab,        /* the table into which we are inserting */
81532   int baseCur,        /* Index of a read/write cursor pointing at pTab */
81533   int regRowid,       /* Index of the range of input registers */
81534   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81535   int rowidChng,      /* True if the rowid might collide with existing entry */
81536   int isUpdate,       /* True for UPDATE, False for INSERT */
81537   int overrideError,  /* Override onError to this if not OE_Default */
81538   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
81539   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
81540 ){
81541   int i;              /* loop counter */
81542   Vdbe *v;            /* VDBE under constrution */
81543   int nCol;           /* Number of columns */
81544   int onError;        /* Conflict resolution strategy */
81545   int j1;             /* Addresss of jump instruction */
81546   int j2 = 0, j3;     /* Addresses of jump instructions */
81547   int regData;        /* Register containing first data column */
81548   int iCur;           /* Table cursor number */
81549   Index *pIdx;         /* Pointer to one of the indices */
81550   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
81551   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
81552
81553   v = sqlite3GetVdbe(pParse);
81554   assert( v!=0 );
81555   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81556   nCol = pTab->nCol;
81557   regData = regRowid + 1;
81558
81559   /* Test all NOT NULL constraints.
81560   */
81561   for(i=0; i<nCol; i++){
81562     if( i==pTab->iPKey ){
81563       continue;
81564     }
81565     onError = pTab->aCol[i].notNull;
81566     if( onError==OE_None ) continue;
81567     if( overrideError!=OE_Default ){
81568       onError = overrideError;
81569     }else if( onError==OE_Default ){
81570       onError = OE_Abort;
81571     }
81572     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
81573       onError = OE_Abort;
81574     }
81575     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81576         || onError==OE_Ignore || onError==OE_Replace );
81577     switch( onError ){
81578       case OE_Abort:
81579         sqlite3MayAbort(pParse);
81580       case OE_Rollback:
81581       case OE_Fail: {
81582         char *zMsg;
81583         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
81584                                   SQLITE_CONSTRAINT, onError, regData+i);
81585         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
81586                               pTab->zName, pTab->aCol[i].zName);
81587         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
81588         break;
81589       }
81590       case OE_Ignore: {
81591         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
81592         break;
81593       }
81594       default: {
81595         assert( onError==OE_Replace );
81596         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
81597         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
81598         sqlite3VdbeJumpHere(v, j1);
81599         break;
81600       }
81601     }
81602   }
81603
81604   /* Test all CHECK constraints
81605   */
81606 #ifndef SQLITE_OMIT_CHECK
81607   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
81608     int allOk = sqlite3VdbeMakeLabel(v);
81609     pParse->ckBase = regData;
81610     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
81611     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
81612     if( onError==OE_Ignore ){
81613       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81614     }else{
81615       sqlite3HaltConstraint(pParse, onError, 0, 0);
81616     }
81617     sqlite3VdbeResolveLabel(v, allOk);
81618   }
81619 #endif /* !defined(SQLITE_OMIT_CHECK) */
81620
81621   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
81622   ** of the new record does not previously exist.  Except, if this
81623   ** is an UPDATE and the primary key is not changing, that is OK.
81624   */
81625   if( rowidChng ){
81626     onError = pTab->keyConf;
81627     if( overrideError!=OE_Default ){
81628       onError = overrideError;
81629     }else if( onError==OE_Default ){
81630       onError = OE_Abort;
81631     }
81632     
81633     if( isUpdate ){
81634       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
81635     }
81636     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
81637     switch( onError ){
81638       default: {
81639         onError = OE_Abort;
81640         /* Fall thru into the next case */
81641       }
81642       case OE_Rollback:
81643       case OE_Abort:
81644       case OE_Fail: {
81645         sqlite3HaltConstraint(
81646           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
81647         break;
81648       }
81649       case OE_Replace: {
81650         /* If there are DELETE triggers on this table and the
81651         ** recursive-triggers flag is set, call GenerateRowDelete() to
81652         ** remove the conflicting row from the the table. This will fire
81653         ** the triggers and remove both the table and index b-tree entries.
81654         **
81655         ** Otherwise, if there are no triggers or the recursive-triggers
81656         ** flag is not set, but the table has one or more indexes, call 
81657         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
81658         ** only. The table b-tree entry will be replaced by the new entry 
81659         ** when it is inserted.  
81660         **
81661         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
81662         ** also invoke MultiWrite() to indicate that this VDBE may require
81663         ** statement rollback (if the statement is aborted after the delete
81664         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
81665         ** but being more selective here allows statements like:
81666         **
81667         **   REPLACE INTO t(rowid) VALUES($newrowid)
81668         **
81669         ** to run without a statement journal if there are no indexes on the
81670         ** table.
81671         */
81672         Trigger *pTrigger = 0;
81673         if( pParse->db->flags&SQLITE_RecTriggers ){
81674           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81675         }
81676         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
81677           sqlite3MultiWrite(pParse);
81678           sqlite3GenerateRowDelete(
81679               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
81680           );
81681         }else if( pTab->pIndex ){
81682           sqlite3MultiWrite(pParse);
81683           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
81684         }
81685         seenReplace = 1;
81686         break;
81687       }
81688       case OE_Ignore: {
81689         assert( seenReplace==0 );
81690         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81691         break;
81692       }
81693     }
81694     sqlite3VdbeJumpHere(v, j3);
81695     if( isUpdate ){
81696       sqlite3VdbeJumpHere(v, j2);
81697     }
81698   }
81699
81700   /* Test all UNIQUE constraints by creating entries for each UNIQUE
81701   ** index and making sure that duplicate entries do not already exist.
81702   ** Add the new records to the indices as we go.
81703   */
81704   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
81705     int regIdx;
81706     int regR;
81707
81708     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
81709
81710     /* Create a key for accessing the index entry */
81711     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
81712     for(i=0; i<pIdx->nColumn; i++){
81713       int idx = pIdx->aiColumn[i];
81714       if( idx==pTab->iPKey ){
81715         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81716       }else{
81717         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
81718       }
81719     }
81720     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81721     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
81722     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81723     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
81724
81725     /* Find out what action to take in case there is an indexing conflict */
81726     onError = pIdx->onError;
81727     if( onError==OE_None ){ 
81728       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81729       continue;  /* pIdx is not a UNIQUE index */
81730     }
81731     if( overrideError!=OE_Default ){
81732       onError = overrideError;
81733     }else if( onError==OE_Default ){
81734       onError = OE_Abort;
81735     }
81736     if( seenReplace ){
81737       if( onError==OE_Ignore ) onError = OE_Replace;
81738       else if( onError==OE_Fail ) onError = OE_Abort;
81739     }
81740     
81741     /* Check to see if the new index entry will be unique */
81742     regR = sqlite3GetTempReg(pParse);
81743     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
81744     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
81745                            regR, SQLITE_INT_TO_PTR(regIdx),
81746                            P4_INT32);
81747     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81748
81749     /* Generate code that executes if the new index entry is not unique */
81750     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81751         || onError==OE_Ignore || onError==OE_Replace );
81752     switch( onError ){
81753       case OE_Rollback:
81754       case OE_Abort:
81755       case OE_Fail: {
81756         int j;
81757         StrAccum errMsg;
81758         const char *zSep;
81759         char *zErr;
81760
81761         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
81762         errMsg.db = pParse->db;
81763         zSep = pIdx->nColumn>1 ? "columns " : "column ";
81764         for(j=0; j<pIdx->nColumn; j++){
81765           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
81766           sqlite3StrAccumAppend(&errMsg, zSep, -1);
81767           zSep = ", ";
81768           sqlite3StrAccumAppend(&errMsg, zCol, -1);
81769         }
81770         sqlite3StrAccumAppend(&errMsg,
81771             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
81772         zErr = sqlite3StrAccumFinish(&errMsg);
81773         sqlite3HaltConstraint(pParse, onError, zErr, 0);
81774         sqlite3DbFree(errMsg.db, zErr);
81775         break;
81776       }
81777       case OE_Ignore: {
81778         assert( seenReplace==0 );
81779         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81780         break;
81781       }
81782       default: {
81783         Trigger *pTrigger = 0;
81784         assert( onError==OE_Replace );
81785         sqlite3MultiWrite(pParse);
81786         if( pParse->db->flags&SQLITE_RecTriggers ){
81787           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81788         }
81789         sqlite3GenerateRowDelete(
81790             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
81791         );
81792         seenReplace = 1;
81793         break;
81794       }
81795     }
81796     sqlite3VdbeJumpHere(v, j3);
81797     sqlite3ReleaseTempReg(pParse, regR);
81798   }
81799   
81800   if( pbMayReplace ){
81801     *pbMayReplace = seenReplace;
81802   }
81803 }
81804
81805 /*
81806 ** This routine generates code to finish the INSERT or UPDATE operation
81807 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
81808 ** A consecutive range of registers starting at regRowid contains the
81809 ** rowid and the content to be inserted.
81810 **
81811 ** The arguments to this routine should be the same as the first six
81812 ** arguments to sqlite3GenerateConstraintChecks.
81813 */
81814 SQLITE_PRIVATE void sqlite3CompleteInsertion(
81815   Parse *pParse,      /* The parser context */
81816   Table *pTab,        /* the table into which we are inserting */
81817   int baseCur,        /* Index of a read/write cursor pointing at pTab */
81818   int regRowid,       /* Range of content */
81819   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81820   int isUpdate,       /* True for UPDATE, False for INSERT */
81821   int appendBias,     /* True if this is likely to be an append */
81822   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
81823 ){
81824   int i;
81825   Vdbe *v;
81826   int nIdx;
81827   Index *pIdx;
81828   u8 pik_flags;
81829   int regData;
81830   int regRec;
81831
81832   v = sqlite3GetVdbe(pParse);
81833   assert( v!=0 );
81834   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81835   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
81836   for(i=nIdx-1; i>=0; i--){
81837     if( aRegIdx[i]==0 ) continue;
81838     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
81839     if( useSeekResult ){
81840       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81841     }
81842   }
81843   regData = regRowid + 1;
81844   regRec = sqlite3GetTempReg(pParse);
81845   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
81846   sqlite3TableAffinityStr(v, pTab);
81847   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
81848   if( pParse->nested ){
81849     pik_flags = 0;
81850   }else{
81851     pik_flags = OPFLAG_NCHANGE;
81852     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
81853   }
81854   if( appendBias ){
81855     pik_flags |= OPFLAG_APPEND;
81856   }
81857   if( useSeekResult ){
81858     pik_flags |= OPFLAG_USESEEKRESULT;
81859   }
81860   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
81861   if( !pParse->nested ){
81862     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
81863   }
81864   sqlite3VdbeChangeP5(v, pik_flags);
81865 }
81866
81867 /*
81868 ** Generate code that will open cursors for a table and for all
81869 ** indices of that table.  The "baseCur" parameter is the cursor number used
81870 ** for the table.  Indices are opened on subsequent cursors.
81871 **
81872 ** Return the number of indices on the table.
81873 */
81874 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
81875   Parse *pParse,   /* Parsing context */
81876   Table *pTab,     /* Table to be opened */
81877   int baseCur,     /* Cursor number assigned to the table */
81878   int op           /* OP_OpenRead or OP_OpenWrite */
81879 ){
81880   int i;
81881   int iDb;
81882   Index *pIdx;
81883   Vdbe *v;
81884
81885   if( IsVirtual(pTab) ) return 0;
81886   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81887   v = sqlite3GetVdbe(pParse);
81888   assert( v!=0 );
81889   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
81890   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
81891     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81892     assert( pIdx->pSchema==pTab->pSchema );
81893     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
81894                       (char*)pKey, P4_KEYINFO_HANDOFF);
81895     VdbeComment((v, "%s", pIdx->zName));
81896   }
81897   if( pParse->nTab<baseCur+i ){
81898     pParse->nTab = baseCur+i;
81899   }
81900   return i-1;
81901 }
81902
81903
81904 #ifdef SQLITE_TEST
81905 /*
81906 ** The following global variable is incremented whenever the
81907 ** transfer optimization is used.  This is used for testing
81908 ** purposes only - to make sure the transfer optimization really
81909 ** is happening when it is suppose to.
81910 */
81911 SQLITE_API int sqlite3_xferopt_count;
81912 #endif /* SQLITE_TEST */
81913
81914
81915 #ifndef SQLITE_OMIT_XFER_OPT
81916 /*
81917 ** Check to collation names to see if they are compatible.
81918 */
81919 static int xferCompatibleCollation(const char *z1, const char *z2){
81920   if( z1==0 ){
81921     return z2==0;
81922   }
81923   if( z2==0 ){
81924     return 0;
81925   }
81926   return sqlite3StrICmp(z1, z2)==0;
81927 }
81928
81929
81930 /*
81931 ** Check to see if index pSrc is compatible as a source of data
81932 ** for index pDest in an insert transfer optimization.  The rules
81933 ** for a compatible index:
81934 **
81935 **    *   The index is over the same set of columns
81936 **    *   The same DESC and ASC markings occurs on all columns
81937 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
81938 **    *   The same collating sequence on each column
81939 */
81940 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
81941   int i;
81942   assert( pDest && pSrc );
81943   assert( pDest->pTable!=pSrc->pTable );
81944   if( pDest->nColumn!=pSrc->nColumn ){
81945     return 0;   /* Different number of columns */
81946   }
81947   if( pDest->onError!=pSrc->onError ){
81948     return 0;   /* Different conflict resolution strategies */
81949   }
81950   for(i=0; i<pSrc->nColumn; i++){
81951     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
81952       return 0;   /* Different columns indexed */
81953     }
81954     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
81955       return 0;   /* Different sort orders */
81956     }
81957     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
81958       return 0;   /* Different collating sequences */
81959     }
81960   }
81961
81962   /* If no test above fails then the indices must be compatible */
81963   return 1;
81964 }
81965
81966 /*
81967 ** Attempt the transfer optimization on INSERTs of the form
81968 **
81969 **     INSERT INTO tab1 SELECT * FROM tab2;
81970 **
81971 ** This optimization is only attempted if
81972 **
81973 **    (1)  tab1 and tab2 have identical schemas including all the
81974 **         same indices and constraints
81975 **
81976 **    (2)  tab1 and tab2 are different tables
81977 **
81978 **    (3)  There must be no triggers on tab1
81979 **
81980 **    (4)  The result set of the SELECT statement is "*"
81981 **
81982 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
81983 **         or LIMIT clause.
81984 **
81985 **    (6)  The SELECT statement is a simple (not a compound) select that
81986 **         contains only tab2 in its FROM clause
81987 **
81988 ** This method for implementing the INSERT transfers raw records from
81989 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
81990 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
81991 ** the resulting tab1 has much less fragmentation.
81992 **
81993 ** This routine returns TRUE if the optimization is attempted.  If any
81994 ** of the conditions above fail so that the optimization should not
81995 ** be attempted, then this routine returns FALSE.
81996 */
81997 static int xferOptimization(
81998   Parse *pParse,        /* Parser context */
81999   Table *pDest,         /* The table we are inserting into */
82000   Select *pSelect,      /* A SELECT statement to use as the data source */
82001   int onError,          /* How to handle constraint errors */
82002   int iDbDest           /* The database of pDest */
82003 ){
82004   ExprList *pEList;                /* The result set of the SELECT */
82005   Table *pSrc;                     /* The table in the FROM clause of SELECT */
82006   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
82007   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
82008   int i;                           /* Loop counter */
82009   int iDbSrc;                      /* The database of pSrc */
82010   int iSrc, iDest;                 /* Cursors from source and destination */
82011   int addr1, addr2;                /* Loop addresses */
82012   int emptyDestTest;               /* Address of test for empty pDest */
82013   int emptySrcTest;                /* Address of test for empty pSrc */
82014   Vdbe *v;                         /* The VDBE we are building */
82015   KeyInfo *pKey;                   /* Key information for an index */
82016   int regAutoinc;                  /* Memory register used by AUTOINC */
82017   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
82018   int regData, regRowid;           /* Registers holding data and rowid */
82019
82020   if( pSelect==0 ){
82021     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
82022   }
82023   if( sqlite3TriggerList(pParse, pDest) ){
82024     return 0;   /* tab1 must not have triggers */
82025   }
82026 #ifndef SQLITE_OMIT_VIRTUALTABLE
82027   if( pDest->tabFlags & TF_Virtual ){
82028     return 0;   /* tab1 must not be a virtual table */
82029   }
82030 #endif
82031   if( onError==OE_Default ){
82032     onError = OE_Abort;
82033   }
82034   if( onError!=OE_Abort && onError!=OE_Rollback ){
82035     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
82036   }
82037   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
82038   if( pSelect->pSrc->nSrc!=1 ){
82039     return 0;   /* FROM clause must have exactly one term */
82040   }
82041   if( pSelect->pSrc->a[0].pSelect ){
82042     return 0;   /* FROM clause cannot contain a subquery */
82043   }
82044   if( pSelect->pWhere ){
82045     return 0;   /* SELECT may not have a WHERE clause */
82046   }
82047   if( pSelect->pOrderBy ){
82048     return 0;   /* SELECT may not have an ORDER BY clause */
82049   }
82050   /* Do not need to test for a HAVING clause.  If HAVING is present but
82051   ** there is no ORDER BY, we will get an error. */
82052   if( pSelect->pGroupBy ){
82053     return 0;   /* SELECT may not have a GROUP BY clause */
82054   }
82055   if( pSelect->pLimit ){
82056     return 0;   /* SELECT may not have a LIMIT clause */
82057   }
82058   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
82059   if( pSelect->pPrior ){
82060     return 0;   /* SELECT may not be a compound query */
82061   }
82062   if( pSelect->selFlags & SF_Distinct ){
82063     return 0;   /* SELECT may not be DISTINCT */
82064   }
82065   pEList = pSelect->pEList;
82066   assert( pEList!=0 );
82067   if( pEList->nExpr!=1 ){
82068     return 0;   /* The result set must have exactly one column */
82069   }
82070   assert( pEList->a[0].pExpr );
82071   if( pEList->a[0].pExpr->op!=TK_ALL ){
82072     return 0;   /* The result set must be the special operator "*" */
82073   }
82074
82075   /* At this point we have established that the statement is of the
82076   ** correct syntactic form to participate in this optimization.  Now
82077   ** we have to check the semantics.
82078   */
82079   pItem = pSelect->pSrc->a;
82080   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
82081   if( pSrc==0 ){
82082     return 0;   /* FROM clause does not contain a real table */
82083   }
82084   if( pSrc==pDest ){
82085     return 0;   /* tab1 and tab2 may not be the same table */
82086   }
82087 #ifndef SQLITE_OMIT_VIRTUALTABLE
82088   if( pSrc->tabFlags & TF_Virtual ){
82089     return 0;   /* tab2 must not be a virtual table */
82090   }
82091 #endif
82092   if( pSrc->pSelect ){
82093     return 0;   /* tab2 may not be a view */
82094   }
82095   if( pDest->nCol!=pSrc->nCol ){
82096     return 0;   /* Number of columns must be the same in tab1 and tab2 */
82097   }
82098   if( pDest->iPKey!=pSrc->iPKey ){
82099     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
82100   }
82101   for(i=0; i<pDest->nCol; i++){
82102     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
82103       return 0;    /* Affinity must be the same on all columns */
82104     }
82105     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
82106       return 0;    /* Collating sequence must be the same on all columns */
82107     }
82108     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
82109       return 0;    /* tab2 must be NOT NULL if tab1 is */
82110     }
82111   }
82112   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
82113     if( pDestIdx->onError!=OE_None ){
82114       destHasUniqueIdx = 1;
82115     }
82116     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
82117       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
82118     }
82119     if( pSrcIdx==0 ){
82120       return 0;    /* pDestIdx has no corresponding index in pSrc */
82121     }
82122   }
82123 #ifndef SQLITE_OMIT_CHECK
82124   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
82125     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
82126   }
82127 #endif
82128
82129   /* If we get this far, it means either:
82130   **
82131   **    *   We can always do the transfer if the table contains an
82132   **        an integer primary key
82133   **
82134   **    *   We can conditionally do the transfer if the destination
82135   **        table is empty.
82136   */
82137 #ifdef SQLITE_TEST
82138   sqlite3_xferopt_count++;
82139 #endif
82140   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
82141   v = sqlite3GetVdbe(pParse);
82142   sqlite3CodeVerifySchema(pParse, iDbSrc);
82143   iSrc = pParse->nTab++;
82144   iDest = pParse->nTab++;
82145   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
82146   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
82147   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
82148     /* If tables do not have an INTEGER PRIMARY KEY and there
82149     ** are indices to be copied and the destination is not empty,
82150     ** we have to disallow the transfer optimization because the
82151     ** the rowids might change which will mess up indexing.
82152     **
82153     ** Or if the destination has a UNIQUE index and is not empty,
82154     ** we also disallow the transfer optimization because we cannot
82155     ** insure that all entries in the union of DEST and SRC will be
82156     ** unique.
82157     */
82158     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
82159     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
82160     sqlite3VdbeJumpHere(v, addr1);
82161   }else{
82162     emptyDestTest = 0;
82163   }
82164   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
82165   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
82166   regData = sqlite3GetTempReg(pParse);
82167   regRowid = sqlite3GetTempReg(pParse);
82168   if( pDest->iPKey>=0 ){
82169     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
82170     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
82171     sqlite3HaltConstraint(
82172         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
82173     sqlite3VdbeJumpHere(v, addr2);
82174     autoIncStep(pParse, regAutoinc, regRowid);
82175   }else if( pDest->pIndex==0 ){
82176     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
82177   }else{
82178     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
82179     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
82180   }
82181   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
82182   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
82183   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
82184   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
82185   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
82186   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
82187     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
82188       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
82189     }
82190     assert( pSrcIdx );
82191     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
82192     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82193     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
82194     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
82195                       (char*)pKey, P4_KEYINFO_HANDOFF);
82196     VdbeComment((v, "%s", pSrcIdx->zName));
82197     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
82198     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
82199                       (char*)pKey, P4_KEYINFO_HANDOFF);
82200     VdbeComment((v, "%s", pDestIdx->zName));
82201     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
82202     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
82203     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
82204     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
82205     sqlite3VdbeJumpHere(v, addr1);
82206   }
82207   sqlite3VdbeJumpHere(v, emptySrcTest);
82208   sqlite3ReleaseTempReg(pParse, regRowid);
82209   sqlite3ReleaseTempReg(pParse, regData);
82210   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
82211   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82212   if( emptyDestTest ){
82213     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
82214     sqlite3VdbeJumpHere(v, emptyDestTest);
82215     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82216     return 0;
82217   }else{
82218     return 1;
82219   }
82220 }
82221 #endif /* SQLITE_OMIT_XFER_OPT */
82222
82223 /************** End of insert.c **********************************************/
82224 /************** Begin file legacy.c ******************************************/
82225 /*
82226 ** 2001 September 15
82227 **
82228 ** The author disclaims copyright to this source code.  In place of
82229 ** a legal notice, here is a blessing:
82230 **
82231 **    May you do good and not evil.
82232 **    May you find forgiveness for yourself and forgive others.
82233 **    May you share freely, never taking more than you give.
82234 **
82235 *************************************************************************
82236 ** Main file for the SQLite library.  The routines in this file
82237 ** implement the programmer interface to the library.  Routines in
82238 ** other files are for internal use by SQLite and should not be
82239 ** accessed by users of the library.
82240 */
82241
82242
82243 /*
82244 ** Execute SQL code.  Return one of the SQLITE_ success/failure
82245 ** codes.  Also write an error message into memory obtained from
82246 ** malloc() and make *pzErrMsg point to that message.
82247 **
82248 ** If the SQL is a query, then for each row in the query result
82249 ** the xCallback() function is called.  pArg becomes the first
82250 ** argument to xCallback().  If xCallback=NULL then no callback
82251 ** is invoked, even for queries.
82252 */
82253 SQLITE_API int sqlite3_exec(
82254   sqlite3 *db,                /* The database on which the SQL executes */
82255   const char *zSql,           /* The SQL to be executed */
82256   sqlite3_callback xCallback, /* Invoke this callback routine */
82257   void *pArg,                 /* First argument to xCallback() */
82258   char **pzErrMsg             /* Write error messages here */
82259 ){
82260   int rc = SQLITE_OK;         /* Return code */
82261   const char *zLeftover;      /* Tail of unprocessed SQL */
82262   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
82263   char **azCols = 0;          /* Names of result columns */
82264   int nRetry = 0;             /* Number of retry attempts */
82265   int callbackIsInit;         /* True if callback data is initialized */
82266
82267   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
82268   if( zSql==0 ) zSql = "";
82269
82270   sqlite3_mutex_enter(db->mutex);
82271   sqlite3Error(db, SQLITE_OK, 0);
82272   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
82273     int nCol;
82274     char **azVals = 0;
82275
82276     pStmt = 0;
82277     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
82278     assert( rc==SQLITE_OK || pStmt==0 );
82279     if( rc!=SQLITE_OK ){
82280       continue;
82281     }
82282     if( !pStmt ){
82283       /* this happens for a comment or white-space */
82284       zSql = zLeftover;
82285       continue;
82286     }
82287
82288     callbackIsInit = 0;
82289     nCol = sqlite3_column_count(pStmt);
82290
82291     while( 1 ){
82292       int i;
82293       rc = sqlite3_step(pStmt);
82294
82295       /* Invoke the callback function if required */
82296       if( xCallback && (SQLITE_ROW==rc || 
82297           (SQLITE_DONE==rc && !callbackIsInit
82298                            && db->flags&SQLITE_NullCallback)) ){
82299         if( !callbackIsInit ){
82300           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
82301           if( azCols==0 ){
82302             goto exec_out;
82303           }
82304           for(i=0; i<nCol; i++){
82305             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
82306             /* sqlite3VdbeSetColName() installs column names as UTF8
82307             ** strings so there is no way for sqlite3_column_name() to fail. */
82308             assert( azCols[i]!=0 );
82309           }
82310           callbackIsInit = 1;
82311         }
82312         if( rc==SQLITE_ROW ){
82313           azVals = &azCols[nCol];
82314           for(i=0; i<nCol; i++){
82315             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
82316             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
82317               db->mallocFailed = 1;
82318               goto exec_out;
82319             }
82320           }
82321         }
82322         if( xCallback(pArg, nCol, azVals, azCols) ){
82323           rc = SQLITE_ABORT;
82324           sqlite3VdbeFinalize((Vdbe *)pStmt);
82325           pStmt = 0;
82326           sqlite3Error(db, SQLITE_ABORT, 0);
82327           goto exec_out;
82328         }
82329       }
82330
82331       if( rc!=SQLITE_ROW ){
82332         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
82333         pStmt = 0;
82334         if( rc!=SQLITE_SCHEMA ){
82335           nRetry = 0;
82336           zSql = zLeftover;
82337           while( sqlite3Isspace(zSql[0]) ) zSql++;
82338         }
82339         break;
82340       }
82341     }
82342
82343     sqlite3DbFree(db, azCols);
82344     azCols = 0;
82345   }
82346
82347 exec_out:
82348   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
82349   sqlite3DbFree(db, azCols);
82350
82351   rc = sqlite3ApiExit(db, rc);
82352   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
82353     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
82354     *pzErrMsg = sqlite3Malloc(nErrMsg);
82355     if( *pzErrMsg ){
82356       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
82357     }else{
82358       rc = SQLITE_NOMEM;
82359       sqlite3Error(db, SQLITE_NOMEM, 0);
82360     }
82361   }else if( pzErrMsg ){
82362     *pzErrMsg = 0;
82363   }
82364
82365   assert( (rc&db->errMask)==rc );
82366   sqlite3_mutex_leave(db->mutex);
82367   return rc;
82368 }
82369
82370 /************** End of legacy.c **********************************************/
82371 /************** Begin file loadext.c *****************************************/
82372 /*
82373 ** 2006 June 7
82374 **
82375 ** The author disclaims copyright to this source code.  In place of
82376 ** a legal notice, here is a blessing:
82377 **
82378 **    May you do good and not evil.
82379 **    May you find forgiveness for yourself and forgive others.
82380 **    May you share freely, never taking more than you give.
82381 **
82382 *************************************************************************
82383 ** This file contains code used to dynamically load extensions into
82384 ** the SQLite library.
82385 */
82386
82387 #ifndef SQLITE_CORE
82388   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
82389 #endif
82390 /************** Include sqlite3ext.h in the middle of loadext.c **************/
82391 /************** Begin file sqlite3ext.h **************************************/
82392 /*
82393 ** 2006 June 7
82394 **
82395 ** The author disclaims copyright to this source code.  In place of
82396 ** a legal notice, here is a blessing:
82397 **
82398 **    May you do good and not evil.
82399 **    May you find forgiveness for yourself and forgive others.
82400 **    May you share freely, never taking more than you give.
82401 **
82402 *************************************************************************
82403 ** This header file defines the SQLite interface for use by
82404 ** shared libraries that want to be imported as extensions into
82405 ** an SQLite instance.  Shared libraries that intend to be loaded
82406 ** as extensions by SQLite should #include this file instead of 
82407 ** sqlite3.h.
82408 */
82409 #ifndef _SQLITE3EXT_H_
82410 #define _SQLITE3EXT_H_
82411
82412 typedef struct sqlite3_api_routines sqlite3_api_routines;
82413
82414 /*
82415 ** The following structure holds pointers to all of the SQLite API
82416 ** routines.
82417 **
82418 ** WARNING:  In order to maintain backwards compatibility, add new
82419 ** interfaces to the end of this structure only.  If you insert new
82420 ** interfaces in the middle of this structure, then older different
82421 ** versions of SQLite will not be able to load each others' shared
82422 ** libraries!
82423 */
82424 struct sqlite3_api_routines {
82425   void * (*aggregate_context)(sqlite3_context*,int nBytes);
82426   int  (*aggregate_count)(sqlite3_context*);
82427   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
82428   int  (*bind_double)(sqlite3_stmt*,int,double);
82429   int  (*bind_int)(sqlite3_stmt*,int,int);
82430   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
82431   int  (*bind_null)(sqlite3_stmt*,int);
82432   int  (*bind_parameter_count)(sqlite3_stmt*);
82433   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
82434   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
82435   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
82436   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
82437   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
82438   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
82439   int  (*busy_timeout)(sqlite3*,int ms);
82440   int  (*changes)(sqlite3*);
82441   int  (*close)(sqlite3*);
82442   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
82443   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
82444   const void * (*column_blob)(sqlite3_stmt*,int iCol);
82445   int  (*column_bytes)(sqlite3_stmt*,int iCol);
82446   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
82447   int  (*column_count)(sqlite3_stmt*pStmt);
82448   const char * (*column_database_name)(sqlite3_stmt*,int);
82449   const void * (*column_database_name16)(sqlite3_stmt*,int);
82450   const char * (*column_decltype)(sqlite3_stmt*,int i);
82451   const void * (*column_decltype16)(sqlite3_stmt*,int);
82452   double  (*column_double)(sqlite3_stmt*,int iCol);
82453   int  (*column_int)(sqlite3_stmt*,int iCol);
82454   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
82455   const char * (*column_name)(sqlite3_stmt*,int);
82456   const void * (*column_name16)(sqlite3_stmt*,int);
82457   const char * (*column_origin_name)(sqlite3_stmt*,int);
82458   const void * (*column_origin_name16)(sqlite3_stmt*,int);
82459   const char * (*column_table_name)(sqlite3_stmt*,int);
82460   const void * (*column_table_name16)(sqlite3_stmt*,int);
82461   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
82462   const void * (*column_text16)(sqlite3_stmt*,int iCol);
82463   int  (*column_type)(sqlite3_stmt*,int iCol);
82464   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
82465   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
82466   int  (*complete)(const char*sql);
82467   int  (*complete16)(const void*sql);
82468   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
82469   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
82470   int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
82471   int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
82472   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
82473   int  (*data_count)(sqlite3_stmt*pStmt);
82474   sqlite3 * (*db_handle)(sqlite3_stmt*);
82475   int (*declare_vtab)(sqlite3*,const char*);
82476   int  (*enable_shared_cache)(int);
82477   int  (*errcode)(sqlite3*db);
82478   const char * (*errmsg)(sqlite3*);
82479   const void * (*errmsg16)(sqlite3*);
82480   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
82481   int  (*expired)(sqlite3_stmt*);
82482   int  (*finalize)(sqlite3_stmt*pStmt);
82483   void  (*free)(void*);
82484   void  (*free_table)(char**result);
82485   int  (*get_autocommit)(sqlite3*);
82486   void * (*get_auxdata)(sqlite3_context*,int);
82487   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
82488   int  (*global_recover)(void);
82489   void  (*interruptx)(sqlite3*);
82490   sqlite_int64  (*last_insert_rowid)(sqlite3*);
82491   const char * (*libversion)(void);
82492   int  (*libversion_number)(void);
82493   void *(*malloc)(int);
82494   char * (*mprintf)(const char*,...);
82495   int  (*open)(const char*,sqlite3**);
82496   int  (*open16)(const void*,sqlite3**);
82497   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82498   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82499   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
82500   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
82501   void *(*realloc)(void*,int);
82502   int  (*reset)(sqlite3_stmt*pStmt);
82503   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
82504   void  (*result_double)(sqlite3_context*,double);
82505   void  (*result_error)(sqlite3_context*,const char*,int);
82506   void  (*result_error16)(sqlite3_context*,const void*,int);
82507   void  (*result_int)(sqlite3_context*,int);
82508   void  (*result_int64)(sqlite3_context*,sqlite_int64);
82509   void  (*result_null)(sqlite3_context*);
82510   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
82511   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
82512   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
82513   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
82514   void  (*result_value)(sqlite3_context*,sqlite3_value*);
82515   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
82516   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
82517   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
82518   char * (*snprintf)(int,char*,const char*,...);
82519   int  (*step)(sqlite3_stmt*);
82520   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
82521   void  (*thread_cleanup)(void);
82522   int  (*total_changes)(sqlite3*);
82523   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
82524   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
82525   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
82526   void * (*user_data)(sqlite3_context*);
82527   const void * (*value_blob)(sqlite3_value*);
82528   int  (*value_bytes)(sqlite3_value*);
82529   int  (*value_bytes16)(sqlite3_value*);
82530   double  (*value_double)(sqlite3_value*);
82531   int  (*value_int)(sqlite3_value*);
82532   sqlite_int64  (*value_int64)(sqlite3_value*);
82533   int  (*value_numeric_type)(sqlite3_value*);
82534   const unsigned char * (*value_text)(sqlite3_value*);
82535   const void * (*value_text16)(sqlite3_value*);
82536   const void * (*value_text16be)(sqlite3_value*);
82537   const void * (*value_text16le)(sqlite3_value*);
82538   int  (*value_type)(sqlite3_value*);
82539   char *(*vmprintf)(const char*,va_list);
82540   /* Added ??? */
82541   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
82542   /* Added by 3.3.13 */
82543   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82544   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82545   int (*clear_bindings)(sqlite3_stmt*);
82546   /* Added by 3.4.1 */
82547   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
82548   /* Added by 3.5.0 */
82549   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
82550   int (*blob_bytes)(sqlite3_blob*);
82551   int (*blob_close)(sqlite3_blob*);
82552   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
82553   int (*blob_read)(sqlite3_blob*,void*,int,int);
82554   int (*blob_write)(sqlite3_blob*,const void*,int,int);
82555   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
82556   int (*file_control)(sqlite3*,const char*,int,void*);
82557   sqlite3_int64 (*memory_highwater)(int);
82558   sqlite3_int64 (*memory_used)(void);
82559   sqlite3_mutex *(*mutex_alloc)(int);
82560   void (*mutex_enter)(sqlite3_mutex*);
82561   void (*mutex_free)(sqlite3_mutex*);
82562   void (*mutex_leave)(sqlite3_mutex*);
82563   int (*mutex_try)(sqlite3_mutex*);
82564   int (*open_v2)(const char*,sqlite3**,int,const char*);
82565   int (*release_memory)(int);
82566   void (*result_error_nomem)(sqlite3_context*);
82567   void (*result_error_toobig)(sqlite3_context*);
82568   int (*sleep)(int);
82569   void (*soft_heap_limit)(int);
82570   sqlite3_vfs *(*vfs_find)(const char*);
82571   int (*vfs_register)(sqlite3_vfs*,int);
82572   int (*vfs_unregister)(sqlite3_vfs*);
82573   int (*xthreadsafe)(void);
82574   void (*result_zeroblob)(sqlite3_context*,int);
82575   void (*result_error_code)(sqlite3_context*,int);
82576   int (*test_control)(int, ...);
82577   void (*randomness)(int,void*);
82578   sqlite3 *(*context_db_handle)(sqlite3_context*);
82579   int (*extended_result_codes)(sqlite3*,int);
82580   int (*limit)(sqlite3*,int,int);
82581   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
82582   const char *(*sql)(sqlite3_stmt*);
82583   int (*status)(int,int*,int*,int);
82584 };
82585
82586 /*
82587 ** The following macros redefine the API routines so that they are
82588 ** redirected throught the global sqlite3_api structure.
82589 **
82590 ** This header file is also used by the loadext.c source file
82591 ** (part of the main SQLite library - not an extension) so that
82592 ** it can get access to the sqlite3_api_routines structure
82593 ** definition.  But the main library does not want to redefine
82594 ** the API.  So the redefinition macros are only valid if the
82595 ** SQLITE_CORE macros is undefined.
82596 */
82597 #ifndef SQLITE_CORE
82598 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
82599 #ifndef SQLITE_OMIT_DEPRECATED
82600 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
82601 #endif
82602 #define sqlite3_bind_blob              sqlite3_api->bind_blob
82603 #define sqlite3_bind_double            sqlite3_api->bind_double
82604 #define sqlite3_bind_int               sqlite3_api->bind_int
82605 #define sqlite3_bind_int64             sqlite3_api->bind_int64
82606 #define sqlite3_bind_null              sqlite3_api->bind_null
82607 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
82608 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
82609 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
82610 #define sqlite3_bind_text              sqlite3_api->bind_text
82611 #define sqlite3_bind_text16            sqlite3_api->bind_text16
82612 #define sqlite3_bind_value             sqlite3_api->bind_value
82613 #define sqlite3_busy_handler           sqlite3_api->busy_handler
82614 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
82615 #define sqlite3_changes                sqlite3_api->changes
82616 #define sqlite3_close                  sqlite3_api->close
82617 #define sqlite3_collation_needed       sqlite3_api->collation_needed
82618 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
82619 #define sqlite3_column_blob            sqlite3_api->column_blob
82620 #define sqlite3_column_bytes           sqlite3_api->column_bytes
82621 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
82622 #define sqlite3_column_count           sqlite3_api->column_count
82623 #define sqlite3_column_database_name   sqlite3_api->column_database_name
82624 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
82625 #define sqlite3_column_decltype        sqlite3_api->column_decltype
82626 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
82627 #define sqlite3_column_double          sqlite3_api->column_double
82628 #define sqlite3_column_int             sqlite3_api->column_int
82629 #define sqlite3_column_int64           sqlite3_api->column_int64
82630 #define sqlite3_column_name            sqlite3_api->column_name
82631 #define sqlite3_column_name16          sqlite3_api->column_name16
82632 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
82633 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
82634 #define sqlite3_column_table_name      sqlite3_api->column_table_name
82635 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
82636 #define sqlite3_column_text            sqlite3_api->column_text
82637 #define sqlite3_column_text16          sqlite3_api->column_text16
82638 #define sqlite3_column_type            sqlite3_api->column_type
82639 #define sqlite3_column_value           sqlite3_api->column_value
82640 #define sqlite3_commit_hook            sqlite3_api->commit_hook
82641 #define sqlite3_complete               sqlite3_api->complete
82642 #define sqlite3_complete16             sqlite3_api->complete16
82643 #define sqlite3_create_collation       sqlite3_api->create_collation
82644 #define sqlite3_create_collation16     sqlite3_api->create_collation16
82645 #define sqlite3_create_function        sqlite3_api->create_function
82646 #define sqlite3_create_function16      sqlite3_api->create_function16
82647 #define sqlite3_create_module          sqlite3_api->create_module
82648 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
82649 #define sqlite3_data_count             sqlite3_api->data_count
82650 #define sqlite3_db_handle              sqlite3_api->db_handle
82651 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
82652 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
82653 #define sqlite3_errcode                sqlite3_api->errcode
82654 #define sqlite3_errmsg                 sqlite3_api->errmsg
82655 #define sqlite3_errmsg16               sqlite3_api->errmsg16
82656 #define sqlite3_exec                   sqlite3_api->exec
82657 #ifndef SQLITE_OMIT_DEPRECATED
82658 #define sqlite3_expired                sqlite3_api->expired
82659 #endif
82660 #define sqlite3_finalize               sqlite3_api->finalize
82661 #define sqlite3_free                   sqlite3_api->free
82662 #define sqlite3_free_table             sqlite3_api->free_table
82663 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
82664 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
82665 #define sqlite3_get_table              sqlite3_api->get_table
82666 #ifndef SQLITE_OMIT_DEPRECATED
82667 #define sqlite3_global_recover         sqlite3_api->global_recover
82668 #endif
82669 #define sqlite3_interrupt              sqlite3_api->interruptx
82670 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
82671 #define sqlite3_libversion             sqlite3_api->libversion
82672 #define sqlite3_libversion_number      sqlite3_api->libversion_number
82673 #define sqlite3_malloc                 sqlite3_api->malloc
82674 #define sqlite3_mprintf                sqlite3_api->mprintf
82675 #define sqlite3_open                   sqlite3_api->open
82676 #define sqlite3_open16                 sqlite3_api->open16
82677 #define sqlite3_prepare                sqlite3_api->prepare
82678 #define sqlite3_prepare16              sqlite3_api->prepare16
82679 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82680 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82681 #define sqlite3_profile                sqlite3_api->profile
82682 #define sqlite3_progress_handler       sqlite3_api->progress_handler
82683 #define sqlite3_realloc                sqlite3_api->realloc
82684 #define sqlite3_reset                  sqlite3_api->reset
82685 #define sqlite3_result_blob            sqlite3_api->result_blob
82686 #define sqlite3_result_double          sqlite3_api->result_double
82687 #define sqlite3_result_error           sqlite3_api->result_error
82688 #define sqlite3_result_error16         sqlite3_api->result_error16
82689 #define sqlite3_result_int             sqlite3_api->result_int
82690 #define sqlite3_result_int64           sqlite3_api->result_int64
82691 #define sqlite3_result_null            sqlite3_api->result_null
82692 #define sqlite3_result_text            sqlite3_api->result_text
82693 #define sqlite3_result_text16          sqlite3_api->result_text16
82694 #define sqlite3_result_text16be        sqlite3_api->result_text16be
82695 #define sqlite3_result_text16le        sqlite3_api->result_text16le
82696 #define sqlite3_result_value           sqlite3_api->result_value
82697 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
82698 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
82699 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
82700 #define sqlite3_snprintf               sqlite3_api->snprintf
82701 #define sqlite3_step                   sqlite3_api->step
82702 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
82703 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
82704 #define sqlite3_total_changes          sqlite3_api->total_changes
82705 #define sqlite3_trace                  sqlite3_api->trace
82706 #ifndef SQLITE_OMIT_DEPRECATED
82707 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
82708 #endif
82709 #define sqlite3_update_hook            sqlite3_api->update_hook
82710 #define sqlite3_user_data              sqlite3_api->user_data
82711 #define sqlite3_value_blob             sqlite3_api->value_blob
82712 #define sqlite3_value_bytes            sqlite3_api->value_bytes
82713 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
82714 #define sqlite3_value_double           sqlite3_api->value_double
82715 #define sqlite3_value_int              sqlite3_api->value_int
82716 #define sqlite3_value_int64            sqlite3_api->value_int64
82717 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
82718 #define sqlite3_value_text             sqlite3_api->value_text
82719 #define sqlite3_value_text16           sqlite3_api->value_text16
82720 #define sqlite3_value_text16be         sqlite3_api->value_text16be
82721 #define sqlite3_value_text16le         sqlite3_api->value_text16le
82722 #define sqlite3_value_type             sqlite3_api->value_type
82723 #define sqlite3_vmprintf               sqlite3_api->vmprintf
82724 #define sqlite3_overload_function      sqlite3_api->overload_function
82725 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82726 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82727 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
82728 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
82729 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
82730 #define sqlite3_blob_close             sqlite3_api->blob_close
82731 #define sqlite3_blob_open              sqlite3_api->blob_open
82732 #define sqlite3_blob_read              sqlite3_api->blob_read
82733 #define sqlite3_blob_write             sqlite3_api->blob_write
82734 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
82735 #define sqlite3_file_control           sqlite3_api->file_control
82736 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
82737 #define sqlite3_memory_used            sqlite3_api->memory_used
82738 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
82739 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
82740 #define sqlite3_mutex_free             sqlite3_api->mutex_free
82741 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
82742 #define sqlite3_mutex_try              sqlite3_api->mutex_try
82743 #define sqlite3_open_v2                sqlite3_api->open_v2
82744 #define sqlite3_release_memory         sqlite3_api->release_memory
82745 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
82746 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
82747 #define sqlite3_sleep                  sqlite3_api->sleep
82748 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
82749 #define sqlite3_vfs_find               sqlite3_api->vfs_find
82750 #define sqlite3_vfs_register           sqlite3_api->vfs_register
82751 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
82752 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
82753 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
82754 #define sqlite3_result_error_code      sqlite3_api->result_error_code
82755 #define sqlite3_test_control           sqlite3_api->test_control
82756 #define sqlite3_randomness             sqlite3_api->randomness
82757 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
82758 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
82759 #define sqlite3_limit                  sqlite3_api->limit
82760 #define sqlite3_next_stmt              sqlite3_api->next_stmt
82761 #define sqlite3_sql                    sqlite3_api->sql
82762 #define sqlite3_status                 sqlite3_api->status
82763 #endif /* SQLITE_CORE */
82764
82765 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
82766 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
82767
82768 #endif /* _SQLITE3EXT_H_ */
82769
82770 /************** End of sqlite3ext.h ******************************************/
82771 /************** Continuing where we left off in loadext.c ********************/
82772
82773 #ifndef SQLITE_OMIT_LOAD_EXTENSION
82774
82775 /*
82776 ** Some API routines are omitted when various features are
82777 ** excluded from a build of SQLite.  Substitute a NULL pointer
82778 ** for any missing APIs.
82779 */
82780 #ifndef SQLITE_ENABLE_COLUMN_METADATA
82781 # define sqlite3_column_database_name   0
82782 # define sqlite3_column_database_name16 0
82783 # define sqlite3_column_table_name      0
82784 # define sqlite3_column_table_name16    0
82785 # define sqlite3_column_origin_name     0
82786 # define sqlite3_column_origin_name16   0
82787 # define sqlite3_table_column_metadata  0
82788 #endif
82789
82790 #ifdef SQLITE_OMIT_AUTHORIZATION
82791 # define sqlite3_set_authorizer         0
82792 #endif
82793
82794 #ifdef SQLITE_OMIT_UTF16
82795 # define sqlite3_bind_text16            0
82796 # define sqlite3_collation_needed16     0
82797 # define sqlite3_column_decltype16      0
82798 # define sqlite3_column_name16          0
82799 # define sqlite3_column_text16          0
82800 # define sqlite3_complete16             0
82801 # define sqlite3_create_collation16     0
82802 # define sqlite3_create_function16      0
82803 # define sqlite3_errmsg16               0
82804 # define sqlite3_open16                 0
82805 # define sqlite3_prepare16              0
82806 # define sqlite3_prepare16_v2           0
82807 # define sqlite3_result_error16         0
82808 # define sqlite3_result_text16          0
82809 # define sqlite3_result_text16be        0
82810 # define sqlite3_result_text16le        0
82811 # define sqlite3_value_text16           0
82812 # define sqlite3_value_text16be         0
82813 # define sqlite3_value_text16le         0
82814 # define sqlite3_column_database_name16 0
82815 # define sqlite3_column_table_name16    0
82816 # define sqlite3_column_origin_name16   0
82817 #endif
82818
82819 #ifdef SQLITE_OMIT_COMPLETE
82820 # define sqlite3_complete 0
82821 # define sqlite3_complete16 0
82822 #endif
82823
82824 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
82825 # define sqlite3_progress_handler 0
82826 #endif
82827
82828 #ifdef SQLITE_OMIT_VIRTUALTABLE
82829 # define sqlite3_create_module 0
82830 # define sqlite3_create_module_v2 0
82831 # define sqlite3_declare_vtab 0
82832 #endif
82833
82834 #ifdef SQLITE_OMIT_SHARED_CACHE
82835 # define sqlite3_enable_shared_cache 0
82836 #endif
82837
82838 #ifdef SQLITE_OMIT_TRACE
82839 # define sqlite3_profile       0
82840 # define sqlite3_trace         0
82841 #endif
82842
82843 #ifdef SQLITE_OMIT_GET_TABLE
82844 # define sqlite3_free_table    0
82845 # define sqlite3_get_table     0
82846 #endif
82847
82848 #ifdef SQLITE_OMIT_INCRBLOB
82849 #define sqlite3_bind_zeroblob  0
82850 #define sqlite3_blob_bytes     0
82851 #define sqlite3_blob_close     0
82852 #define sqlite3_blob_open      0
82853 #define sqlite3_blob_read      0
82854 #define sqlite3_blob_write     0
82855 #endif
82856
82857 /*
82858 ** The following structure contains pointers to all SQLite API routines.
82859 ** A pointer to this structure is passed into extensions when they are
82860 ** loaded so that the extension can make calls back into the SQLite
82861 ** library.
82862 **
82863 ** When adding new APIs, add them to the bottom of this structure
82864 ** in order to preserve backwards compatibility.
82865 **
82866 ** Extensions that use newer APIs should first call the
82867 ** sqlite3_libversion_number() to make sure that the API they
82868 ** intend to use is supported by the library.  Extensions should
82869 ** also check to make sure that the pointer to the function is
82870 ** not NULL before calling it.
82871 */
82872 static const sqlite3_api_routines sqlite3Apis = {
82873   sqlite3_aggregate_context,
82874 #ifndef SQLITE_OMIT_DEPRECATED
82875   sqlite3_aggregate_count,
82876 #else
82877   0,
82878 #endif
82879   sqlite3_bind_blob,
82880   sqlite3_bind_double,
82881   sqlite3_bind_int,
82882   sqlite3_bind_int64,
82883   sqlite3_bind_null,
82884   sqlite3_bind_parameter_count,
82885   sqlite3_bind_parameter_index,
82886   sqlite3_bind_parameter_name,
82887   sqlite3_bind_text,
82888   sqlite3_bind_text16,
82889   sqlite3_bind_value,
82890   sqlite3_busy_handler,
82891   sqlite3_busy_timeout,
82892   sqlite3_changes,
82893   sqlite3_close,
82894   sqlite3_collation_needed,
82895   sqlite3_collation_needed16,
82896   sqlite3_column_blob,
82897   sqlite3_column_bytes,
82898   sqlite3_column_bytes16,
82899   sqlite3_column_count,
82900   sqlite3_column_database_name,
82901   sqlite3_column_database_name16,
82902   sqlite3_column_decltype,
82903   sqlite3_column_decltype16,
82904   sqlite3_column_double,
82905   sqlite3_column_int,
82906   sqlite3_column_int64,
82907   sqlite3_column_name,
82908   sqlite3_column_name16,
82909   sqlite3_column_origin_name,
82910   sqlite3_column_origin_name16,
82911   sqlite3_column_table_name,
82912   sqlite3_column_table_name16,
82913   sqlite3_column_text,
82914   sqlite3_column_text16,
82915   sqlite3_column_type,
82916   sqlite3_column_value,
82917   sqlite3_commit_hook,
82918   sqlite3_complete,
82919   sqlite3_complete16,
82920   sqlite3_create_collation,
82921   sqlite3_create_collation16,
82922   sqlite3_create_function,
82923   sqlite3_create_function16,
82924   sqlite3_create_module,
82925   sqlite3_data_count,
82926   sqlite3_db_handle,
82927   sqlite3_declare_vtab,
82928   sqlite3_enable_shared_cache,
82929   sqlite3_errcode,
82930   sqlite3_errmsg,
82931   sqlite3_errmsg16,
82932   sqlite3_exec,
82933 #ifndef SQLITE_OMIT_DEPRECATED
82934   sqlite3_expired,
82935 #else
82936   0,
82937 #endif
82938   sqlite3_finalize,
82939   sqlite3_free,
82940   sqlite3_free_table,
82941   sqlite3_get_autocommit,
82942   sqlite3_get_auxdata,
82943   sqlite3_get_table,
82944   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
82945   sqlite3_interrupt,
82946   sqlite3_last_insert_rowid,
82947   sqlite3_libversion,
82948   sqlite3_libversion_number,
82949   sqlite3_malloc,
82950   sqlite3_mprintf,
82951   sqlite3_open,
82952   sqlite3_open16,
82953   sqlite3_prepare,
82954   sqlite3_prepare16,
82955   sqlite3_profile,
82956   sqlite3_progress_handler,
82957   sqlite3_realloc,
82958   sqlite3_reset,
82959   sqlite3_result_blob,
82960   sqlite3_result_double,
82961   sqlite3_result_error,
82962   sqlite3_result_error16,
82963   sqlite3_result_int,
82964   sqlite3_result_int64,
82965   sqlite3_result_null,
82966   sqlite3_result_text,
82967   sqlite3_result_text16,
82968   sqlite3_result_text16be,
82969   sqlite3_result_text16le,
82970   sqlite3_result_value,
82971   sqlite3_rollback_hook,
82972   sqlite3_set_authorizer,
82973   sqlite3_set_auxdata,
82974   sqlite3_snprintf,
82975   sqlite3_step,
82976   sqlite3_table_column_metadata,
82977 #ifndef SQLITE_OMIT_DEPRECATED
82978   sqlite3_thread_cleanup,
82979 #else
82980   0,
82981 #endif
82982   sqlite3_total_changes,
82983   sqlite3_trace,
82984 #ifndef SQLITE_OMIT_DEPRECATED
82985   sqlite3_transfer_bindings,
82986 #else
82987   0,
82988 #endif
82989   sqlite3_update_hook,
82990   sqlite3_user_data,
82991   sqlite3_value_blob,
82992   sqlite3_value_bytes,
82993   sqlite3_value_bytes16,
82994   sqlite3_value_double,
82995   sqlite3_value_int,
82996   sqlite3_value_int64,
82997   sqlite3_value_numeric_type,
82998   sqlite3_value_text,
82999   sqlite3_value_text16,
83000   sqlite3_value_text16be,
83001   sqlite3_value_text16le,
83002   sqlite3_value_type,
83003   sqlite3_vmprintf,
83004   /*
83005   ** The original API set ends here.  All extensions can call any
83006   ** of the APIs above provided that the pointer is not NULL.  But
83007   ** before calling APIs that follow, extension should check the
83008   ** sqlite3_libversion_number() to make sure they are dealing with
83009   ** a library that is new enough to support that API.
83010   *************************************************************************
83011   */
83012   sqlite3_overload_function,
83013
83014   /*
83015   ** Added after 3.3.13
83016   */
83017   sqlite3_prepare_v2,
83018   sqlite3_prepare16_v2,
83019   sqlite3_clear_bindings,
83020
83021   /*
83022   ** Added for 3.4.1
83023   */
83024   sqlite3_create_module_v2,
83025
83026   /*
83027   ** Added for 3.5.0
83028   */
83029   sqlite3_bind_zeroblob,
83030   sqlite3_blob_bytes,
83031   sqlite3_blob_close,
83032   sqlite3_blob_open,
83033   sqlite3_blob_read,
83034   sqlite3_blob_write,
83035   sqlite3_create_collation_v2,
83036   sqlite3_file_control,
83037   sqlite3_memory_highwater,
83038   sqlite3_memory_used,
83039 #ifdef SQLITE_MUTEX_OMIT
83040   0, 
83041   0, 
83042   0,
83043   0,
83044   0,
83045 #else
83046   sqlite3_mutex_alloc,
83047   sqlite3_mutex_enter,
83048   sqlite3_mutex_free,
83049   sqlite3_mutex_leave,
83050   sqlite3_mutex_try,
83051 #endif
83052   sqlite3_open_v2,
83053   sqlite3_release_memory,
83054   sqlite3_result_error_nomem,
83055   sqlite3_result_error_toobig,
83056   sqlite3_sleep,
83057   sqlite3_soft_heap_limit,
83058   sqlite3_vfs_find,
83059   sqlite3_vfs_register,
83060   sqlite3_vfs_unregister,
83061
83062   /*
83063   ** Added for 3.5.8
83064   */
83065   sqlite3_threadsafe,
83066   sqlite3_result_zeroblob,
83067   sqlite3_result_error_code,
83068   sqlite3_test_control,
83069   sqlite3_randomness,
83070   sqlite3_context_db_handle,
83071
83072   /*
83073   ** Added for 3.6.0
83074   */
83075   sqlite3_extended_result_codes,
83076   sqlite3_limit,
83077   sqlite3_next_stmt,
83078   sqlite3_sql,
83079   sqlite3_status,
83080 };
83081
83082 /*
83083 ** Attempt to load an SQLite extension library contained in the file
83084 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
83085 ** default entry point name (sqlite3_extension_init) is used.  Use
83086 ** of the default name is recommended.
83087 **
83088 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
83089 **
83090 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
83091 ** error message text.  The calling function should free this memory
83092 ** by calling sqlite3DbFree(db, ).
83093 */
83094 static int sqlite3LoadExtension(
83095   sqlite3 *db,          /* Load the extension into this database connection */
83096   const char *zFile,    /* Name of the shared library containing extension */
83097   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
83098   char **pzErrMsg       /* Put error message here if not 0 */
83099 ){
83100   sqlite3_vfs *pVfs = db->pVfs;
83101   void *handle;
83102   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
83103   char *zErrmsg = 0;
83104   void **aHandle;
83105   const int nMsg = 300;
83106
83107   if( pzErrMsg ) *pzErrMsg = 0;
83108
83109   /* Ticket #1863.  To avoid a creating security problems for older
83110   ** applications that relink against newer versions of SQLite, the
83111   ** ability to run load_extension is turned off by default.  One
83112   ** must call sqlite3_enable_load_extension() to turn on extension
83113   ** loading.  Otherwise you get the following error.
83114   */
83115   if( (db->flags & SQLITE_LoadExtension)==0 ){
83116     if( pzErrMsg ){
83117       *pzErrMsg = sqlite3_mprintf("not authorized");
83118     }
83119     return SQLITE_ERROR;
83120   }
83121
83122   if( zProc==0 ){
83123     zProc = "sqlite3_extension_init";
83124   }
83125
83126   handle = sqlite3OsDlOpen(pVfs, zFile);
83127   if( handle==0 ){
83128     if( pzErrMsg ){
83129       zErrmsg = sqlite3StackAllocZero(db, nMsg);
83130       if( zErrmsg ){
83131         sqlite3_snprintf(nMsg, zErrmsg, 
83132             "unable to open shared library [%s]", zFile);
83133         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
83134         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
83135         sqlite3StackFree(db, zErrmsg);
83136       }
83137     }
83138     return SQLITE_ERROR;
83139   }
83140   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
83141                    sqlite3OsDlSym(pVfs, handle, zProc);
83142   if( xInit==0 ){
83143     if( pzErrMsg ){
83144       zErrmsg = sqlite3StackAllocZero(db, nMsg);
83145       if( zErrmsg ){
83146         sqlite3_snprintf(nMsg, zErrmsg,
83147             "no entry point [%s] in shared library [%s]", zProc,zFile);
83148         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
83149         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
83150         sqlite3StackFree(db, zErrmsg);
83151       }
83152       sqlite3OsDlClose(pVfs, handle);
83153     }
83154     return SQLITE_ERROR;
83155   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
83156     if( pzErrMsg ){
83157       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
83158     }
83159     sqlite3_free(zErrmsg);
83160     sqlite3OsDlClose(pVfs, handle);
83161     return SQLITE_ERROR;
83162   }
83163
83164   /* Append the new shared library handle to the db->aExtension array. */
83165   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
83166   if( aHandle==0 ){
83167     return SQLITE_NOMEM;
83168   }
83169   if( db->nExtension>0 ){
83170     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
83171   }
83172   sqlite3DbFree(db, db->aExtension);
83173   db->aExtension = aHandle;
83174
83175   db->aExtension[db->nExtension++] = handle;
83176   return SQLITE_OK;
83177 }
83178 SQLITE_API int sqlite3_load_extension(
83179   sqlite3 *db,          /* Load the extension into this database connection */
83180   const char *zFile,    /* Name of the shared library containing extension */
83181   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
83182   char **pzErrMsg       /* Put error message here if not 0 */
83183 ){
83184   int rc;
83185   sqlite3_mutex_enter(db->mutex);
83186   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
83187   rc = sqlite3ApiExit(db, rc);
83188   sqlite3_mutex_leave(db->mutex);
83189   return rc;
83190 }
83191
83192 /*
83193 ** Call this routine when the database connection is closing in order
83194 ** to clean up loaded extensions
83195 */
83196 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
83197   int i;
83198   assert( sqlite3_mutex_held(db->mutex) );
83199   for(i=0; i<db->nExtension; i++){
83200     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
83201   }
83202   sqlite3DbFree(db, db->aExtension);
83203 }
83204
83205 /*
83206 ** Enable or disable extension loading.  Extension loading is disabled by
83207 ** default so as not to open security holes in older applications.
83208 */
83209 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
83210   sqlite3_mutex_enter(db->mutex);
83211   if( onoff ){
83212     db->flags |= SQLITE_LoadExtension;
83213   }else{
83214     db->flags &= ~SQLITE_LoadExtension;
83215   }
83216   sqlite3_mutex_leave(db->mutex);
83217   return SQLITE_OK;
83218 }
83219
83220 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
83221
83222 /*
83223 ** The auto-extension code added regardless of whether or not extension
83224 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
83225 ** code if regular extension loading is not available.  This is that
83226 ** dummy pointer.
83227 */
83228 #ifdef SQLITE_OMIT_LOAD_EXTENSION
83229 static const sqlite3_api_routines sqlite3Apis = { 0 };
83230 #endif
83231
83232
83233 /*
83234 ** The following object holds the list of automatically loaded
83235 ** extensions.
83236 **
83237 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
83238 ** mutex must be held while accessing this list.
83239 */
83240 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
83241 static SQLITE_WSD struct sqlite3AutoExtList {
83242   int nExt;              /* Number of entries in aExt[] */          
83243   void (**aExt)(void);   /* Pointers to the extension init functions */
83244 } sqlite3Autoext = { 0, 0 };
83245
83246 /* The "wsdAutoext" macro will resolve to the autoextension
83247 ** state vector.  If writable static data is unsupported on the target,
83248 ** we have to locate the state vector at run-time.  In the more common
83249 ** case where writable static data is supported, wsdStat can refer directly
83250 ** to the "sqlite3Autoext" state vector declared above.
83251 */
83252 #ifdef SQLITE_OMIT_WSD
83253 # define wsdAutoextInit \
83254   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
83255 # define wsdAutoext x[0]
83256 #else
83257 # define wsdAutoextInit
83258 # define wsdAutoext sqlite3Autoext
83259 #endif
83260
83261
83262 /*
83263 ** Register a statically linked extension that is automatically
83264 ** loaded by every new database connection.
83265 */
83266 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
83267   int rc = SQLITE_OK;
83268 #ifndef SQLITE_OMIT_AUTOINIT
83269   rc = sqlite3_initialize();
83270   if( rc ){
83271     return rc;
83272   }else
83273 #endif
83274   {
83275     int i;
83276 #if SQLITE_THREADSAFE
83277     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83278 #endif
83279     wsdAutoextInit;
83280     sqlite3_mutex_enter(mutex);
83281     for(i=0; i<wsdAutoext.nExt; i++){
83282       if( wsdAutoext.aExt[i]==xInit ) break;
83283     }
83284     if( i==wsdAutoext.nExt ){
83285       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
83286       void (**aNew)(void);
83287       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
83288       if( aNew==0 ){
83289         rc = SQLITE_NOMEM;
83290       }else{
83291         wsdAutoext.aExt = aNew;
83292         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
83293         wsdAutoext.nExt++;
83294       }
83295     }
83296     sqlite3_mutex_leave(mutex);
83297     assert( (rc&0xff)==rc );
83298     return rc;
83299   }
83300 }
83301
83302 /*
83303 ** Reset the automatic extension loading mechanism.
83304 */
83305 SQLITE_API void sqlite3_reset_auto_extension(void){
83306 #ifndef SQLITE_OMIT_AUTOINIT
83307   if( sqlite3_initialize()==SQLITE_OK )
83308 #endif
83309   {
83310 #if SQLITE_THREADSAFE
83311     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83312 #endif
83313     wsdAutoextInit;
83314     sqlite3_mutex_enter(mutex);
83315     sqlite3_free(wsdAutoext.aExt);
83316     wsdAutoext.aExt = 0;
83317     wsdAutoext.nExt = 0;
83318     sqlite3_mutex_leave(mutex);
83319   }
83320 }
83321
83322 /*
83323 ** Load all automatic extensions.
83324 **
83325 ** If anything goes wrong, set an error in the database connection.
83326 */
83327 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
83328   int i;
83329   int go = 1;
83330   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
83331
83332   wsdAutoextInit;
83333   if( wsdAutoext.nExt==0 ){
83334     /* Common case: early out without every having to acquire a mutex */
83335     return;
83336   }
83337   for(i=0; go; i++){
83338     char *zErrmsg;
83339 #if SQLITE_THREADSAFE
83340     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83341 #endif
83342     sqlite3_mutex_enter(mutex);
83343     if( i>=wsdAutoext.nExt ){
83344       xInit = 0;
83345       go = 0;
83346     }else{
83347       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
83348               wsdAutoext.aExt[i];
83349     }
83350     sqlite3_mutex_leave(mutex);
83351     zErrmsg = 0;
83352     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
83353       sqlite3Error(db, SQLITE_ERROR,
83354             "automatic extension loading failed: %s", zErrmsg);
83355       go = 0;
83356     }
83357     sqlite3_free(zErrmsg);
83358   }
83359 }
83360
83361 /************** End of loadext.c *********************************************/
83362 /************** Begin file pragma.c ******************************************/
83363 /*
83364 ** 2003 April 6
83365 **
83366 ** The author disclaims copyright to this source code.  In place of
83367 ** a legal notice, here is a blessing:
83368 **
83369 **    May you do good and not evil.
83370 **    May you find forgiveness for yourself and forgive others.
83371 **    May you share freely, never taking more than you give.
83372 **
83373 *************************************************************************
83374 ** This file contains code used to implement the PRAGMA command.
83375 */
83376
83377 /* Ignore this whole file if pragmas are disabled
83378 */
83379 #if !defined(SQLITE_OMIT_PRAGMA)
83380
83381 /*
83382 ** Interpret the given string as a safety level.  Return 0 for OFF,
83383 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
83384 ** unrecognized string argument.
83385 **
83386 ** Note that the values returned are one less that the values that
83387 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
83388 ** to support legacy SQL code.  The safety level used to be boolean
83389 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
83390 */
83391 static u8 getSafetyLevel(const char *z){
83392                              /* 123456789 123456789 */
83393   static const char zText[] = "onoffalseyestruefull";
83394   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
83395   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
83396   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
83397   int i, n;
83398   if( sqlite3Isdigit(*z) ){
83399     return (u8)atoi(z);
83400   }
83401   n = sqlite3Strlen30(z);
83402   for(i=0; i<ArraySize(iLength); i++){
83403     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
83404       return iValue[i];
83405     }
83406   }
83407   return 1;
83408 }
83409
83410 /*
83411 ** Interpret the given string as a boolean value.
83412 */
83413 static u8 getBoolean(const char *z){
83414   return getSafetyLevel(z)&1;
83415 }
83416
83417 /*
83418 ** Interpret the given string as a locking mode value.
83419 */
83420 static int getLockingMode(const char *z){
83421   if( z ){
83422     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
83423     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
83424   }
83425   return PAGER_LOCKINGMODE_QUERY;
83426 }
83427
83428 #ifndef SQLITE_OMIT_AUTOVACUUM
83429 /*
83430 ** Interpret the given string as an auto-vacuum mode value.
83431 **
83432 ** The following strings, "none", "full" and "incremental" are 
83433 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
83434 */
83435 static int getAutoVacuum(const char *z){
83436   int i;
83437   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
83438   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
83439   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
83440   i = atoi(z);
83441   return (u8)((i>=0&&i<=2)?i:0);
83442 }
83443 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
83444
83445 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83446 /*
83447 ** Interpret the given string as a temp db location. Return 1 for file
83448 ** backed temporary databases, 2 for the Red-Black tree in memory database
83449 ** and 0 to use the compile-time default.
83450 */
83451 static int getTempStore(const char *z){
83452   if( z[0]>='0' && z[0]<='2' ){
83453     return z[0] - '0';
83454   }else if( sqlite3StrICmp(z, "file")==0 ){
83455     return 1;
83456   }else if( sqlite3StrICmp(z, "memory")==0 ){
83457     return 2;
83458   }else{
83459     return 0;
83460   }
83461 }
83462 #endif /* SQLITE_PAGER_PRAGMAS */
83463
83464 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83465 /*
83466 ** Invalidate temp storage, either when the temp storage is changed
83467 ** from default, or when 'file' and the temp_store_directory has changed
83468 */
83469 static int invalidateTempStorage(Parse *pParse){
83470   sqlite3 *db = pParse->db;
83471   if( db->aDb[1].pBt!=0 ){
83472     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
83473       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
83474         "from within a transaction");
83475       return SQLITE_ERROR;
83476     }
83477     sqlite3BtreeClose(db->aDb[1].pBt);
83478     db->aDb[1].pBt = 0;
83479     sqlite3ResetInternalSchema(db, 0);
83480   }
83481   return SQLITE_OK;
83482 }
83483 #endif /* SQLITE_PAGER_PRAGMAS */
83484
83485 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83486 /*
83487 ** If the TEMP database is open, close it and mark the database schema
83488 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
83489 ** or DEFAULT_TEMP_STORE pragmas.
83490 */
83491 static int changeTempStorage(Parse *pParse, const char *zStorageType){
83492   int ts = getTempStore(zStorageType);
83493   sqlite3 *db = pParse->db;
83494   if( db->temp_store==ts ) return SQLITE_OK;
83495   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
83496     return SQLITE_ERROR;
83497   }
83498   db->temp_store = (u8)ts;
83499   return SQLITE_OK;
83500 }
83501 #endif /* SQLITE_PAGER_PRAGMAS */
83502
83503 /*
83504 ** Generate code to return a single integer value.
83505 */
83506 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
83507   Vdbe *v = sqlite3GetVdbe(pParse);
83508   int mem = ++pParse->nMem;
83509   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
83510   if( pI64 ){
83511     memcpy(pI64, &value, sizeof(value));
83512   }
83513   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
83514   sqlite3VdbeSetNumCols(v, 1);
83515   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
83516   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
83517 }
83518
83519 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
83520 /*
83521 ** Check to see if zRight and zLeft refer to a pragma that queries
83522 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
83523 ** Also, implement the pragma.
83524 */
83525 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
83526   static const struct sPragmaType {
83527     const char *zName;  /* Name of the pragma */
83528     int mask;           /* Mask for the db->flags value */
83529   } aPragma[] = {
83530     { "full_column_names",        SQLITE_FullColNames  },
83531     { "short_column_names",       SQLITE_ShortColNames },
83532     { "count_changes",            SQLITE_CountRows     },
83533     { "empty_result_callbacks",   SQLITE_NullCallback  },
83534     { "legacy_file_format",       SQLITE_LegacyFileFmt },
83535     { "fullfsync",                SQLITE_FullFSync     },
83536     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
83537 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
83538     { "automatic_index",          SQLITE_AutoIndex     },
83539 #endif
83540 #ifdef SQLITE_DEBUG
83541     { "sql_trace",                SQLITE_SqlTrace      },
83542     { "vdbe_listing",             SQLITE_VdbeListing   },
83543     { "vdbe_trace",               SQLITE_VdbeTrace     },
83544 #endif
83545 #ifndef SQLITE_OMIT_CHECK
83546     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
83547 #endif
83548     /* The following is VERY experimental */
83549     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
83550     { "omit_readlock",            SQLITE_NoReadlock    },
83551
83552     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
83553     ** flag if there are any active statements. */
83554     { "read_uncommitted",         SQLITE_ReadUncommitted },
83555     { "recursive_triggers",       SQLITE_RecTriggers },
83556
83557     /* This flag may only be set if both foreign-key and trigger support
83558     ** are present in the build.  */
83559 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
83560     { "foreign_keys",             SQLITE_ForeignKeys },
83561 #endif
83562   };
83563   int i;
83564   const struct sPragmaType *p;
83565   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
83566     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
83567       sqlite3 *db = pParse->db;
83568       Vdbe *v;
83569       v = sqlite3GetVdbe(pParse);
83570       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
83571       if( ALWAYS(v) ){
83572         if( zRight==0 ){
83573           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
83574         }else{
83575           int mask = p->mask;          /* Mask of bits to set or clear. */
83576           if( db->autoCommit==0 ){
83577             /* Foreign key support may not be enabled or disabled while not
83578             ** in auto-commit mode.  */
83579             mask &= ~(SQLITE_ForeignKeys);
83580           }
83581
83582           if( getBoolean(zRight) ){
83583             db->flags |= mask;
83584           }else{
83585             db->flags &= ~mask;
83586           }
83587
83588           /* Many of the flag-pragmas modify the code generated by the SQL 
83589           ** compiler (eg. count_changes). So add an opcode to expire all
83590           ** compiled SQL statements after modifying a pragma value.
83591           */
83592           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
83593         }
83594       }
83595
83596       return 1;
83597     }
83598   }
83599   return 0;
83600 }
83601 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
83602
83603 /*
83604 ** Return a human-readable name for a constraint resolution action.
83605 */
83606 #ifndef SQLITE_OMIT_FOREIGN_KEY
83607 static const char *actionName(u8 action){
83608   const char *zName;
83609   switch( action ){
83610     case OE_SetNull:  zName = "SET NULL";        break;
83611     case OE_SetDflt:  zName = "SET DEFAULT";     break;
83612     case OE_Cascade:  zName = "CASCADE";         break;
83613     case OE_Restrict: zName = "RESTRICT";        break;
83614     default:          zName = "NO ACTION";  
83615                       assert( action==OE_None ); break;
83616   }
83617   return zName;
83618 }
83619 #endif
83620
83621
83622 /*
83623 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
83624 ** defined in pager.h. This function returns the associated lowercase
83625 ** journal-mode name.
83626 */
83627 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
83628   static char * const azModeName[] = {
83629     "delete", "persist", "off", "truncate", "memory"
83630 #ifndef SQLITE_OMIT_WAL
83631      , "wal"
83632 #endif
83633   };
83634   assert( PAGER_JOURNALMODE_DELETE==0 );
83635   assert( PAGER_JOURNALMODE_PERSIST==1 );
83636   assert( PAGER_JOURNALMODE_OFF==2 );
83637   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
83638   assert( PAGER_JOURNALMODE_MEMORY==4 );
83639   assert( PAGER_JOURNALMODE_WAL==5 );
83640   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
83641
83642   if( eMode==ArraySize(azModeName) ) return 0;
83643   return azModeName[eMode];
83644 }
83645
83646 /*
83647 ** Process a pragma statement.  
83648 **
83649 ** Pragmas are of this form:
83650 **
83651 **      PRAGMA [database.]id [= value]
83652 **
83653 ** The identifier might also be a string.  The value is a string, and
83654 ** identifier, or a number.  If minusFlag is true, then the value is
83655 ** a number that was preceded by a minus sign.
83656 **
83657 ** If the left side is "database.id" then pId1 is the database name
83658 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
83659 ** id and pId2 is any empty string.
83660 */
83661 SQLITE_PRIVATE void sqlite3Pragma(
83662   Parse *pParse, 
83663   Token *pId1,        /* First part of [database.]id field */
83664   Token *pId2,        /* Second part of [database.]id field, or NULL */
83665   Token *pValue,      /* Token for <value>, or NULL */
83666   int minusFlag       /* True if a '-' sign preceded <value> */
83667 ){
83668   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
83669   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
83670   const char *zDb = 0;   /* The database name */
83671   Token *pId;            /* Pointer to <id> token */
83672   int iDb;               /* Database index for <database> */
83673   sqlite3 *db = pParse->db;
83674   Db *pDb;
83675   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
83676   if( v==0 ) return;
83677   sqlite3VdbeRunOnlyOnce(v);
83678   pParse->nMem = 2;
83679
83680   /* Interpret the [database.] part of the pragma statement. iDb is the
83681   ** index of the database this pragma is being applied to in db.aDb[]. */
83682   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
83683   if( iDb<0 ) return;
83684   pDb = &db->aDb[iDb];
83685
83686   /* If the temp database has been explicitly named as part of the 
83687   ** pragma, make sure it is open. 
83688   */
83689   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
83690     return;
83691   }
83692
83693   zLeft = sqlite3NameFromToken(db, pId);
83694   if( !zLeft ) return;
83695   if( minusFlag ){
83696     zRight = sqlite3MPrintf(db, "-%T", pValue);
83697   }else{
83698     zRight = sqlite3NameFromToken(db, pValue);
83699   }
83700
83701   assert( pId2 );
83702   zDb = pId2->n>0 ? pDb->zName : 0;
83703   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
83704     goto pragma_out;
83705   }
83706  
83707 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83708   /*
83709   **  PRAGMA [database.]default_cache_size
83710   **  PRAGMA [database.]default_cache_size=N
83711   **
83712   ** The first form reports the current persistent setting for the
83713   ** page cache size.  The value returned is the maximum number of
83714   ** pages in the page cache.  The second form sets both the current
83715   ** page cache size value and the persistent page cache size value
83716   ** stored in the database file.
83717   **
83718   ** Older versions of SQLite would set the default cache size to a
83719   ** negative number to indicate synchronous=OFF.  These days, synchronous
83720   ** is always on by default regardless of the sign of the default cache
83721   ** size.  But continue to take the absolute value of the default cache
83722   ** size of historical compatibility.
83723   */
83724   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
83725     static const VdbeOpList getCacheSize[] = {
83726       { OP_Transaction, 0, 0,        0},                         /* 0 */
83727       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
83728       { OP_IfPos,       1, 7,        0},
83729       { OP_Integer,     0, 2,        0},
83730       { OP_Subtract,    1, 2,        1},
83731       { OP_IfPos,       1, 7,        0},
83732       { OP_Integer,     0, 1,        0},                         /* 6 */
83733       { OP_ResultRow,   1, 1,        0},
83734     };
83735     int addr;
83736     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83737     sqlite3VdbeUsesBtree(v, iDb);
83738     if( !zRight ){
83739       sqlite3VdbeSetNumCols(v, 1);
83740       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
83741       pParse->nMem += 2;
83742       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
83743       sqlite3VdbeChangeP1(v, addr, iDb);
83744       sqlite3VdbeChangeP1(v, addr+1, iDb);
83745       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
83746     }else{
83747       int size = atoi(zRight);
83748       if( size<0 ) size = -size;
83749       sqlite3BeginWriteOperation(pParse, 0, iDb);
83750       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
83751       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
83752       pDb->pSchema->cache_size = size;
83753       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
83754     }
83755   }else
83756
83757   /*
83758   **  PRAGMA [database.]page_size
83759   **  PRAGMA [database.]page_size=N
83760   **
83761   ** The first form reports the current setting for the
83762   ** database page size in bytes.  The second form sets the
83763   ** database page size value.  The value can only be set if
83764   ** the database has not yet been created.
83765   */
83766   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
83767     Btree *pBt = pDb->pBt;
83768     assert( pBt!=0 );
83769     if( !zRight ){
83770       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
83771       returnSingleInt(pParse, "page_size", size);
83772     }else{
83773       /* Malloc may fail when setting the page-size, as there is an internal
83774       ** buffer that the pager module resizes using sqlite3_realloc().
83775       */
83776       db->nextPagesize = atoi(zRight);
83777       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
83778         db->mallocFailed = 1;
83779       }
83780     }
83781   }else
83782
83783   /*
83784   **  PRAGMA [database.]max_page_count
83785   **  PRAGMA [database.]max_page_count=N
83786   **
83787   ** The first form reports the current setting for the
83788   ** maximum number of pages in the database file.  The 
83789   ** second form attempts to change this setting.  Both
83790   ** forms return the current setting.
83791   */
83792   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
83793     Btree *pBt = pDb->pBt;
83794     int newMax = 0;
83795     assert( pBt!=0 );
83796     if( zRight ){
83797       newMax = atoi(zRight);
83798     }
83799     if( ALWAYS(pBt) ){
83800       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
83801     }
83802     returnSingleInt(pParse, "max_page_count", newMax);
83803   }else
83804
83805   /*
83806   **  PRAGMA [database.]secure_delete
83807   **  PRAGMA [database.]secure_delete=ON/OFF
83808   **
83809   ** The first form reports the current setting for the
83810   ** secure_delete flag.  The second form changes the secure_delete
83811   ** flag setting and reports thenew value.
83812   */
83813   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
83814     Btree *pBt = pDb->pBt;
83815     int b = -1;
83816     assert( pBt!=0 );
83817     if( zRight ){
83818       b = getBoolean(zRight);
83819     }
83820     if( pId2->n==0 && b>=0 ){
83821       int ii;
83822       for(ii=0; ii<db->nDb; ii++){
83823         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
83824       }
83825     }
83826     b = sqlite3BtreeSecureDelete(pBt, b);
83827     returnSingleInt(pParse, "secure_delete", b);
83828   }else
83829
83830   /*
83831   **  PRAGMA [database.]page_count
83832   **
83833   ** Return the number of pages in the specified database.
83834   */
83835   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
83836     int iReg;
83837     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83838     sqlite3CodeVerifySchema(pParse, iDb);
83839     iReg = ++pParse->nMem;
83840     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
83841     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
83842     sqlite3VdbeSetNumCols(v, 1);
83843     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
83844   }else
83845
83846   /*
83847   **  PRAGMA [database.]locking_mode
83848   **  PRAGMA [database.]locking_mode = (normal|exclusive)
83849   */
83850   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
83851     const char *zRet = "normal";
83852     int eMode = getLockingMode(zRight);
83853
83854     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
83855       /* Simple "PRAGMA locking_mode;" statement. This is a query for
83856       ** the current default locking mode (which may be different to
83857       ** the locking-mode of the main database).
83858       */
83859       eMode = db->dfltLockMode;
83860     }else{
83861       Pager *pPager;
83862       if( pId2->n==0 ){
83863         /* This indicates that no database name was specified as part
83864         ** of the PRAGMA command. In this case the locking-mode must be
83865         ** set on all attached databases, as well as the main db file.
83866         **
83867         ** Also, the sqlite3.dfltLockMode variable is set so that
83868         ** any subsequently attached databases also use the specified
83869         ** locking mode.
83870         */
83871         int ii;
83872         assert(pDb==&db->aDb[0]);
83873         for(ii=2; ii<db->nDb; ii++){
83874           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
83875           sqlite3PagerLockingMode(pPager, eMode);
83876         }
83877         db->dfltLockMode = (u8)eMode;
83878       }
83879       pPager = sqlite3BtreePager(pDb->pBt);
83880       eMode = sqlite3PagerLockingMode(pPager, eMode);
83881     }
83882
83883     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
83884     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
83885       zRet = "exclusive";
83886     }
83887     sqlite3VdbeSetNumCols(v, 1);
83888     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
83889     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
83890     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83891   }else
83892
83893   /*
83894   **  PRAGMA [database.]journal_mode
83895   **  PRAGMA [database.]journal_mode =
83896   **                      (delete|persist|off|truncate|memory|wal|off)
83897   */
83898   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
83899     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
83900     int ii;           /* Loop counter */
83901
83902     /* Force the schema to be loaded on all databases.  This cases all
83903     ** database files to be opened and the journal_modes set. */
83904     if( sqlite3ReadSchema(pParse) ){
83905       goto pragma_out;
83906     }
83907
83908     sqlite3VdbeSetNumCols(v, 1);
83909     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
83910
83911     if( zRight==0 ){
83912       /* If there is no "=MODE" part of the pragma, do a query for the
83913       ** current mode */
83914       eMode = PAGER_JOURNALMODE_QUERY;
83915     }else{
83916       const char *zMode;
83917       int n = sqlite3Strlen30(zRight);
83918       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
83919         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
83920       }
83921       if( !zMode ){
83922         /* If the "=MODE" part does not match any known journal mode,
83923         ** then do a query */
83924         eMode = PAGER_JOURNALMODE_QUERY;
83925       }
83926     }
83927     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
83928       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
83929       iDb = 0;
83930       pId2->n = 1;
83931     }
83932     for(ii=db->nDb-1; ii>=0; ii--){
83933       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
83934         sqlite3VdbeUsesBtree(v, ii);
83935         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
83936       }
83937     }
83938     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83939   }else
83940
83941   /*
83942   **  PRAGMA [database.]journal_size_limit
83943   **  PRAGMA [database.]journal_size_limit=N
83944   **
83945   ** Get or set the size limit on rollback journal files.
83946   */
83947   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
83948     Pager *pPager = sqlite3BtreePager(pDb->pBt);
83949     i64 iLimit = -2;
83950     if( zRight ){
83951       sqlite3Atoi64(zRight, &iLimit);
83952       if( iLimit<-1 ) iLimit = -1;
83953     }
83954     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
83955     returnSingleInt(pParse, "journal_size_limit", iLimit);
83956   }else
83957
83958 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
83959
83960   /*
83961   **  PRAGMA [database.]auto_vacuum
83962   **  PRAGMA [database.]auto_vacuum=N
83963   **
83964   ** Get or set the value of the database 'auto-vacuum' parameter.
83965   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
83966   */
83967 #ifndef SQLITE_OMIT_AUTOVACUUM
83968   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
83969     Btree *pBt = pDb->pBt;
83970     assert( pBt!=0 );
83971     if( sqlite3ReadSchema(pParse) ){
83972       goto pragma_out;
83973     }
83974     if( !zRight ){
83975       int auto_vacuum;
83976       if( ALWAYS(pBt) ){
83977          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
83978       }else{
83979          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
83980       }
83981       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
83982     }else{
83983       int eAuto = getAutoVacuum(zRight);
83984       assert( eAuto>=0 && eAuto<=2 );
83985       db->nextAutovac = (u8)eAuto;
83986       if( ALWAYS(eAuto>=0) ){
83987         /* Call SetAutoVacuum() to set initialize the internal auto and
83988         ** incr-vacuum flags. This is required in case this connection
83989         ** creates the database file. It is important that it is created
83990         ** as an auto-vacuum capable db.
83991         */
83992         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
83993         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
83994           /* When setting the auto_vacuum mode to either "full" or 
83995           ** "incremental", write the value of meta[6] in the database
83996           ** file. Before writing to meta[6], check that meta[3] indicates
83997           ** that this really is an auto-vacuum capable database.
83998           */
83999           static const VdbeOpList setMeta6[] = {
84000             { OP_Transaction,    0,         1,                 0},    /* 0 */
84001             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
84002             { OP_If,             1,         0,                 0},    /* 2 */
84003             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
84004             { OP_Integer,        0,         1,                 0},    /* 4 */
84005             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
84006           };
84007           int iAddr;
84008           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
84009           sqlite3VdbeChangeP1(v, iAddr, iDb);
84010           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
84011           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
84012           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
84013           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
84014           sqlite3VdbeUsesBtree(v, iDb);
84015         }
84016       }
84017     }
84018   }else
84019 #endif
84020
84021   /*
84022   **  PRAGMA [database.]incremental_vacuum(N)
84023   **
84024   ** Do N steps of incremental vacuuming on a database.
84025   */
84026 #ifndef SQLITE_OMIT_AUTOVACUUM
84027   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
84028     int iLimit, addr;
84029     if( sqlite3ReadSchema(pParse) ){
84030       goto pragma_out;
84031     }
84032     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
84033       iLimit = 0x7fffffff;
84034     }
84035     sqlite3BeginWriteOperation(pParse, 0, iDb);
84036     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
84037     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
84038     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
84039     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
84040     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
84041     sqlite3VdbeJumpHere(v, addr);
84042   }else
84043 #endif
84044
84045 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84046   /*
84047   **  PRAGMA [database.]cache_size
84048   **  PRAGMA [database.]cache_size=N
84049   **
84050   ** The first form reports the current local setting for the
84051   ** page cache size.  The local setting can be different from
84052   ** the persistent cache size value that is stored in the database
84053   ** file itself.  The value returned is the maximum number of
84054   ** pages in the page cache.  The second form sets the local
84055   ** page cache size value.  It does not change the persistent
84056   ** cache size stored on the disk so the cache size will revert
84057   ** to its default value when the database is closed and reopened.
84058   ** N should be a positive integer.
84059   */
84060   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
84061     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84062     if( !zRight ){
84063       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
84064     }else{
84065       int size = atoi(zRight);
84066       if( size<0 ) size = -size;
84067       pDb->pSchema->cache_size = size;
84068       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84069     }
84070   }else
84071
84072   /*
84073   **   PRAGMA temp_store
84074   **   PRAGMA temp_store = "default"|"memory"|"file"
84075   **
84076   ** Return or set the local value of the temp_store flag.  Changing
84077   ** the local value does not make changes to the disk file and the default
84078   ** value will be restored the next time the database is opened.
84079   **
84080   ** Note that it is possible for the library compile-time options to
84081   ** override this setting
84082   */
84083   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
84084     if( !zRight ){
84085       returnSingleInt(pParse, "temp_store", db->temp_store);
84086     }else{
84087       changeTempStorage(pParse, zRight);
84088     }
84089   }else
84090
84091   /*
84092   **   PRAGMA temp_store_directory
84093   **   PRAGMA temp_store_directory = ""|"directory_name"
84094   **
84095   ** Return or set the local value of the temp_store_directory flag.  Changing
84096   ** the value sets a specific directory to be used for temporary files.
84097   ** Setting to a null string reverts to the default temporary directory search.
84098   ** If temporary directory is changed, then invalidateTempStorage.
84099   **
84100   */
84101   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
84102     if( !zRight ){
84103       if( sqlite3_temp_directory ){
84104         sqlite3VdbeSetNumCols(v, 1);
84105         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
84106             "temp_store_directory", SQLITE_STATIC);
84107         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
84108         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84109       }
84110     }else{
84111 #ifndef SQLITE_OMIT_WSD
84112       if( zRight[0] ){
84113         int rc;
84114         int res;
84115         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
84116         if( rc!=SQLITE_OK || res==0 ){
84117           sqlite3ErrorMsg(pParse, "not a writable directory");
84118           goto pragma_out;
84119         }
84120       }
84121       if( SQLITE_TEMP_STORE==0
84122        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
84123        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
84124       ){
84125         invalidateTempStorage(pParse);
84126       }
84127       sqlite3_free(sqlite3_temp_directory);
84128       if( zRight[0] ){
84129         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
84130       }else{
84131         sqlite3_temp_directory = 0;
84132       }
84133 #endif /* SQLITE_OMIT_WSD */
84134     }
84135   }else
84136
84137 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
84138 #  if defined(__APPLE__)
84139 #    define SQLITE_ENABLE_LOCKING_STYLE 1
84140 #  else
84141 #    define SQLITE_ENABLE_LOCKING_STYLE 0
84142 #  endif
84143 #endif
84144 #if SQLITE_ENABLE_LOCKING_STYLE
84145   /*
84146    **   PRAGMA [database.]lock_proxy_file
84147    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
84148    **
84149    ** Return or set the value of the lock_proxy_file flag.  Changing
84150    ** the value sets a specific file to be used for database access locks.
84151    **
84152    */
84153   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
84154     if( !zRight ){
84155       Pager *pPager = sqlite3BtreePager(pDb->pBt);
84156       char *proxy_file_path = NULL;
84157       sqlite3_file *pFile = sqlite3PagerFile(pPager);
84158       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
84159                            &proxy_file_path);
84160       
84161       if( proxy_file_path ){
84162         sqlite3VdbeSetNumCols(v, 1);
84163         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
84164                               "lock_proxy_file", SQLITE_STATIC);
84165         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
84166         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84167       }
84168     }else{
84169       Pager *pPager = sqlite3BtreePager(pDb->pBt);
84170       sqlite3_file *pFile = sqlite3PagerFile(pPager);
84171       int res;
84172       if( zRight[0] ){
84173         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
84174                                      zRight);
84175       } else {
84176         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
84177                                      NULL);
84178       }
84179       if( res!=SQLITE_OK ){
84180         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
84181         goto pragma_out;
84182       }
84183     }
84184   }else
84185 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
84186     
84187   /*
84188   **   PRAGMA [database.]synchronous
84189   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
84190   **
84191   ** Return or set the local value of the synchronous flag.  Changing
84192   ** the local value does not make changes to the disk file and the
84193   ** default value will be restored the next time the database is
84194   ** opened.
84195   */
84196   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
84197     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84198     if( !zRight ){
84199       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
84200     }else{
84201       if( !db->autoCommit ){
84202         sqlite3ErrorMsg(pParse, 
84203             "Safety level may not be changed inside a transaction");
84204       }else{
84205         pDb->safety_level = getSafetyLevel(zRight)+1;
84206       }
84207     }
84208   }else
84209 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
84210
84211 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
84212   if( flagPragma(pParse, zLeft, zRight) ){
84213     /* The flagPragma() subroutine also generates any necessary code
84214     ** there is nothing more to do here */
84215   }else
84216 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
84217
84218 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
84219   /*
84220   **   PRAGMA table_info(<table>)
84221   **
84222   ** Return a single row for each column of the named table. The columns of
84223   ** the returned data set are:
84224   **
84225   ** cid:        Column id (numbered from left to right, starting at 0)
84226   ** name:       Column name
84227   ** type:       Column declaration type.
84228   ** notnull:    True if 'NOT NULL' is part of column declaration
84229   ** dflt_value: The default value for the column, if any.
84230   */
84231   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
84232     Table *pTab;
84233     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84234     pTab = sqlite3FindTable(db, zRight, zDb);
84235     if( pTab ){
84236       int i;
84237       int nHidden = 0;
84238       Column *pCol;
84239       sqlite3VdbeSetNumCols(v, 6);
84240       pParse->nMem = 6;
84241       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
84242       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84243       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
84244       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
84245       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
84246       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
84247       sqlite3ViewGetColumnNames(pParse, pTab);
84248       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
84249         if( IsHiddenColumn(pCol) ){
84250           nHidden++;
84251           continue;
84252         }
84253         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
84254         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
84255         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84256            pCol->zType ? pCol->zType : "", 0);
84257         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
84258         if( pCol->zDflt ){
84259           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
84260         }else{
84261           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
84262         }
84263         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
84264         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
84265       }
84266     }
84267   }else
84268
84269   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
84270     Index *pIdx;
84271     Table *pTab;
84272     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84273     pIdx = sqlite3FindIndex(db, zRight, zDb);
84274     if( pIdx ){
84275       int i;
84276       pTab = pIdx->pTable;
84277       sqlite3VdbeSetNumCols(v, 3);
84278       pParse->nMem = 3;
84279       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
84280       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
84281       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
84282       for(i=0; i<pIdx->nColumn; i++){
84283         int cnum = pIdx->aiColumn[i];
84284         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84285         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
84286         assert( pTab->nCol>cnum );
84287         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
84288         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84289       }
84290     }
84291   }else
84292
84293   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
84294     Index *pIdx;
84295     Table *pTab;
84296     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84297     pTab = sqlite3FindTable(db, zRight, zDb);
84298     if( pTab ){
84299       v = sqlite3GetVdbe(pParse);
84300       pIdx = pTab->pIndex;
84301       if( pIdx ){
84302         int i = 0; 
84303         sqlite3VdbeSetNumCols(v, 3);
84304         pParse->nMem = 3;
84305         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84306         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84307         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
84308         while(pIdx){
84309           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84310           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
84311           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
84312           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84313           ++i;
84314           pIdx = pIdx->pNext;
84315         }
84316       }
84317     }
84318   }else
84319
84320   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
84321     int i;
84322     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84323     sqlite3VdbeSetNumCols(v, 3);
84324     pParse->nMem = 3;
84325     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84326     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84327     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
84328     for(i=0; i<db->nDb; i++){
84329       if( db->aDb[i].pBt==0 ) continue;
84330       assert( db->aDb[i].zName!=0 );
84331       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84332       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
84333       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84334            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
84335       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84336     }
84337   }else
84338
84339   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
84340     int i = 0;
84341     HashElem *p;
84342     sqlite3VdbeSetNumCols(v, 2);
84343     pParse->nMem = 2;
84344     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84345     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84346     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
84347       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
84348       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
84349       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
84350       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
84351     }
84352   }else
84353 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
84354
84355 #ifndef SQLITE_OMIT_FOREIGN_KEY
84356   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
84357     FKey *pFK;
84358     Table *pTab;
84359     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84360     pTab = sqlite3FindTable(db, zRight, zDb);
84361     if( pTab ){
84362       v = sqlite3GetVdbe(pParse);
84363       pFK = pTab->pFKey;
84364       if( pFK ){
84365         int i = 0; 
84366         sqlite3VdbeSetNumCols(v, 8);
84367         pParse->nMem = 8;
84368         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
84369         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
84370         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
84371         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
84372         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
84373         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
84374         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
84375         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
84376         while(pFK){
84377           int j;
84378           for(j=0; j<pFK->nCol; j++){
84379             char *zCol = pFK->aCol[j].zCol;
84380             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
84381             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
84382             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84383             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
84384             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
84385             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
84386                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
84387             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
84388             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
84389             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
84390             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
84391             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
84392           }
84393           ++i;
84394           pFK = pFK->pNextFrom;
84395         }
84396       }
84397     }
84398   }else
84399 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84400
84401 #ifndef NDEBUG
84402   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
84403     if( zRight ){
84404       if( getBoolean(zRight) ){
84405         sqlite3ParserTrace(stderr, "parser: ");
84406       }else{
84407         sqlite3ParserTrace(0, 0);
84408       }
84409     }
84410   }else
84411 #endif
84412
84413   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
84414   ** used will be case sensitive or not depending on the RHS.
84415   */
84416   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
84417     if( zRight ){
84418       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
84419     }
84420   }else
84421
84422 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
84423 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
84424 #endif
84425
84426 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
84427   /* Pragma "quick_check" is an experimental reduced version of 
84428   ** integrity_check designed to detect most database corruption
84429   ** without most of the overhead of a full integrity-check.
84430   */
84431   if( sqlite3StrICmp(zLeft, "integrity_check")==0
84432    || sqlite3StrICmp(zLeft, "quick_check")==0 
84433   ){
84434     int i, j, addr, mxErr;
84435
84436     /* Code that appears at the end of the integrity check.  If no error
84437     ** messages have been generated, output OK.  Otherwise output the
84438     ** error message
84439     */
84440     static const VdbeOpList endCode[] = {
84441       { OP_AddImm,      1, 0,        0},    /* 0 */
84442       { OP_IfNeg,       1, 0,        0},    /* 1 */
84443       { OP_String8,     0, 3,        0},    /* 2 */
84444       { OP_ResultRow,   3, 1,        0},
84445     };
84446
84447     int isQuick = (zLeft[0]=='q');
84448
84449     /* Initialize the VDBE program */
84450     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84451     pParse->nMem = 6;
84452     sqlite3VdbeSetNumCols(v, 1);
84453     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
84454
84455     /* Set the maximum error count */
84456     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84457     if( zRight ){
84458       mxErr = atoi(zRight);
84459       if( mxErr<=0 ){
84460         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84461       }
84462     }
84463     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
84464
84465     /* Do an integrity check on each database file */
84466     for(i=0; i<db->nDb; i++){
84467       HashElem *x;
84468       Hash *pTbls;
84469       int cnt = 0;
84470
84471       if( OMIT_TEMPDB && i==1 ) continue;
84472
84473       sqlite3CodeVerifySchema(pParse, i);
84474       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
84475       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84476       sqlite3VdbeJumpHere(v, addr);
84477
84478       /* Do an integrity check of the B-Tree
84479       **
84480       ** Begin by filling registers 2, 3, ... with the root pages numbers
84481       ** for all tables and indices in the database.
84482       */
84483       pTbls = &db->aDb[i].pSchema->tblHash;
84484       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
84485         Table *pTab = sqliteHashData(x);
84486         Index *pIdx;
84487         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
84488         cnt++;
84489         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84490           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
84491           cnt++;
84492         }
84493       }
84494
84495       /* Make sure sufficient number of registers have been allocated */
84496       if( pParse->nMem < cnt+4 ){
84497         pParse->nMem = cnt+4;
84498       }
84499
84500       /* Do the b-tree integrity checks */
84501       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
84502       sqlite3VdbeChangeP5(v, (u8)i);
84503       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
84504       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84505          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
84506          P4_DYNAMIC);
84507       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
84508       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
84509       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
84510       sqlite3VdbeJumpHere(v, addr);
84511
84512       /* Make sure all the indices are constructed correctly.
84513       */
84514       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
84515         Table *pTab = sqliteHashData(x);
84516         Index *pIdx;
84517         int loopTop;
84518
84519         if( pTab->pIndex==0 ) continue;
84520         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
84521         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84522         sqlite3VdbeJumpHere(v, addr);
84523         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
84524         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
84525         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
84526         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
84527         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84528           int jmp2;
84529           int r1;
84530           static const VdbeOpList idxErr[] = {
84531             { OP_AddImm,      1, -1,  0},
84532             { OP_String8,     0,  3,  0},    /* 1 */
84533             { OP_Rowid,       1,  4,  0},
84534             { OP_String8,     0,  5,  0},    /* 3 */
84535             { OP_String8,     0,  6,  0},    /* 4 */
84536             { OP_Concat,      4,  3,  3},
84537             { OP_Concat,      5,  3,  3},
84538             { OP_Concat,      6,  3,  3},
84539             { OP_ResultRow,   3,  1,  0},
84540             { OP_IfPos,       1,  0,  0},    /* 9 */
84541             { OP_Halt,        0,  0,  0},
84542           };
84543           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
84544           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
84545           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
84546           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
84547           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
84548           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
84549           sqlite3VdbeJumpHere(v, addr+9);
84550           sqlite3VdbeJumpHere(v, jmp2);
84551         }
84552         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
84553         sqlite3VdbeJumpHere(v, loopTop);
84554         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84555           static const VdbeOpList cntIdx[] = {
84556              { OP_Integer,      0,  3,  0},
84557              { OP_Rewind,       0,  0,  0},  /* 1 */
84558              { OP_AddImm,       3,  1,  0},
84559              { OP_Next,         0,  0,  0},  /* 3 */
84560              { OP_Eq,           2,  0,  3},  /* 4 */
84561              { OP_AddImm,       1, -1,  0},
84562              { OP_String8,      0,  2,  0},  /* 6 */
84563              { OP_String8,      0,  3,  0},  /* 7 */
84564              { OP_Concat,       3,  2,  2},
84565              { OP_ResultRow,    2,  1,  0},
84566           };
84567           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
84568           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84569           sqlite3VdbeJumpHere(v, addr);
84570           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
84571           sqlite3VdbeChangeP1(v, addr+1, j+2);
84572           sqlite3VdbeChangeP2(v, addr+1, addr+4);
84573           sqlite3VdbeChangeP1(v, addr+3, j+2);
84574           sqlite3VdbeChangeP2(v, addr+3, addr+2);
84575           sqlite3VdbeJumpHere(v, addr+4);
84576           sqlite3VdbeChangeP4(v, addr+6, 
84577                      "wrong # of entries in index ", P4_STATIC);
84578           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
84579         }
84580       } 
84581     }
84582     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
84583     sqlite3VdbeChangeP2(v, addr, -mxErr);
84584     sqlite3VdbeJumpHere(v, addr+1);
84585     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
84586   }else
84587 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
84588
84589 #ifndef SQLITE_OMIT_UTF16
84590   /*
84591   **   PRAGMA encoding
84592   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
84593   **
84594   ** In its first form, this pragma returns the encoding of the main
84595   ** database. If the database is not initialized, it is initialized now.
84596   **
84597   ** The second form of this pragma is a no-op if the main database file
84598   ** has not already been initialized. In this case it sets the default
84599   ** encoding that will be used for the main database file if a new file
84600   ** is created. If an existing main database file is opened, then the
84601   ** default text encoding for the existing database is used.
84602   ** 
84603   ** In all cases new databases created using the ATTACH command are
84604   ** created to use the same default text encoding as the main database. If
84605   ** the main database has not been initialized and/or created when ATTACH
84606   ** is executed, this is done before the ATTACH operation.
84607   **
84608   ** In the second form this pragma sets the text encoding to be used in
84609   ** new database files created using this database handle. It is only
84610   ** useful if invoked immediately after the main database i
84611   */
84612   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
84613     static const struct EncName {
84614       char *zName;
84615       u8 enc;
84616     } encnames[] = {
84617       { "UTF8",     SQLITE_UTF8        },
84618       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
84619       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
84620       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
84621       { "UTF16le",  SQLITE_UTF16LE     },
84622       { "UTF16be",  SQLITE_UTF16BE     },
84623       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
84624       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
84625       { 0, 0 }
84626     };
84627     const struct EncName *pEnc;
84628     if( !zRight ){    /* "PRAGMA encoding" */
84629       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84630       sqlite3VdbeSetNumCols(v, 1);
84631       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
84632       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
84633       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
84634       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
84635       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
84636       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
84637       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84638     }else{                        /* "PRAGMA encoding = XXX" */
84639       /* Only change the value of sqlite.enc if the database handle is not
84640       ** initialized. If the main database exists, the new sqlite.enc value
84641       ** will be overwritten when the schema is next loaded. If it does not
84642       ** already exists, it will be created to use the new encoding value.
84643       */
84644       if( 
84645         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
84646         DbHasProperty(db, 0, DB_Empty) 
84647       ){
84648         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
84649           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
84650             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
84651             break;
84652           }
84653         }
84654         if( !pEnc->zName ){
84655           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
84656         }
84657       }
84658     }
84659   }else
84660 #endif /* SQLITE_OMIT_UTF16 */
84661
84662 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
84663   /*
84664   **   PRAGMA [database.]schema_version
84665   **   PRAGMA [database.]schema_version = <integer>
84666   **
84667   **   PRAGMA [database.]user_version
84668   **   PRAGMA [database.]user_version = <integer>
84669   **
84670   ** The pragma's schema_version and user_version are used to set or get
84671   ** the value of the schema-version and user-version, respectively. Both
84672   ** the schema-version and the user-version are 32-bit signed integers
84673   ** stored in the database header.
84674   **
84675   ** The schema-cookie is usually only manipulated internally by SQLite. It
84676   ** is incremented by SQLite whenever the database schema is modified (by
84677   ** creating or dropping a table or index). The schema version is used by
84678   ** SQLite each time a query is executed to ensure that the internal cache
84679   ** of the schema used when compiling the SQL query matches the schema of
84680   ** the database against which the compiled query is actually executed.
84681   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
84682   ** the schema-version is potentially dangerous and may lead to program
84683   ** crashes or database corruption. Use with caution!
84684   **
84685   ** The user-version is not used internally by SQLite. It may be used by
84686   ** applications for any purpose.
84687   */
84688   if( sqlite3StrICmp(zLeft, "schema_version")==0 
84689    || sqlite3StrICmp(zLeft, "user_version")==0 
84690    || sqlite3StrICmp(zLeft, "freelist_count")==0 
84691   ){
84692     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
84693     sqlite3VdbeUsesBtree(v, iDb);
84694     switch( zLeft[0] ){
84695       case 'f': case 'F':
84696         iCookie = BTREE_FREE_PAGE_COUNT;
84697         break;
84698       case 's': case 'S':
84699         iCookie = BTREE_SCHEMA_VERSION;
84700         break;
84701       default:
84702         iCookie = BTREE_USER_VERSION;
84703         break;
84704     }
84705
84706     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
84707       /* Write the specified cookie value */
84708       static const VdbeOpList setCookie[] = {
84709         { OP_Transaction,    0,  1,  0},    /* 0 */
84710         { OP_Integer,        0,  1,  0},    /* 1 */
84711         { OP_SetCookie,      0,  0,  1},    /* 2 */
84712       };
84713       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
84714       sqlite3VdbeChangeP1(v, addr, iDb);
84715       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
84716       sqlite3VdbeChangeP1(v, addr+2, iDb);
84717       sqlite3VdbeChangeP2(v, addr+2, iCookie);
84718     }else{
84719       /* Read the specified cookie value */
84720       static const VdbeOpList readCookie[] = {
84721         { OP_Transaction,     0,  0,  0},    /* 0 */
84722         { OP_ReadCookie,      0,  1,  0},    /* 1 */
84723         { OP_ResultRow,       1,  1,  0}
84724       };
84725       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
84726       sqlite3VdbeChangeP1(v, addr, iDb);
84727       sqlite3VdbeChangeP1(v, addr+1, iDb);
84728       sqlite3VdbeChangeP3(v, addr+1, iCookie);
84729       sqlite3VdbeSetNumCols(v, 1);
84730       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
84731     }
84732   }else
84733 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
84734
84735 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
84736   /*
84737   **   PRAGMA compile_options
84738   **
84739   ** Return the names of all compile-time options used in this build,
84740   ** one option per row.
84741   */
84742   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
84743     int i = 0;
84744     const char *zOpt;
84745     sqlite3VdbeSetNumCols(v, 1);
84746     pParse->nMem = 1;
84747     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
84748     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
84749       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
84750       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84751     }
84752   }else
84753 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
84754
84755 #ifndef SQLITE_OMIT_WAL
84756   /*
84757   **   PRAGMA [database.]wal_checkpoint
84758   **
84759   ** Checkpoint the database.
84760   */
84761   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
84762     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84763     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
84764   }else
84765
84766   /*
84767   **   PRAGMA wal_autocheckpoint
84768   **   PRAGMA wal_autocheckpoint = N
84769   **
84770   ** Configure a database connection to automatically checkpoint a database
84771   ** after accumulating N frames in the log. Or query for the current value
84772   ** of N.
84773   */
84774   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
84775     if( zRight ){
84776       int nAuto = atoi(zRight);
84777       sqlite3_wal_autocheckpoint(db, nAuto);
84778     }
84779     returnSingleInt(pParse, "wal_autocheckpoint", 
84780        db->xWalCallback==sqlite3WalDefaultHook ? 
84781            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
84782   }else
84783 #endif
84784
84785 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
84786   /*
84787   ** Report the current state of file logs for all databases
84788   */
84789   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
84790     static const char *const azLockName[] = {
84791       "unlocked", "shared", "reserved", "pending", "exclusive"
84792     };
84793     int i;
84794     sqlite3VdbeSetNumCols(v, 2);
84795     pParse->nMem = 2;
84796     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
84797     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
84798     for(i=0; i<db->nDb; i++){
84799       Btree *pBt;
84800       Pager *pPager;
84801       const char *zState = "unknown";
84802       int j;
84803       if( db->aDb[i].zName==0 ) continue;
84804       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
84805       pBt = db->aDb[i].pBt;
84806       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
84807         zState = "closed";
84808       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
84809                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
84810          zState = azLockName[j];
84811       }
84812       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
84813       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
84814     }
84815
84816   }else
84817 #endif
84818
84819 #ifdef SQLITE_HAS_CODEC
84820   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
84821     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
84822   }else
84823   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
84824     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
84825   }else
84826   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
84827                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
84828     int i, h1, h2;
84829     char zKey[40];
84830     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
84831       h1 += 9*(1&(h1>>6));
84832       h2 += 9*(1&(h2>>6));
84833       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
84834     }
84835     if( (zLeft[3] & 0xf)==0xb ){
84836       sqlite3_key(db, zKey, i/2);
84837     }else{
84838       sqlite3_rekey(db, zKey, i/2);
84839     }
84840   }else
84841 #endif
84842 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
84843   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
84844 #ifdef SQLITE_HAS_CODEC
84845     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
84846       sqlite3_activate_see(&zRight[4]);
84847     }
84848 #endif
84849 #ifdef SQLITE_ENABLE_CEROD
84850     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
84851       sqlite3_activate_cerod(&zRight[6]);
84852     }
84853 #endif
84854   }else
84855 #endif
84856
84857  
84858   {/* Empty ELSE clause */}
84859
84860   /*
84861   ** Reset the safety level, in case the fullfsync flag or synchronous
84862   ** setting changed.
84863   */
84864 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84865   if( db->autoCommit ){
84866     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
84867                (db->flags&SQLITE_FullFSync)!=0);
84868   }
84869 #endif
84870 pragma_out:
84871   sqlite3DbFree(db, zLeft);
84872   sqlite3DbFree(db, zRight);
84873 }
84874
84875 #endif /* SQLITE_OMIT_PRAGMA */
84876
84877 /************** End of pragma.c **********************************************/
84878 /************** Begin file prepare.c *****************************************/
84879 /*
84880 ** 2005 May 25
84881 **
84882 ** The author disclaims copyright to this source code.  In place of
84883 ** a legal notice, here is a blessing:
84884 **
84885 **    May you do good and not evil.
84886 **    May you find forgiveness for yourself and forgive others.
84887 **    May you share freely, never taking more than you give.
84888 **
84889 *************************************************************************
84890 ** This file contains the implementation of the sqlite3_prepare()
84891 ** interface, and routines that contribute to loading the database schema
84892 ** from disk.
84893 */
84894
84895 /*
84896 ** Fill the InitData structure with an error message that indicates
84897 ** that the database is corrupt.
84898 */
84899 static void corruptSchema(
84900   InitData *pData,     /* Initialization context */
84901   const char *zObj,    /* Object being parsed at the point of error */
84902   const char *zExtra   /* Error information */
84903 ){
84904   sqlite3 *db = pData->db;
84905   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
84906     if( zObj==0 ) zObj = "?";
84907     sqlite3SetString(pData->pzErrMsg, db,
84908       "malformed database schema (%s)", zObj);
84909     if( zExtra ){
84910       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
84911                                  "%s - %s", *pData->pzErrMsg, zExtra);
84912     }
84913   }
84914   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
84915 }
84916
84917 /*
84918 ** This is the callback routine for the code that initializes the
84919 ** database.  See sqlite3Init() below for additional information.
84920 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
84921 **
84922 ** Each callback contains the following information:
84923 **
84924 **     argv[0] = name of thing being created
84925 **     argv[1] = root page number for table or index. 0 for trigger or view.
84926 **     argv[2] = SQL text for the CREATE statement.
84927 **
84928 */
84929 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
84930   InitData *pData = (InitData*)pInit;
84931   sqlite3 *db = pData->db;
84932   int iDb = pData->iDb;
84933
84934   assert( argc==3 );
84935   UNUSED_PARAMETER2(NotUsed, argc);
84936   assert( sqlite3_mutex_held(db->mutex) );
84937   DbClearProperty(db, iDb, DB_Empty);
84938   if( db->mallocFailed ){
84939     corruptSchema(pData, argv[0], 0);
84940     return 1;
84941   }
84942
84943   assert( iDb>=0 && iDb<db->nDb );
84944   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
84945   if( argv[1]==0 ){
84946     corruptSchema(pData, argv[0], 0);
84947   }else if( argv[2] && argv[2][0] ){
84948     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
84949     ** But because db->init.busy is set to 1, no VDBE code is generated
84950     ** or executed.  All the parser does is build the internal data
84951     ** structures that describe the table, index, or view.
84952     */
84953     int rc;
84954     sqlite3_stmt *pStmt;
84955     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
84956
84957     assert( db->init.busy );
84958     db->init.iDb = iDb;
84959     db->init.newTnum = atoi(argv[1]);
84960     db->init.orphanTrigger = 0;
84961     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
84962     rc = db->errCode;
84963     assert( (rc&0xFF)==(rcp&0xFF) );
84964     db->init.iDb = 0;
84965     if( SQLITE_OK!=rc ){
84966       if( db->init.orphanTrigger ){
84967         assert( iDb==1 );
84968       }else{
84969         pData->rc = rc;
84970         if( rc==SQLITE_NOMEM ){
84971           db->mallocFailed = 1;
84972         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
84973           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
84974         }
84975       }
84976     }
84977     sqlite3_finalize(pStmt);
84978   }else if( argv[0]==0 ){
84979     corruptSchema(pData, 0, 0);
84980   }else{
84981     /* If the SQL column is blank it means this is an index that
84982     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
84983     ** constraint for a CREATE TABLE.  The index should have already
84984     ** been created when we processed the CREATE TABLE.  All we have
84985     ** to do here is record the root page number for that index.
84986     */
84987     Index *pIndex;
84988     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
84989     if( pIndex==0 ){
84990       /* This can occur if there exists an index on a TEMP table which
84991       ** has the same name as another index on a permanent index.  Since
84992       ** the permanent table is hidden by the TEMP table, we can also
84993       ** safely ignore the index on the permanent table.
84994       */
84995       /* Do Nothing */;
84996     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
84997       corruptSchema(pData, argv[0], "invalid rootpage");
84998     }
84999   }
85000   return 0;
85001 }
85002
85003 /*
85004 ** Attempt to read the database schema and initialize internal
85005 ** data structures for a single database file.  The index of the
85006 ** database file is given by iDb.  iDb==0 is used for the main
85007 ** database.  iDb==1 should never be used.  iDb>=2 is used for
85008 ** auxiliary databases.  Return one of the SQLITE_ error codes to
85009 ** indicate success or failure.
85010 */
85011 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
85012   int rc;
85013   int i;
85014   int size;
85015   Table *pTab;
85016   Db *pDb;
85017   char const *azArg[4];
85018   int meta[5];
85019   InitData initData;
85020   char const *zMasterSchema;
85021   char const *zMasterName = SCHEMA_TABLE(iDb);
85022   int openedTransaction = 0;
85023
85024   /*
85025   ** The master database table has a structure like this
85026   */
85027   static const char master_schema[] = 
85028      "CREATE TABLE sqlite_master(\n"
85029      "  type text,\n"
85030      "  name text,\n"
85031      "  tbl_name text,\n"
85032      "  rootpage integer,\n"
85033      "  sql text\n"
85034      ")"
85035   ;
85036 #ifndef SQLITE_OMIT_TEMPDB
85037   static const char temp_master_schema[] = 
85038      "CREATE TEMP TABLE sqlite_temp_master(\n"
85039      "  type text,\n"
85040      "  name text,\n"
85041      "  tbl_name text,\n"
85042      "  rootpage integer,\n"
85043      "  sql text\n"
85044      ")"
85045   ;
85046 #else
85047   #define temp_master_schema 0
85048 #endif
85049
85050   assert( iDb>=0 && iDb<db->nDb );
85051   assert( db->aDb[iDb].pSchema );
85052   assert( sqlite3_mutex_held(db->mutex) );
85053   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
85054
85055   /* zMasterSchema and zInitScript are set to point at the master schema
85056   ** and initialisation script appropriate for the database being
85057   ** initialised. zMasterName is the name of the master table.
85058   */
85059   if( !OMIT_TEMPDB && iDb==1 ){
85060     zMasterSchema = temp_master_schema;
85061   }else{
85062     zMasterSchema = master_schema;
85063   }
85064   zMasterName = SCHEMA_TABLE(iDb);
85065
85066   /* Construct the schema tables.  */
85067   azArg[0] = zMasterName;
85068   azArg[1] = "1";
85069   azArg[2] = zMasterSchema;
85070   azArg[3] = 0;
85071   initData.db = db;
85072   initData.iDb = iDb;
85073   initData.rc = SQLITE_OK;
85074   initData.pzErrMsg = pzErrMsg;
85075   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
85076   if( initData.rc ){
85077     rc = initData.rc;
85078     goto error_out;
85079   }
85080   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
85081   if( ALWAYS(pTab) ){
85082     pTab->tabFlags |= TF_Readonly;
85083   }
85084
85085   /* Create a cursor to hold the database open
85086   */
85087   pDb = &db->aDb[iDb];
85088   if( pDb->pBt==0 ){
85089     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
85090       DbSetProperty(db, 1, DB_SchemaLoaded);
85091     }
85092     return SQLITE_OK;
85093   }
85094
85095   /* If there is not already a read-only (or read-write) transaction opened
85096   ** on the b-tree database, open one now. If a transaction is opened, it 
85097   ** will be closed before this function returns.  */
85098   sqlite3BtreeEnter(pDb->pBt);
85099   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
85100     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
85101     if( rc!=SQLITE_OK ){
85102       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
85103       goto initone_error_out;
85104     }
85105     openedTransaction = 1;
85106   }
85107
85108   /* Get the database meta information.
85109   **
85110   ** Meta values are as follows:
85111   **    meta[0]   Schema cookie.  Changes with each schema change.
85112   **    meta[1]   File format of schema layer.
85113   **    meta[2]   Size of the page cache.
85114   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
85115   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
85116   **    meta[5]   User version
85117   **    meta[6]   Incremental vacuum mode
85118   **    meta[7]   unused
85119   **    meta[8]   unused
85120   **    meta[9]   unused
85121   **
85122   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
85123   ** the possible values of meta[4].
85124   */
85125   for(i=0; i<ArraySize(meta); i++){
85126     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
85127   }
85128   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
85129
85130   /* If opening a non-empty database, check the text encoding. For the
85131   ** main database, set sqlite3.enc to the encoding of the main database.
85132   ** For an attached db, it is an error if the encoding is not the same
85133   ** as sqlite3.enc.
85134   */
85135   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
85136     if( iDb==0 ){
85137       u8 encoding;
85138       /* If opening the main database, set ENC(db). */
85139       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
85140       if( encoding==0 ) encoding = SQLITE_UTF8;
85141       ENC(db) = encoding;
85142       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
85143     }else{
85144       /* If opening an attached database, the encoding much match ENC(db) */
85145       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
85146         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
85147             " text encoding as main database");
85148         rc = SQLITE_ERROR;
85149         goto initone_error_out;
85150       }
85151     }
85152   }else{
85153     DbSetProperty(db, iDb, DB_Empty);
85154   }
85155   pDb->pSchema->enc = ENC(db);
85156
85157   if( pDb->pSchema->cache_size==0 ){
85158     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
85159     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
85160     if( size<0 ) size = -size;
85161     pDb->pSchema->cache_size = size;
85162     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
85163   }
85164
85165   /*
85166   ** file_format==1    Version 3.0.0.
85167   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
85168   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
85169   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
85170   */
85171   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
85172   if( pDb->pSchema->file_format==0 ){
85173     pDb->pSchema->file_format = 1;
85174   }
85175   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
85176     sqlite3SetString(pzErrMsg, db, "unsupported file format");
85177     rc = SQLITE_ERROR;
85178     goto initone_error_out;
85179   }
85180
85181   /* Ticket #2804:  When we open a database in the newer file format,
85182   ** clear the legacy_file_format pragma flag so that a VACUUM will
85183   ** not downgrade the database and thus invalidate any descending
85184   ** indices that the user might have created.
85185   */
85186   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
85187     db->flags &= ~SQLITE_LegacyFileFmt;
85188   }
85189
85190   /* Read the schema information out of the schema tables
85191   */
85192   assert( db->init.busy );
85193   {
85194     char *zSql;
85195     zSql = sqlite3MPrintf(db, 
85196         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
85197         db->aDb[iDb].zName, zMasterName);
85198 #ifndef SQLITE_OMIT_AUTHORIZATION
85199     {
85200       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
85201       xAuth = db->xAuth;
85202       db->xAuth = 0;
85203 #endif
85204       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
85205 #ifndef SQLITE_OMIT_AUTHORIZATION
85206       db->xAuth = xAuth;
85207     }
85208 #endif
85209     if( rc==SQLITE_OK ) rc = initData.rc;
85210     sqlite3DbFree(db, zSql);
85211 #ifndef SQLITE_OMIT_ANALYZE
85212     if( rc==SQLITE_OK ){
85213       sqlite3AnalysisLoad(db, iDb);
85214     }
85215 #endif
85216   }
85217   if( db->mallocFailed ){
85218     rc = SQLITE_NOMEM;
85219     sqlite3ResetInternalSchema(db, 0);
85220   }
85221   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
85222     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
85223     ** the schema loaded, even if errors occurred. In this situation the 
85224     ** current sqlite3_prepare() operation will fail, but the following one
85225     ** will attempt to compile the supplied statement against whatever subset
85226     ** of the schema was loaded before the error occurred. The primary
85227     ** purpose of this is to allow access to the sqlite_master table
85228     ** even when its contents have been corrupted.
85229     */
85230     DbSetProperty(db, iDb, DB_SchemaLoaded);
85231     rc = SQLITE_OK;
85232   }
85233
85234   /* Jump here for an error that occurs after successfully allocating
85235   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
85236   ** before that point, jump to error_out.
85237   */
85238 initone_error_out:
85239   if( openedTransaction ){
85240     sqlite3BtreeCommit(pDb->pBt);
85241   }
85242   sqlite3BtreeLeave(pDb->pBt);
85243
85244 error_out:
85245   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
85246     db->mallocFailed = 1;
85247   }
85248   return rc;
85249 }
85250
85251 /*
85252 ** Initialize all database files - the main database file, the file
85253 ** used to store temporary tables, and any additional database files
85254 ** created using ATTACH statements.  Return a success code.  If an
85255 ** error occurs, write an error message into *pzErrMsg.
85256 **
85257 ** After a database is initialized, the DB_SchemaLoaded bit is set
85258 ** bit is set in the flags field of the Db structure. If the database
85259 ** file was of zero-length, then the DB_Empty flag is also set.
85260 */
85261 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
85262   int i, rc;
85263   int commit_internal = !(db->flags&SQLITE_InternChanges);
85264   
85265   assert( sqlite3_mutex_held(db->mutex) );
85266   rc = SQLITE_OK;
85267   db->init.busy = 1;
85268   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85269     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
85270     rc = sqlite3InitOne(db, i, pzErrMsg);
85271     if( rc ){
85272       sqlite3ResetInternalSchema(db, i);
85273     }
85274   }
85275
85276   /* Once all the other databases have been initialised, load the schema
85277   ** for the TEMP database. This is loaded last, as the TEMP database
85278   ** schema may contain references to objects in other databases.
85279   */
85280 #ifndef SQLITE_OMIT_TEMPDB
85281   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
85282                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
85283     rc = sqlite3InitOne(db, 1, pzErrMsg);
85284     if( rc ){
85285       sqlite3ResetInternalSchema(db, 1);
85286     }
85287   }
85288 #endif
85289
85290   db->init.busy = 0;
85291   if( rc==SQLITE_OK && commit_internal ){
85292     sqlite3CommitInternalChanges(db);
85293   }
85294
85295   return rc; 
85296 }
85297
85298 /*
85299 ** This routine is a no-op if the database schema is already initialised.
85300 ** Otherwise, the schema is loaded. An error code is returned.
85301 */
85302 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
85303   int rc = SQLITE_OK;
85304   sqlite3 *db = pParse->db;
85305   assert( sqlite3_mutex_held(db->mutex) );
85306   if( !db->init.busy ){
85307     rc = sqlite3Init(db, &pParse->zErrMsg);
85308   }
85309   if( rc!=SQLITE_OK ){
85310     pParse->rc = rc;
85311     pParse->nErr++;
85312   }
85313   return rc;
85314 }
85315
85316
85317 /*
85318 ** Check schema cookies in all databases.  If any cookie is out
85319 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
85320 ** make no changes to pParse->rc.
85321 */
85322 static void schemaIsValid(Parse *pParse){
85323   sqlite3 *db = pParse->db;
85324   int iDb;
85325   int rc;
85326   int cookie;
85327
85328   assert( pParse->checkSchema );
85329   assert( sqlite3_mutex_held(db->mutex) );
85330   for(iDb=0; iDb<db->nDb; iDb++){
85331     int openedTransaction = 0;         /* True if a transaction is opened */
85332     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
85333     if( pBt==0 ) continue;
85334
85335     /* If there is not already a read-only (or read-write) transaction opened
85336     ** on the b-tree database, open one now. If a transaction is opened, it 
85337     ** will be closed immediately after reading the meta-value. */
85338     if( !sqlite3BtreeIsInReadTrans(pBt) ){
85339       rc = sqlite3BtreeBeginTrans(pBt, 0);
85340       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
85341         db->mallocFailed = 1;
85342       }
85343       if( rc!=SQLITE_OK ) return;
85344       openedTransaction = 1;
85345     }
85346
85347     /* Read the schema cookie from the database. If it does not match the 
85348     ** value stored as part of the in-memory schema representation,
85349     ** set Parse.rc to SQLITE_SCHEMA. */
85350     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
85351     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
85352       pParse->rc = SQLITE_SCHEMA;
85353     }
85354
85355     /* Close the transaction, if one was opened. */
85356     if( openedTransaction ){
85357       sqlite3BtreeCommit(pBt);
85358     }
85359   }
85360 }
85361
85362 /*
85363 ** Convert a schema pointer into the iDb index that indicates
85364 ** which database file in db->aDb[] the schema refers to.
85365 **
85366 ** If the same database is attached more than once, the first
85367 ** attached database is returned.
85368 */
85369 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
85370   int i = -1000000;
85371
85372   /* If pSchema is NULL, then return -1000000. This happens when code in 
85373   ** expr.c is trying to resolve a reference to a transient table (i.e. one
85374   ** created by a sub-select). In this case the return value of this 
85375   ** function should never be used.
85376   **
85377   ** We return -1000000 instead of the more usual -1 simply because using
85378   ** -1000000 as the incorrect index into db->aDb[] is much 
85379   ** more likely to cause a segfault than -1 (of course there are assert()
85380   ** statements too, but it never hurts to play the odds).
85381   */
85382   assert( sqlite3_mutex_held(db->mutex) );
85383   if( pSchema ){
85384     for(i=0; ALWAYS(i<db->nDb); i++){
85385       if( db->aDb[i].pSchema==pSchema ){
85386         break;
85387       }
85388     }
85389     assert( i>=0 && i<db->nDb );
85390   }
85391   return i;
85392 }
85393
85394 /*
85395 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
85396 */
85397 static int sqlite3Prepare(
85398   sqlite3 *db,              /* Database handle. */
85399   const char *zSql,         /* UTF-8 encoded SQL statement. */
85400   int nBytes,               /* Length of zSql in bytes. */
85401   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85402   Vdbe *pReprepare,         /* VM being reprepared */
85403   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85404   const char **pzTail       /* OUT: End of parsed string */
85405 ){
85406   Parse *pParse;            /* Parsing context */
85407   char *zErrMsg = 0;        /* Error message */
85408   int rc = SQLITE_OK;       /* Result code */
85409   int i;                    /* Loop counter */
85410
85411   /* Allocate the parsing context */
85412   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
85413   if( pParse==0 ){
85414     rc = SQLITE_NOMEM;
85415     goto end_prepare;
85416   }
85417   pParse->pReprepare = pReprepare;
85418   assert( ppStmt && *ppStmt==0 );
85419   assert( !db->mallocFailed );
85420   assert( sqlite3_mutex_held(db->mutex) );
85421
85422   /* Check to verify that it is possible to get a read lock on all
85423   ** database schemas.  The inability to get a read lock indicates that
85424   ** some other database connection is holding a write-lock, which in
85425   ** turn means that the other connection has made uncommitted changes
85426   ** to the schema.
85427   **
85428   ** Were we to proceed and prepare the statement against the uncommitted
85429   ** schema changes and if those schema changes are subsequently rolled
85430   ** back and different changes are made in their place, then when this
85431   ** prepared statement goes to run the schema cookie would fail to detect
85432   ** the schema change.  Disaster would follow.
85433   **
85434   ** This thread is currently holding mutexes on all Btrees (because
85435   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
85436   ** is not possible for another thread to start a new schema change
85437   ** while this routine is running.  Hence, we do not need to hold 
85438   ** locks on the schema, we just need to make sure nobody else is 
85439   ** holding them.
85440   **
85441   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
85442   ** but it does *not* override schema lock detection, so this all still
85443   ** works even if READ_UNCOMMITTED is set.
85444   */
85445   for(i=0; i<db->nDb; i++) {
85446     Btree *pBt = db->aDb[i].pBt;
85447     if( pBt ){
85448       assert( sqlite3BtreeHoldsMutex(pBt) );
85449       rc = sqlite3BtreeSchemaLocked(pBt);
85450       if( rc ){
85451         const char *zDb = db->aDb[i].zName;
85452         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
85453         testcase( db->flags & SQLITE_ReadUncommitted );
85454         goto end_prepare;
85455       }
85456     }
85457   }
85458
85459   sqlite3VtabUnlockList(db);
85460
85461   pParse->db = db;
85462   pParse->nQueryLoop = (double)1;
85463   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
85464     char *zSqlCopy;
85465     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
85466     testcase( nBytes==mxLen );
85467     testcase( nBytes==mxLen+1 );
85468     if( nBytes>mxLen ){
85469       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
85470       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
85471       goto end_prepare;
85472     }
85473     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
85474     if( zSqlCopy ){
85475       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
85476       sqlite3DbFree(db, zSqlCopy);
85477       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
85478     }else{
85479       pParse->zTail = &zSql[nBytes];
85480     }
85481   }else{
85482     sqlite3RunParser(pParse, zSql, &zErrMsg);
85483   }
85484   assert( 1==(int)pParse->nQueryLoop );
85485
85486   if( db->mallocFailed ){
85487     pParse->rc = SQLITE_NOMEM;
85488   }
85489   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
85490   if( pParse->checkSchema ){
85491     schemaIsValid(pParse);
85492   }
85493   if( pParse->rc==SQLITE_SCHEMA ){
85494     sqlite3ResetInternalSchema(db, 0);
85495   }
85496   if( db->mallocFailed ){
85497     pParse->rc = SQLITE_NOMEM;
85498   }
85499   if( pzTail ){
85500     *pzTail = pParse->zTail;
85501   }
85502   rc = pParse->rc;
85503
85504 #ifndef SQLITE_OMIT_EXPLAIN
85505   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
85506     static const char * const azColName[] = {
85507        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
85508        "order", "from", "detail"
85509     };
85510     int iFirst, mx;
85511     if( pParse->explain==2 ){
85512       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
85513       iFirst = 8;
85514       mx = 11;
85515     }else{
85516       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
85517       iFirst = 0;
85518       mx = 8;
85519     }
85520     for(i=iFirst; i<mx; i++){
85521       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
85522                             azColName[i], SQLITE_STATIC);
85523     }
85524   }
85525 #endif
85526
85527   assert( db->init.busy==0 || saveSqlFlag==0 );
85528   if( db->init.busy==0 ){
85529     Vdbe *pVdbe = pParse->pVdbe;
85530     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
85531   }
85532   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
85533     sqlite3VdbeFinalize(pParse->pVdbe);
85534     assert(!(*ppStmt));
85535   }else{
85536     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
85537   }
85538
85539   if( zErrMsg ){
85540     sqlite3Error(db, rc, "%s", zErrMsg);
85541     sqlite3DbFree(db, zErrMsg);
85542   }else{
85543     sqlite3Error(db, rc, 0);
85544   }
85545
85546   /* Delete any TriggerPrg structures allocated while parsing this statement. */
85547   while( pParse->pTriggerPrg ){
85548     TriggerPrg *pT = pParse->pTriggerPrg;
85549     pParse->pTriggerPrg = pT->pNext;
85550     sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
85551     sqlite3DbFree(db, pT);
85552   }
85553
85554 end_prepare:
85555
85556   sqlite3StackFree(db, pParse);
85557   rc = sqlite3ApiExit(db, rc);
85558   assert( (rc&db->errMask)==rc );
85559   return rc;
85560 }
85561 static int sqlite3LockAndPrepare(
85562   sqlite3 *db,              /* Database handle. */
85563   const char *zSql,         /* UTF-8 encoded SQL statement. */
85564   int nBytes,               /* Length of zSql in bytes. */
85565   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85566   Vdbe *pOld,               /* VM being reprepared */
85567   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85568   const char **pzTail       /* OUT: End of parsed string */
85569 ){
85570   int rc;
85571   assert( ppStmt!=0 );
85572   *ppStmt = 0;
85573   if( !sqlite3SafetyCheckOk(db) ){
85574     return SQLITE_MISUSE_BKPT;
85575   }
85576   sqlite3_mutex_enter(db->mutex);
85577   sqlite3BtreeEnterAll(db);
85578   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85579   if( rc==SQLITE_SCHEMA ){
85580     sqlite3_finalize(*ppStmt);
85581     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85582   }
85583   sqlite3BtreeLeaveAll(db);
85584   sqlite3_mutex_leave(db->mutex);
85585   return rc;
85586 }
85587
85588 /*
85589 ** Rerun the compilation of a statement after a schema change.
85590 **
85591 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
85592 ** if the statement cannot be recompiled because another connection has
85593 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
85594 ** occurs, return SQLITE_SCHEMA.
85595 */
85596 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
85597   int rc;
85598   sqlite3_stmt *pNew;
85599   const char *zSql;
85600   sqlite3 *db;
85601
85602   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
85603   zSql = sqlite3_sql((sqlite3_stmt *)p);
85604   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
85605   db = sqlite3VdbeDb(p);
85606   assert( sqlite3_mutex_held(db->mutex) );
85607   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
85608   if( rc ){
85609     if( rc==SQLITE_NOMEM ){
85610       db->mallocFailed = 1;
85611     }
85612     assert( pNew==0 );
85613     return rc;
85614   }else{
85615     assert( pNew!=0 );
85616   }
85617   sqlite3VdbeSwap((Vdbe*)pNew, p);
85618   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
85619   sqlite3VdbeResetStepResult((Vdbe*)pNew);
85620   sqlite3VdbeFinalize((Vdbe*)pNew);
85621   return SQLITE_OK;
85622 }
85623
85624
85625 /*
85626 ** Two versions of the official API.  Legacy and new use.  In the legacy
85627 ** version, the original SQL text is not saved in the prepared statement
85628 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85629 ** sqlite3_step().  In the new version, the original SQL text is retained
85630 ** and the statement is automatically recompiled if an schema change
85631 ** occurs.
85632 */
85633 SQLITE_API int sqlite3_prepare(
85634   sqlite3 *db,              /* Database handle. */
85635   const char *zSql,         /* UTF-8 encoded SQL statement. */
85636   int nBytes,               /* Length of zSql in bytes. */
85637   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85638   const char **pzTail       /* OUT: End of parsed string */
85639 ){
85640   int rc;
85641   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
85642   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85643   return rc;
85644 }
85645 SQLITE_API int sqlite3_prepare_v2(
85646   sqlite3 *db,              /* Database handle. */
85647   const char *zSql,         /* UTF-8 encoded SQL statement. */
85648   int nBytes,               /* Length of zSql in bytes. */
85649   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85650   const char **pzTail       /* OUT: End of parsed string */
85651 ){
85652   int rc;
85653   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
85654   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85655   return rc;
85656 }
85657
85658
85659 #ifndef SQLITE_OMIT_UTF16
85660 /*
85661 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
85662 */
85663 static int sqlite3Prepare16(
85664   sqlite3 *db,              /* Database handle. */ 
85665   const void *zSql,         /* UTF-8 encoded SQL statement. */
85666   int nBytes,               /* Length of zSql in bytes. */
85667   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
85668   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85669   const void **pzTail       /* OUT: End of parsed string */
85670 ){
85671   /* This function currently works by first transforming the UTF-16
85672   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
85673   ** tricky bit is figuring out the pointer to return in *pzTail.
85674   */
85675   char *zSql8;
85676   const char *zTail8 = 0;
85677   int rc = SQLITE_OK;
85678
85679   assert( ppStmt );
85680   *ppStmt = 0;
85681   if( !sqlite3SafetyCheckOk(db) ){
85682     return SQLITE_MISUSE_BKPT;
85683   }
85684   sqlite3_mutex_enter(db->mutex);
85685   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
85686   if( zSql8 ){
85687     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
85688   }
85689
85690   if( zTail8 && pzTail ){
85691     /* If sqlite3_prepare returns a tail pointer, we calculate the
85692     ** equivalent pointer into the UTF-16 string by counting the unicode
85693     ** characters between zSql8 and zTail8, and then returning a pointer
85694     ** the same number of characters into the UTF-16 string.
85695     */
85696     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
85697     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
85698   }
85699   sqlite3DbFree(db, zSql8); 
85700   rc = sqlite3ApiExit(db, rc);
85701   sqlite3_mutex_leave(db->mutex);
85702   return rc;
85703 }
85704
85705 /*
85706 ** Two versions of the official API.  Legacy and new use.  In the legacy
85707 ** version, the original SQL text is not saved in the prepared statement
85708 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85709 ** sqlite3_step().  In the new version, the original SQL text is retained
85710 ** and the statement is automatically recompiled if an schema change
85711 ** occurs.
85712 */
85713 SQLITE_API int sqlite3_prepare16(
85714   sqlite3 *db,              /* Database handle. */ 
85715   const void *zSql,         /* UTF-8 encoded SQL statement. */
85716   int nBytes,               /* Length of zSql in bytes. */
85717   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85718   const void **pzTail       /* OUT: End of parsed string */
85719 ){
85720   int rc;
85721   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
85722   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85723   return rc;
85724 }
85725 SQLITE_API int sqlite3_prepare16_v2(
85726   sqlite3 *db,              /* Database handle. */ 
85727   const void *zSql,         /* UTF-8 encoded SQL statement. */
85728   int nBytes,               /* Length of zSql in bytes. */
85729   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85730   const void **pzTail       /* OUT: End of parsed string */
85731 ){
85732   int rc;
85733   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
85734   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85735   return rc;
85736 }
85737
85738 #endif /* SQLITE_OMIT_UTF16 */
85739
85740 /************** End of prepare.c *********************************************/
85741 /************** Begin file select.c ******************************************/
85742 /*
85743 ** 2001 September 15
85744 **
85745 ** The author disclaims copyright to this source code.  In place of
85746 ** a legal notice, here is a blessing:
85747 **
85748 **    May you do good and not evil.
85749 **    May you find forgiveness for yourself and forgive others.
85750 **    May you share freely, never taking more than you give.
85751 **
85752 *************************************************************************
85753 ** This file contains C code routines that are called by the parser
85754 ** to handle SELECT statements in SQLite.
85755 */
85756
85757
85758 /*
85759 ** Delete all the content of a Select structure but do not deallocate
85760 ** the select structure itself.
85761 */
85762 static void clearSelect(sqlite3 *db, Select *p){
85763   sqlite3ExprListDelete(db, p->pEList);
85764   sqlite3SrcListDelete(db, p->pSrc);
85765   sqlite3ExprDelete(db, p->pWhere);
85766   sqlite3ExprListDelete(db, p->pGroupBy);
85767   sqlite3ExprDelete(db, p->pHaving);
85768   sqlite3ExprListDelete(db, p->pOrderBy);
85769   sqlite3SelectDelete(db, p->pPrior);
85770   sqlite3ExprDelete(db, p->pLimit);
85771   sqlite3ExprDelete(db, p->pOffset);
85772 }
85773
85774 /*
85775 ** Initialize a SelectDest structure.
85776 */
85777 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
85778   pDest->eDest = (u8)eDest;
85779   pDest->iParm = iParm;
85780   pDest->affinity = 0;
85781   pDest->iMem = 0;
85782   pDest->nMem = 0;
85783 }
85784
85785
85786 /*
85787 ** Allocate a new Select structure and return a pointer to that
85788 ** structure.
85789 */
85790 SQLITE_PRIVATE Select *sqlite3SelectNew(
85791   Parse *pParse,        /* Parsing context */
85792   ExprList *pEList,     /* which columns to include in the result */
85793   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
85794   Expr *pWhere,         /* the WHERE clause */
85795   ExprList *pGroupBy,   /* the GROUP BY clause */
85796   Expr *pHaving,        /* the HAVING clause */
85797   ExprList *pOrderBy,   /* the ORDER BY clause */
85798   int isDistinct,       /* true if the DISTINCT keyword is present */
85799   Expr *pLimit,         /* LIMIT value.  NULL means not used */
85800   Expr *pOffset         /* OFFSET value.  NULL means no offset */
85801 ){
85802   Select *pNew;
85803   Select standin;
85804   sqlite3 *db = pParse->db;
85805   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
85806   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
85807   if( pNew==0 ){
85808     pNew = &standin;
85809     memset(pNew, 0, sizeof(*pNew));
85810   }
85811   if( pEList==0 ){
85812     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
85813   }
85814   pNew->pEList = pEList;
85815   pNew->pSrc = pSrc;
85816   pNew->pWhere = pWhere;
85817   pNew->pGroupBy = pGroupBy;
85818   pNew->pHaving = pHaving;
85819   pNew->pOrderBy = pOrderBy;
85820   pNew->selFlags = isDistinct ? SF_Distinct : 0;
85821   pNew->op = TK_SELECT;
85822   pNew->pLimit = pLimit;
85823   pNew->pOffset = pOffset;
85824   assert( pOffset==0 || pLimit!=0 );
85825   pNew->addrOpenEphm[0] = -1;
85826   pNew->addrOpenEphm[1] = -1;
85827   pNew->addrOpenEphm[2] = -1;
85828   if( db->mallocFailed ) {
85829     clearSelect(db, pNew);
85830     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
85831     pNew = 0;
85832   }
85833   return pNew;
85834 }
85835
85836 /*
85837 ** Delete the given Select structure and all of its substructures.
85838 */
85839 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
85840   if( p ){
85841     clearSelect(db, p);
85842     sqlite3DbFree(db, p);
85843   }
85844 }
85845
85846 /*
85847 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
85848 ** type of join.  Return an integer constant that expresses that type
85849 ** in terms of the following bit values:
85850 **
85851 **     JT_INNER
85852 **     JT_CROSS
85853 **     JT_OUTER
85854 **     JT_NATURAL
85855 **     JT_LEFT
85856 **     JT_RIGHT
85857 **
85858 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
85859 **
85860 ** If an illegal or unsupported join type is seen, then still return
85861 ** a join type, but put an error in the pParse structure.
85862 */
85863 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
85864   int jointype = 0;
85865   Token *apAll[3];
85866   Token *p;
85867                              /*   0123456789 123456789 123456789 123 */
85868   static const char zKeyText[] = "naturaleftouterightfullinnercross";
85869   static const struct {
85870     u8 i;        /* Beginning of keyword text in zKeyText[] */
85871     u8 nChar;    /* Length of the keyword in characters */
85872     u8 code;     /* Join type mask */
85873   } aKeyword[] = {
85874     /* natural */ { 0,  7, JT_NATURAL                },
85875     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
85876     /* outer   */ { 10, 5, JT_OUTER                  },
85877     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
85878     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
85879     /* inner   */ { 23, 5, JT_INNER                  },
85880     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
85881   };
85882   int i, j;
85883   apAll[0] = pA;
85884   apAll[1] = pB;
85885   apAll[2] = pC;
85886   for(i=0; i<3 && apAll[i]; i++){
85887     p = apAll[i];
85888     for(j=0; j<ArraySize(aKeyword); j++){
85889       if( p->n==aKeyword[j].nChar 
85890           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
85891         jointype |= aKeyword[j].code;
85892         break;
85893       }
85894     }
85895     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
85896     if( j>=ArraySize(aKeyword) ){
85897       jointype |= JT_ERROR;
85898       break;
85899     }
85900   }
85901   if(
85902      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
85903      (jointype & JT_ERROR)!=0
85904   ){
85905     const char *zSp = " ";
85906     assert( pB!=0 );
85907     if( pC==0 ){ zSp++; }
85908     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
85909        "%T %T%s%T", pA, pB, zSp, pC);
85910     jointype = JT_INNER;
85911   }else if( (jointype & JT_OUTER)!=0 
85912          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
85913     sqlite3ErrorMsg(pParse, 
85914       "RIGHT and FULL OUTER JOINs are not currently supported");
85915     jointype = JT_INNER;
85916   }
85917   return jointype;
85918 }
85919
85920 /*
85921 ** Return the index of a column in a table.  Return -1 if the column
85922 ** is not contained in the table.
85923 */
85924 static int columnIndex(Table *pTab, const char *zCol){
85925   int i;
85926   for(i=0; i<pTab->nCol; i++){
85927     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
85928   }
85929   return -1;
85930 }
85931
85932 /*
85933 ** Search the first N tables in pSrc, from left to right, looking for a
85934 ** table that has a column named zCol.  
85935 **
85936 ** When found, set *piTab and *piCol to the table index and column index
85937 ** of the matching column and return TRUE.
85938 **
85939 ** If not found, return FALSE.
85940 */
85941 static int tableAndColumnIndex(
85942   SrcList *pSrc,       /* Array of tables to search */
85943   int N,               /* Number of tables in pSrc->a[] to search */
85944   const char *zCol,    /* Name of the column we are looking for */
85945   int *piTab,          /* Write index of pSrc->a[] here */
85946   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
85947 ){
85948   int i;               /* For looping over tables in pSrc */
85949   int iCol;            /* Index of column matching zCol */
85950
85951   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
85952   for(i=0; i<N; i++){
85953     iCol = columnIndex(pSrc->a[i].pTab, zCol);
85954     if( iCol>=0 ){
85955       if( piTab ){
85956         *piTab = i;
85957         *piCol = iCol;
85958       }
85959       return 1;
85960     }
85961   }
85962   return 0;
85963 }
85964
85965 /*
85966 ** This function is used to add terms implied by JOIN syntax to the
85967 ** WHERE clause expression of a SELECT statement. The new term, which
85968 ** is ANDed with the existing WHERE clause, is of the form:
85969 **
85970 **    (tab1.col1 = tab2.col2)
85971 **
85972 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
85973 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
85974 ** column iColRight of tab2.
85975 */
85976 static void addWhereTerm(
85977   Parse *pParse,                  /* Parsing context */
85978   SrcList *pSrc,                  /* List of tables in FROM clause */
85979   int iLeft,                      /* Index of first table to join in pSrc */
85980   int iColLeft,                   /* Index of column in first table */
85981   int iRight,                     /* Index of second table in pSrc */
85982   int iColRight,                  /* Index of column in second table */
85983   int isOuterJoin,                /* True if this is an OUTER join */
85984   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
85985 ){
85986   sqlite3 *db = pParse->db;
85987   Expr *pE1;
85988   Expr *pE2;
85989   Expr *pEq;
85990
85991   assert( iLeft<iRight );
85992   assert( pSrc->nSrc>iRight );
85993   assert( pSrc->a[iLeft].pTab );
85994   assert( pSrc->a[iRight].pTab );
85995
85996   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
85997   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
85998
85999   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
86000   if( pEq && isOuterJoin ){
86001     ExprSetProperty(pEq, EP_FromJoin);
86002     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
86003     ExprSetIrreducible(pEq);
86004     pEq->iRightJoinTable = (i16)pE2->iTable;
86005   }
86006   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
86007 }
86008
86009 /*
86010 ** Set the EP_FromJoin property on all terms of the given expression.
86011 ** And set the Expr.iRightJoinTable to iTable for every term in the
86012 ** expression.
86013 **
86014 ** The EP_FromJoin property is used on terms of an expression to tell
86015 ** the LEFT OUTER JOIN processing logic that this term is part of the
86016 ** join restriction specified in the ON or USING clause and not a part
86017 ** of the more general WHERE clause.  These terms are moved over to the
86018 ** WHERE clause during join processing but we need to remember that they
86019 ** originated in the ON or USING clause.
86020 **
86021 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
86022 ** expression depends on table iRightJoinTable even if that table is not
86023 ** explicitly mentioned in the expression.  That information is needed
86024 ** for cases like this:
86025 **
86026 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
86027 **
86028 ** The where clause needs to defer the handling of the t1.x=5
86029 ** term until after the t2 loop of the join.  In that way, a
86030 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
86031 ** defer the handling of t1.x=5, it will be processed immediately
86032 ** after the t1 loop and rows with t1.x!=5 will never appear in
86033 ** the output, which is incorrect.
86034 */
86035 static void setJoinExpr(Expr *p, int iTable){
86036   while( p ){
86037     ExprSetProperty(p, EP_FromJoin);
86038     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
86039     ExprSetIrreducible(p);
86040     p->iRightJoinTable = (i16)iTable;
86041     setJoinExpr(p->pLeft, iTable);
86042     p = p->pRight;
86043   } 
86044 }
86045
86046 /*
86047 ** This routine processes the join information for a SELECT statement.
86048 ** ON and USING clauses are converted into extra terms of the WHERE clause.
86049 ** NATURAL joins also create extra WHERE clause terms.
86050 **
86051 ** The terms of a FROM clause are contained in the Select.pSrc structure.
86052 ** The left most table is the first entry in Select.pSrc.  The right-most
86053 ** table is the last entry.  The join operator is held in the entry to
86054 ** the left.  Thus entry 0 contains the join operator for the join between
86055 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
86056 ** also attached to the left entry.
86057 **
86058 ** This routine returns the number of errors encountered.
86059 */
86060 static int sqliteProcessJoin(Parse *pParse, Select *p){
86061   SrcList *pSrc;                  /* All tables in the FROM clause */
86062   int i, j;                       /* Loop counters */
86063   struct SrcList_item *pLeft;     /* Left table being joined */
86064   struct SrcList_item *pRight;    /* Right table being joined */
86065
86066   pSrc = p->pSrc;
86067   pLeft = &pSrc->a[0];
86068   pRight = &pLeft[1];
86069   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
86070     Table *pLeftTab = pLeft->pTab;
86071     Table *pRightTab = pRight->pTab;
86072     int isOuter;
86073
86074     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
86075     isOuter = (pRight->jointype & JT_OUTER)!=0;
86076
86077     /* When the NATURAL keyword is present, add WHERE clause terms for
86078     ** every column that the two tables have in common.
86079     */
86080     if( pRight->jointype & JT_NATURAL ){
86081       if( pRight->pOn || pRight->pUsing ){
86082         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
86083            "an ON or USING clause", 0);
86084         return 1;
86085       }
86086       for(j=0; j<pRightTab->nCol; j++){
86087         char *zName;   /* Name of column in the right table */
86088         int iLeft;     /* Matching left table */
86089         int iLeftCol;  /* Matching column in the left table */
86090
86091         zName = pRightTab->aCol[j].zName;
86092         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
86093           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
86094                        isOuter, &p->pWhere);
86095         }
86096       }
86097     }
86098
86099     /* Disallow both ON and USING clauses in the same join
86100     */
86101     if( pRight->pOn && pRight->pUsing ){
86102       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
86103         "clauses in the same join");
86104       return 1;
86105     }
86106
86107     /* Add the ON clause to the end of the WHERE clause, connected by
86108     ** an AND operator.
86109     */
86110     if( pRight->pOn ){
86111       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
86112       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
86113       pRight->pOn = 0;
86114     }
86115
86116     /* Create extra terms on the WHERE clause for each column named
86117     ** in the USING clause.  Example: If the two tables to be joined are 
86118     ** A and B and the USING clause names X, Y, and Z, then add this
86119     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
86120     ** Report an error if any column mentioned in the USING clause is
86121     ** not contained in both tables to be joined.
86122     */
86123     if( pRight->pUsing ){
86124       IdList *pList = pRight->pUsing;
86125       for(j=0; j<pList->nId; j++){
86126         char *zName;     /* Name of the term in the USING clause */
86127         int iLeft;       /* Table on the left with matching column name */
86128         int iLeftCol;    /* Column number of matching column on the left */
86129         int iRightCol;   /* Column number of matching column on the right */
86130
86131         zName = pList->a[j].zName;
86132         iRightCol = columnIndex(pRightTab, zName);
86133         if( iRightCol<0
86134          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
86135         ){
86136           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
86137             "not present in both tables", zName);
86138           return 1;
86139         }
86140         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
86141                      isOuter, &p->pWhere);
86142       }
86143     }
86144   }
86145   return 0;
86146 }
86147
86148 /*
86149 ** Insert code into "v" that will push the record on the top of the
86150 ** stack into the sorter.
86151 */
86152 static void pushOntoSorter(
86153   Parse *pParse,         /* Parser context */
86154   ExprList *pOrderBy,    /* The ORDER BY clause */
86155   Select *pSelect,       /* The whole SELECT statement */
86156   int regData            /* Register holding data to be sorted */
86157 ){
86158   Vdbe *v = pParse->pVdbe;
86159   int nExpr = pOrderBy->nExpr;
86160   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
86161   int regRecord = sqlite3GetTempReg(pParse);
86162   sqlite3ExprCacheClear(pParse);
86163   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
86164   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
86165   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
86166   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
86167   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
86168   sqlite3ReleaseTempReg(pParse, regRecord);
86169   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
86170   if( pSelect->iLimit ){
86171     int addr1, addr2;
86172     int iLimit;
86173     if( pSelect->iOffset ){
86174       iLimit = pSelect->iOffset+1;
86175     }else{
86176       iLimit = pSelect->iLimit;
86177     }
86178     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
86179     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
86180     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
86181     sqlite3VdbeJumpHere(v, addr1);
86182     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
86183     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
86184     sqlite3VdbeJumpHere(v, addr2);
86185     pSelect->iLimit = 0;
86186   }
86187 }
86188
86189 /*
86190 ** Add code to implement the OFFSET
86191 */
86192 static void codeOffset(
86193   Vdbe *v,          /* Generate code into this VM */
86194   Select *p,        /* The SELECT statement being coded */
86195   int iContinue     /* Jump here to skip the current record */
86196 ){
86197   if( p->iOffset && iContinue!=0 ){
86198     int addr;
86199     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
86200     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
86201     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
86202     VdbeComment((v, "skip OFFSET records"));
86203     sqlite3VdbeJumpHere(v, addr);
86204   }
86205 }
86206
86207 /*
86208 ** Add code that will check to make sure the N registers starting at iMem
86209 ** form a distinct entry.  iTab is a sorting index that holds previously
86210 ** seen combinations of the N values.  A new entry is made in iTab
86211 ** if the current N values are new.
86212 **
86213 ** A jump to addrRepeat is made and the N+1 values are popped from the
86214 ** stack if the top N elements are not distinct.
86215 */
86216 static void codeDistinct(
86217   Parse *pParse,     /* Parsing and code generating context */
86218   int iTab,          /* A sorting index used to test for distinctness */
86219   int addrRepeat,    /* Jump to here if not distinct */
86220   int N,             /* Number of elements */
86221   int iMem           /* First element */
86222 ){
86223   Vdbe *v;
86224   int r1;
86225
86226   v = pParse->pVdbe;
86227   r1 = sqlite3GetTempReg(pParse);
86228   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
86229   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
86230   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
86231   sqlite3ReleaseTempReg(pParse, r1);
86232 }
86233
86234 /*
86235 ** Generate an error message when a SELECT is used within a subexpression
86236 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
86237 ** column.  We do this in a subroutine because the error occurs in multiple
86238 ** places.
86239 */
86240 static int checkForMultiColumnSelectError(
86241   Parse *pParse,       /* Parse context. */
86242   SelectDest *pDest,   /* Destination of SELECT results */
86243   int nExpr            /* Number of result columns returned by SELECT */
86244 ){
86245   int eDest = pDest->eDest;
86246   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
86247     sqlite3ErrorMsg(pParse, "only a single result allowed for "
86248        "a SELECT that is part of an expression");
86249     return 1;
86250   }else{
86251     return 0;
86252   }
86253 }
86254
86255 /*
86256 ** This routine generates the code for the inside of the inner loop
86257 ** of a SELECT.
86258 **
86259 ** If srcTab and nColumn are both zero, then the pEList expressions
86260 ** are evaluated in order to get the data for this row.  If nColumn>0
86261 ** then data is pulled from srcTab and pEList is used only to get the
86262 ** datatypes for each column.
86263 */
86264 static void selectInnerLoop(
86265   Parse *pParse,          /* The parser context */
86266   Select *p,              /* The complete select statement being coded */
86267   ExprList *pEList,       /* List of values being extracted */
86268   int srcTab,             /* Pull data from this table */
86269   int nColumn,            /* Number of columns in the source table */
86270   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
86271   int distinct,           /* If >=0, make sure results are distinct */
86272   SelectDest *pDest,      /* How to dispose of the results */
86273   int iContinue,          /* Jump here to continue with next row */
86274   int iBreak              /* Jump here to break out of the inner loop */
86275 ){
86276   Vdbe *v = pParse->pVdbe;
86277   int i;
86278   int hasDistinct;        /* True if the DISTINCT keyword is present */
86279   int regResult;              /* Start of memory holding result set */
86280   int eDest = pDest->eDest;   /* How to dispose of results */
86281   int iParm = pDest->iParm;   /* First argument to disposal method */
86282   int nResultCol;             /* Number of result columns */
86283
86284   assert( v );
86285   if( NEVER(v==0) ) return;
86286   assert( pEList!=0 );
86287   hasDistinct = distinct>=0;
86288   if( pOrderBy==0 && !hasDistinct ){
86289     codeOffset(v, p, iContinue);
86290   }
86291
86292   /* Pull the requested columns.
86293   */
86294   if( nColumn>0 ){
86295     nResultCol = nColumn;
86296   }else{
86297     nResultCol = pEList->nExpr;
86298   }
86299   if( pDest->iMem==0 ){
86300     pDest->iMem = pParse->nMem+1;
86301     pDest->nMem = nResultCol;
86302     pParse->nMem += nResultCol;
86303   }else{ 
86304     assert( pDest->nMem==nResultCol );
86305   }
86306   regResult = pDest->iMem;
86307   if( nColumn>0 ){
86308     for(i=0; i<nColumn; i++){
86309       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
86310     }
86311   }else if( eDest!=SRT_Exists ){
86312     /* If the destination is an EXISTS(...) expression, the actual
86313     ** values returned by the SELECT are not required.
86314     */
86315     sqlite3ExprCacheClear(pParse);
86316     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
86317   }
86318   nColumn = nResultCol;
86319
86320   /* If the DISTINCT keyword was present on the SELECT statement
86321   ** and this row has been seen before, then do not make this row
86322   ** part of the result.
86323   */
86324   if( hasDistinct ){
86325     assert( pEList!=0 );
86326     assert( pEList->nExpr==nColumn );
86327     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
86328     if( pOrderBy==0 ){
86329       codeOffset(v, p, iContinue);
86330     }
86331   }
86332
86333   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
86334     return;
86335   }
86336
86337   switch( eDest ){
86338     /* In this mode, write each query result to the key of the temporary
86339     ** table iParm.
86340     */
86341 #ifndef SQLITE_OMIT_COMPOUND_SELECT
86342     case SRT_Union: {
86343       int r1;
86344       r1 = sqlite3GetTempReg(pParse);
86345       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86346       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
86347       sqlite3ReleaseTempReg(pParse, r1);
86348       break;
86349     }
86350
86351     /* Construct a record from the query result, but instead of
86352     ** saving that record, use it as a key to delete elements from
86353     ** the temporary table iParm.
86354     */
86355     case SRT_Except: {
86356       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
86357       break;
86358     }
86359 #endif
86360
86361     /* Store the result as data using a unique key.
86362     */
86363     case SRT_Table:
86364     case SRT_EphemTab: {
86365       int r1 = sqlite3GetTempReg(pParse);
86366       testcase( eDest==SRT_Table );
86367       testcase( eDest==SRT_EphemTab );
86368       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86369       if( pOrderBy ){
86370         pushOntoSorter(pParse, pOrderBy, p, r1);
86371       }else{
86372         int r2 = sqlite3GetTempReg(pParse);
86373         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
86374         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
86375         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86376         sqlite3ReleaseTempReg(pParse, r2);
86377       }
86378       sqlite3ReleaseTempReg(pParse, r1);
86379       break;
86380     }
86381
86382 #ifndef SQLITE_OMIT_SUBQUERY
86383     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
86384     ** then there should be a single item on the stack.  Write this
86385     ** item into the set table with bogus data.
86386     */
86387     case SRT_Set: {
86388       assert( nColumn==1 );
86389       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
86390       if( pOrderBy ){
86391         /* At first glance you would think we could optimize out the
86392         ** ORDER BY in this case since the order of entries in the set
86393         ** does not matter.  But there might be a LIMIT clause, in which
86394         ** case the order does matter */
86395         pushOntoSorter(pParse, pOrderBy, p, regResult);
86396       }else{
86397         int r1 = sqlite3GetTempReg(pParse);
86398         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
86399         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
86400         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
86401         sqlite3ReleaseTempReg(pParse, r1);
86402       }
86403       break;
86404     }
86405
86406     /* If any row exist in the result set, record that fact and abort.
86407     */
86408     case SRT_Exists: {
86409       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
86410       /* The LIMIT clause will terminate the loop for us */
86411       break;
86412     }
86413
86414     /* If this is a scalar select that is part of an expression, then
86415     ** store the results in the appropriate memory cell and break out
86416     ** of the scan loop.
86417     */
86418     case SRT_Mem: {
86419       assert( nColumn==1 );
86420       if( pOrderBy ){
86421         pushOntoSorter(pParse, pOrderBy, p, regResult);
86422       }else{
86423         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
86424         /* The LIMIT clause will jump out of the loop for us */
86425       }
86426       break;
86427     }
86428 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
86429
86430     /* Send the data to the callback function or to a subroutine.  In the
86431     ** case of a subroutine, the subroutine itself is responsible for
86432     ** popping the data from the stack.
86433     */
86434     case SRT_Coroutine:
86435     case SRT_Output: {
86436       testcase( eDest==SRT_Coroutine );
86437       testcase( eDest==SRT_Output );
86438       if( pOrderBy ){
86439         int r1 = sqlite3GetTempReg(pParse);
86440         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86441         pushOntoSorter(pParse, pOrderBy, p, r1);
86442         sqlite3ReleaseTempReg(pParse, r1);
86443       }else if( eDest==SRT_Coroutine ){
86444         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86445       }else{
86446         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
86447         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
86448       }
86449       break;
86450     }
86451
86452 #if !defined(SQLITE_OMIT_TRIGGER)
86453     /* Discard the results.  This is used for SELECT statements inside
86454     ** the body of a TRIGGER.  The purpose of such selects is to call
86455     ** user-defined functions that have side effects.  We do not care
86456     ** about the actual results of the select.
86457     */
86458     default: {
86459       assert( eDest==SRT_Discard );
86460       break;
86461     }
86462 #endif
86463   }
86464
86465   /* Jump to the end of the loop if the LIMIT is reached.
86466   */
86467   if( p->iLimit ){
86468     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
86469                             ** pushOntoSorter() would have cleared p->iLimit */
86470     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
86471   }
86472 }
86473
86474 /*
86475 ** Given an expression list, generate a KeyInfo structure that records
86476 ** the collating sequence for each expression in that expression list.
86477 **
86478 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
86479 ** KeyInfo structure is appropriate for initializing a virtual index to
86480 ** implement that clause.  If the ExprList is the result set of a SELECT
86481 ** then the KeyInfo structure is appropriate for initializing a virtual
86482 ** index to implement a DISTINCT test.
86483 **
86484 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
86485 ** function is responsible for seeing that this structure is eventually
86486 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
86487 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
86488 */
86489 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
86490   sqlite3 *db = pParse->db;
86491   int nExpr;
86492   KeyInfo *pInfo;
86493   struct ExprList_item *pItem;
86494   int i;
86495
86496   nExpr = pList->nExpr;
86497   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
86498   if( pInfo ){
86499     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
86500     pInfo->nField = (u16)nExpr;
86501     pInfo->enc = ENC(db);
86502     pInfo->db = db;
86503     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
86504       CollSeq *pColl;
86505       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
86506       if( !pColl ){
86507         pColl = db->pDfltColl;
86508       }
86509       pInfo->aColl[i] = pColl;
86510       pInfo->aSortOrder[i] = pItem->sortOrder;
86511     }
86512   }
86513   return pInfo;
86514 }
86515
86516
86517 /*
86518 ** If the inner loop was generated using a non-null pOrderBy argument,
86519 ** then the results were placed in a sorter.  After the loop is terminated
86520 ** we need to run the sorter and output the results.  The following
86521 ** routine generates the code needed to do that.
86522 */
86523 static void generateSortTail(
86524   Parse *pParse,    /* Parsing context */
86525   Select *p,        /* The SELECT statement */
86526   Vdbe *v,          /* Generate code into this VDBE */
86527   int nColumn,      /* Number of columns of data */
86528   SelectDest *pDest /* Write the sorted results here */
86529 ){
86530   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
86531   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
86532   int addr;
86533   int iTab;
86534   int pseudoTab = 0;
86535   ExprList *pOrderBy = p->pOrderBy;
86536
86537   int eDest = pDest->eDest;
86538   int iParm = pDest->iParm;
86539
86540   int regRow;
86541   int regRowid;
86542
86543   iTab = pOrderBy->iECursor;
86544   regRow = sqlite3GetTempReg(pParse);
86545   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86546     pseudoTab = pParse->nTab++;
86547     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
86548     regRowid = 0;
86549   }else{
86550     regRowid = sqlite3GetTempReg(pParse);
86551   }
86552   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
86553   codeOffset(v, p, addrContinue);
86554   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
86555   switch( eDest ){
86556     case SRT_Table:
86557     case SRT_EphemTab: {
86558       testcase( eDest==SRT_Table );
86559       testcase( eDest==SRT_EphemTab );
86560       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
86561       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
86562       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86563       break;
86564     }
86565 #ifndef SQLITE_OMIT_SUBQUERY
86566     case SRT_Set: {
86567       assert( nColumn==1 );
86568       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
86569       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
86570       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
86571       break;
86572     }
86573     case SRT_Mem: {
86574       assert( nColumn==1 );
86575       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
86576       /* The LIMIT clause will terminate the loop for us */
86577       break;
86578     }
86579 #endif
86580     default: {
86581       int i;
86582       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
86583       testcase( eDest==SRT_Output );
86584       testcase( eDest==SRT_Coroutine );
86585       for(i=0; i<nColumn; i++){
86586         assert( regRow!=pDest->iMem+i );
86587         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
86588         if( i==0 ){
86589           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
86590         }
86591       }
86592       if( eDest==SRT_Output ){
86593         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
86594         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
86595       }else{
86596         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86597       }
86598       break;
86599     }
86600   }
86601   sqlite3ReleaseTempReg(pParse, regRow);
86602   sqlite3ReleaseTempReg(pParse, regRowid);
86603
86604   /* LIMIT has been implemented by the pushOntoSorter() routine.
86605   */
86606   assert( p->iLimit==0 );
86607
86608   /* The bottom of the loop
86609   */
86610   sqlite3VdbeResolveLabel(v, addrContinue);
86611   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
86612   sqlite3VdbeResolveLabel(v, addrBreak);
86613   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86614     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
86615   }
86616 }
86617
86618 /*
86619 ** Return a pointer to a string containing the 'declaration type' of the
86620 ** expression pExpr. The string may be treated as static by the caller.
86621 **
86622 ** The declaration type is the exact datatype definition extracted from the
86623 ** original CREATE TABLE statement if the expression is a column. The
86624 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
86625 ** is considered a column can be complex in the presence of subqueries. The
86626 ** result-set expression in all of the following SELECT statements is 
86627 ** considered a column by this function.
86628 **
86629 **   SELECT col FROM tbl;
86630 **   SELECT (SELECT col FROM tbl;
86631 **   SELECT (SELECT col FROM tbl);
86632 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
86633 ** 
86634 ** The declaration type for any expression other than a column is NULL.
86635 */
86636 static const char *columnType(
86637   NameContext *pNC, 
86638   Expr *pExpr,
86639   const char **pzOriginDb,
86640   const char **pzOriginTab,
86641   const char **pzOriginCol
86642 ){
86643   char const *zType = 0;
86644   char const *zOriginDb = 0;
86645   char const *zOriginTab = 0;
86646   char const *zOriginCol = 0;
86647   int j;
86648   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
86649
86650   switch( pExpr->op ){
86651     case TK_AGG_COLUMN:
86652     case TK_COLUMN: {
86653       /* The expression is a column. Locate the table the column is being
86654       ** extracted from in NameContext.pSrcList. This table may be real
86655       ** database table or a subquery.
86656       */
86657       Table *pTab = 0;            /* Table structure column is extracted from */
86658       Select *pS = 0;             /* Select the column is extracted from */
86659       int iCol = pExpr->iColumn;  /* Index of column in pTab */
86660       testcase( pExpr->op==TK_AGG_COLUMN );
86661       testcase( pExpr->op==TK_COLUMN );
86662       while( pNC && !pTab ){
86663         SrcList *pTabList = pNC->pSrcList;
86664         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
86665         if( j<pTabList->nSrc ){
86666           pTab = pTabList->a[j].pTab;
86667           pS = pTabList->a[j].pSelect;
86668         }else{
86669           pNC = pNC->pNext;
86670         }
86671       }
86672
86673       if( pTab==0 ){
86674         /* At one time, code such as "SELECT new.x" within a trigger would
86675         ** cause this condition to run.  Since then, we have restructured how
86676         ** trigger code is generated and so this condition is no longer 
86677         ** possible. However, it can still be true for statements like
86678         ** the following:
86679         **
86680         **   CREATE TABLE t1(col INTEGER);
86681         **   SELECT (SELECT t1.col) FROM FROM t1;
86682         **
86683         ** when columnType() is called on the expression "t1.col" in the 
86684         ** sub-select. In this case, set the column type to NULL, even
86685         ** though it should really be "INTEGER".
86686         **
86687         ** This is not a problem, as the column type of "t1.col" is never
86688         ** used. When columnType() is called on the expression 
86689         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
86690         ** branch below.  */
86691         break;
86692       }
86693
86694       assert( pTab && pExpr->pTab==pTab );
86695       if( pS ){
86696         /* The "table" is actually a sub-select or a view in the FROM clause
86697         ** of the SELECT statement. Return the declaration type and origin
86698         ** data for the result-set column of the sub-select.
86699         */
86700         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
86701           /* If iCol is less than zero, then the expression requests the
86702           ** rowid of the sub-select or view. This expression is legal (see 
86703           ** test case misc2.2.2) - it always evaluates to NULL.
86704           */
86705           NameContext sNC;
86706           Expr *p = pS->pEList->a[iCol].pExpr;
86707           sNC.pSrcList = pS->pSrc;
86708           sNC.pNext = pNC;
86709           sNC.pParse = pNC->pParse;
86710           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
86711         }
86712       }else if( ALWAYS(pTab->pSchema) ){
86713         /* A real table */
86714         assert( !pS );
86715         if( iCol<0 ) iCol = pTab->iPKey;
86716         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86717         if( iCol<0 ){
86718           zType = "INTEGER";
86719           zOriginCol = "rowid";
86720         }else{
86721           zType = pTab->aCol[iCol].zType;
86722           zOriginCol = pTab->aCol[iCol].zName;
86723         }
86724         zOriginTab = pTab->zName;
86725         if( pNC->pParse ){
86726           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
86727           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
86728         }
86729       }
86730       break;
86731     }
86732 #ifndef SQLITE_OMIT_SUBQUERY
86733     case TK_SELECT: {
86734       /* The expression is a sub-select. Return the declaration type and
86735       ** origin info for the single column in the result set of the SELECT
86736       ** statement.
86737       */
86738       NameContext sNC;
86739       Select *pS = pExpr->x.pSelect;
86740       Expr *p = pS->pEList->a[0].pExpr;
86741       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
86742       sNC.pSrcList = pS->pSrc;
86743       sNC.pNext = pNC;
86744       sNC.pParse = pNC->pParse;
86745       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
86746       break;
86747     }
86748 #endif
86749   }
86750   
86751   if( pzOriginDb ){
86752     assert( pzOriginTab && pzOriginCol );
86753     *pzOriginDb = zOriginDb;
86754     *pzOriginTab = zOriginTab;
86755     *pzOriginCol = zOriginCol;
86756   }
86757   return zType;
86758 }
86759
86760 /*
86761 ** Generate code that will tell the VDBE the declaration types of columns
86762 ** in the result set.
86763 */
86764 static void generateColumnTypes(
86765   Parse *pParse,      /* Parser context */
86766   SrcList *pTabList,  /* List of tables */
86767   ExprList *pEList    /* Expressions defining the result set */
86768 ){
86769 #ifndef SQLITE_OMIT_DECLTYPE
86770   Vdbe *v = pParse->pVdbe;
86771   int i;
86772   NameContext sNC;
86773   sNC.pSrcList = pTabList;
86774   sNC.pParse = pParse;
86775   for(i=0; i<pEList->nExpr; i++){
86776     Expr *p = pEList->a[i].pExpr;
86777     const char *zType;
86778 #ifdef SQLITE_ENABLE_COLUMN_METADATA
86779     const char *zOrigDb = 0;
86780     const char *zOrigTab = 0;
86781     const char *zOrigCol = 0;
86782     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
86783
86784     /* The vdbe must make its own copy of the column-type and other 
86785     ** column specific strings, in case the schema is reset before this
86786     ** virtual machine is deleted.
86787     */
86788     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
86789     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
86790     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
86791 #else
86792     zType = columnType(&sNC, p, 0, 0, 0);
86793 #endif
86794     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
86795   }
86796 #endif /* SQLITE_OMIT_DECLTYPE */
86797 }
86798
86799 /*
86800 ** Generate code that will tell the VDBE the names of columns
86801 ** in the result set.  This information is used to provide the
86802 ** azCol[] values in the callback.
86803 */
86804 static void generateColumnNames(
86805   Parse *pParse,      /* Parser context */
86806   SrcList *pTabList,  /* List of tables */
86807   ExprList *pEList    /* Expressions defining the result set */
86808 ){
86809   Vdbe *v = pParse->pVdbe;
86810   int i, j;
86811   sqlite3 *db = pParse->db;
86812   int fullNames, shortNames;
86813
86814 #ifndef SQLITE_OMIT_EXPLAIN
86815   /* If this is an EXPLAIN, skip this step */
86816   if( pParse->explain ){
86817     return;
86818   }
86819 #endif
86820
86821   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
86822   pParse->colNamesSet = 1;
86823   fullNames = (db->flags & SQLITE_FullColNames)!=0;
86824   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
86825   sqlite3VdbeSetNumCols(v, pEList->nExpr);
86826   for(i=0; i<pEList->nExpr; i++){
86827     Expr *p;
86828     p = pEList->a[i].pExpr;
86829     if( NEVER(p==0) ) continue;
86830     if( pEList->a[i].zName ){
86831       char *zName = pEList->a[i].zName;
86832       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
86833     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
86834       Table *pTab;
86835       char *zCol;
86836       int iCol = p->iColumn;
86837       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
86838         if( pTabList->a[j].iCursor==p->iTable ) break;
86839       }
86840       assert( j<pTabList->nSrc );
86841       pTab = pTabList->a[j].pTab;
86842       if( iCol<0 ) iCol = pTab->iPKey;
86843       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86844       if( iCol<0 ){
86845         zCol = "rowid";
86846       }else{
86847         zCol = pTab->aCol[iCol].zName;
86848       }
86849       if( !shortNames && !fullNames ){
86850         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
86851             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86852       }else if( fullNames ){
86853         char *zName = 0;
86854         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
86855         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
86856       }else{
86857         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
86858       }
86859     }else{
86860       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
86861           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86862     }
86863   }
86864   generateColumnTypes(pParse, pTabList, pEList);
86865 }
86866
86867 #ifndef SQLITE_OMIT_COMPOUND_SELECT
86868 /*
86869 ** Name of the connection operator, used for error messages.
86870 */
86871 static const char *selectOpName(int id){
86872   char *z;
86873   switch( id ){
86874     case TK_ALL:       z = "UNION ALL";   break;
86875     case TK_INTERSECT: z = "INTERSECT";   break;
86876     case TK_EXCEPT:    z = "EXCEPT";      break;
86877     default:           z = "UNION";       break;
86878   }
86879   return z;
86880 }
86881 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
86882
86883 /*
86884 ** Given a an expression list (which is really the list of expressions
86885 ** that form the result set of a SELECT statement) compute appropriate
86886 ** column names for a table that would hold the expression list.
86887 **
86888 ** All column names will be unique.
86889 **
86890 ** Only the column names are computed.  Column.zType, Column.zColl,
86891 ** and other fields of Column are zeroed.
86892 **
86893 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
86894 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
86895 */
86896 static int selectColumnsFromExprList(
86897   Parse *pParse,          /* Parsing context */
86898   ExprList *pEList,       /* Expr list from which to derive column names */
86899   int *pnCol,             /* Write the number of columns here */
86900   Column **paCol          /* Write the new column list here */
86901 ){
86902   sqlite3 *db = pParse->db;   /* Database connection */
86903   int i, j;                   /* Loop counters */
86904   int cnt;                    /* Index added to make the name unique */
86905   Column *aCol, *pCol;        /* For looping over result columns */
86906   int nCol;                   /* Number of columns in the result set */
86907   Expr *p;                    /* Expression for a single result column */
86908   char *zName;                /* Column name */
86909   int nName;                  /* Size of name in zName[] */
86910
86911   *pnCol = nCol = pEList->nExpr;
86912   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
86913   if( aCol==0 ) return SQLITE_NOMEM;
86914   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
86915     /* Get an appropriate name for the column
86916     */
86917     p = pEList->a[i].pExpr;
86918     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
86919                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
86920     if( (zName = pEList->a[i].zName)!=0 ){
86921       /* If the column contains an "AS <name>" phrase, use <name> as the name */
86922       zName = sqlite3DbStrDup(db, zName);
86923     }else{
86924       Expr *pColExpr = p;  /* The expression that is the result column name */
86925       Table *pTab;         /* Table associated with this expression */
86926       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
86927       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
86928         /* For columns use the column name name */
86929         int iCol = pColExpr->iColumn;
86930         pTab = pColExpr->pTab;
86931         if( iCol<0 ) iCol = pTab->iPKey;
86932         zName = sqlite3MPrintf(db, "%s",
86933                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
86934       }else if( pColExpr->op==TK_ID ){
86935         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
86936         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
86937       }else{
86938         /* Use the original text of the column expression as its name */
86939         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
86940       }
86941     }
86942     if( db->mallocFailed ){
86943       sqlite3DbFree(db, zName);
86944       break;
86945     }
86946
86947     /* Make sure the column name is unique.  If the name is not unique,
86948     ** append a integer to the name so that it becomes unique.
86949     */
86950     nName = sqlite3Strlen30(zName);
86951     for(j=cnt=0; j<i; j++){
86952       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
86953         char *zNewName;
86954         zName[nName] = 0;
86955         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
86956         sqlite3DbFree(db, zName);
86957         zName = zNewName;
86958         j = -1;
86959         if( zName==0 ) break;
86960       }
86961     }
86962     pCol->zName = zName;
86963   }
86964   if( db->mallocFailed ){
86965     for(j=0; j<i; j++){
86966       sqlite3DbFree(db, aCol[j].zName);
86967     }
86968     sqlite3DbFree(db, aCol);
86969     *paCol = 0;
86970     *pnCol = 0;
86971     return SQLITE_NOMEM;
86972   }
86973   return SQLITE_OK;
86974 }
86975
86976 /*
86977 ** Add type and collation information to a column list based on
86978 ** a SELECT statement.
86979 ** 
86980 ** The column list presumably came from selectColumnNamesFromExprList().
86981 ** The column list has only names, not types or collations.  This
86982 ** routine goes through and adds the types and collations.
86983 **
86984 ** This routine requires that all identifiers in the SELECT
86985 ** statement be resolved.
86986 */
86987 static void selectAddColumnTypeAndCollation(
86988   Parse *pParse,        /* Parsing contexts */
86989   int nCol,             /* Number of columns */
86990   Column *aCol,         /* List of columns */
86991   Select *pSelect       /* SELECT used to determine types and collations */
86992 ){
86993   sqlite3 *db = pParse->db;
86994   NameContext sNC;
86995   Column *pCol;
86996   CollSeq *pColl;
86997   int i;
86998   Expr *p;
86999   struct ExprList_item *a;
87000
87001   assert( pSelect!=0 );
87002   assert( (pSelect->selFlags & SF_Resolved)!=0 );
87003   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
87004   if( db->mallocFailed ) return;
87005   memset(&sNC, 0, sizeof(sNC));
87006   sNC.pSrcList = pSelect->pSrc;
87007   a = pSelect->pEList->a;
87008   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
87009     p = a[i].pExpr;
87010     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
87011     pCol->affinity = sqlite3ExprAffinity(p);
87012     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
87013     pColl = sqlite3ExprCollSeq(pParse, p);
87014     if( pColl ){
87015       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
87016     }
87017   }
87018 }
87019
87020 /*
87021 ** Given a SELECT statement, generate a Table structure that describes
87022 ** the result set of that SELECT.
87023 */
87024 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
87025   Table *pTab;
87026   sqlite3 *db = pParse->db;
87027   int savedFlags;
87028
87029   savedFlags = db->flags;
87030   db->flags &= ~SQLITE_FullColNames;
87031   db->flags |= SQLITE_ShortColNames;
87032   sqlite3SelectPrep(pParse, pSelect, 0);
87033   if( pParse->nErr ) return 0;
87034   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
87035   db->flags = savedFlags;
87036   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
87037   if( pTab==0 ){
87038     return 0;
87039   }
87040   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
87041   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
87042   assert( db->lookaside.bEnabled==0 );
87043   pTab->dbMem = 0;
87044   pTab->nRef = 1;
87045   pTab->zName = 0;
87046   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
87047   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
87048   pTab->iPKey = -1;
87049   if( db->mallocFailed ){
87050     sqlite3DeleteTable(pTab);
87051     return 0;
87052   }
87053   return pTab;
87054 }
87055
87056 /*
87057 ** Get a VDBE for the given parser context.  Create a new one if necessary.
87058 ** If an error occurs, return NULL and leave a message in pParse.
87059 */
87060 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
87061   Vdbe *v = pParse->pVdbe;
87062   if( v==0 ){
87063     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
87064 #ifndef SQLITE_OMIT_TRACE
87065     if( v ){
87066       sqlite3VdbeAddOp0(v, OP_Trace);
87067     }
87068 #endif
87069   }
87070   return v;
87071 }
87072
87073
87074 /*
87075 ** Compute the iLimit and iOffset fields of the SELECT based on the
87076 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
87077 ** that appear in the original SQL statement after the LIMIT and OFFSET
87078 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
87079 ** are the integer memory register numbers for counters used to compute 
87080 ** the limit and offset.  If there is no limit and/or offset, then 
87081 ** iLimit and iOffset are negative.
87082 **
87083 ** This routine changes the values of iLimit and iOffset only if
87084 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
87085 ** iOffset should have been preset to appropriate default values
87086 ** (usually but not always -1) prior to calling this routine.
87087 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
87088 ** redefined.  The UNION ALL operator uses this property to force
87089 ** the reuse of the same limit and offset registers across multiple
87090 ** SELECT statements.
87091 */
87092 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
87093   Vdbe *v = 0;
87094   int iLimit = 0;
87095   int iOffset;
87096   int addr1, n;
87097   if( p->iLimit ) return;
87098
87099   /* 
87100   ** "LIMIT -1" always shows all rows.  There is some
87101   ** contraversy about what the correct behavior should be.
87102   ** The current implementation interprets "LIMIT 0" to mean
87103   ** no rows.
87104   */
87105   sqlite3ExprCacheClear(pParse);
87106   assert( p->pOffset==0 || p->pLimit!=0 );
87107   if( p->pLimit ){
87108     p->iLimit = iLimit = ++pParse->nMem;
87109     v = sqlite3GetVdbe(pParse);
87110     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
87111     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
87112       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
87113       VdbeComment((v, "LIMIT counter"));
87114       if( n==0 ){
87115         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
87116       }
87117     }else{
87118       sqlite3ExprCode(pParse, p->pLimit, iLimit);
87119       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
87120       VdbeComment((v, "LIMIT counter"));
87121       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
87122     }
87123     if( p->pOffset ){
87124       p->iOffset = iOffset = ++pParse->nMem;
87125       pParse->nMem++;   /* Allocate an extra register for limit+offset */
87126       sqlite3ExprCode(pParse, p->pOffset, iOffset);
87127       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
87128       VdbeComment((v, "OFFSET counter"));
87129       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
87130       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
87131       sqlite3VdbeJumpHere(v, addr1);
87132       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
87133       VdbeComment((v, "LIMIT+OFFSET"));
87134       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
87135       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
87136       sqlite3VdbeJumpHere(v, addr1);
87137     }
87138   }
87139 }
87140
87141 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87142 /*
87143 ** Return the appropriate collating sequence for the iCol-th column of
87144 ** the result set for the compound-select statement "p".  Return NULL if
87145 ** the column has no default collating sequence.
87146 **
87147 ** The collating sequence for the compound select is taken from the
87148 ** left-most term of the select that has a collating sequence.
87149 */
87150 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
87151   CollSeq *pRet;
87152   if( p->pPrior ){
87153     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
87154   }else{
87155     pRet = 0;
87156   }
87157   assert( iCol>=0 );
87158   if( pRet==0 && iCol<p->pEList->nExpr ){
87159     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
87160   }
87161   return pRet;
87162 }
87163 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
87164
87165 /* Forward reference */
87166 static int multiSelectOrderBy(
87167   Parse *pParse,        /* Parsing context */
87168   Select *p,            /* The right-most of SELECTs to be coded */
87169   SelectDest *pDest     /* What to do with query results */
87170 );
87171
87172
87173 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87174 /*
87175 ** This routine is called to process a compound query form from
87176 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
87177 ** INTERSECT
87178 **
87179 ** "p" points to the right-most of the two queries.  the query on the
87180 ** left is p->pPrior.  The left query could also be a compound query
87181 ** in which case this routine will be called recursively. 
87182 **
87183 ** The results of the total query are to be written into a destination
87184 ** of type eDest with parameter iParm.
87185 **
87186 ** Example 1:  Consider a three-way compound SQL statement.
87187 **
87188 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
87189 **
87190 ** This statement is parsed up as follows:
87191 **
87192 **     SELECT c FROM t3
87193 **      |
87194 **      `----->  SELECT b FROM t2
87195 **                |
87196 **                `------>  SELECT a FROM t1
87197 **
87198 ** The arrows in the diagram above represent the Select.pPrior pointer.
87199 ** So if this routine is called with p equal to the t3 query, then
87200 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
87201 **
87202 ** Notice that because of the way SQLite parses compound SELECTs, the
87203 ** individual selects always group from left to right.
87204 */
87205 static int multiSelect(
87206   Parse *pParse,        /* Parsing context */
87207   Select *p,            /* The right-most of SELECTs to be coded */
87208   SelectDest *pDest     /* What to do with query results */
87209 ){
87210   int rc = SQLITE_OK;   /* Success code from a subroutine */
87211   Select *pPrior;       /* Another SELECT immediately to our left */
87212   Vdbe *v;              /* Generate code to this VDBE */
87213   SelectDest dest;      /* Alternative data destination */
87214   Select *pDelete = 0;  /* Chain of simple selects to delete */
87215   sqlite3 *db;          /* Database connection */
87216
87217   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
87218   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
87219   */
87220   assert( p && p->pPrior );  /* Calling function guarantees this much */
87221   db = pParse->db;
87222   pPrior = p->pPrior;
87223   assert( pPrior->pRightmost!=pPrior );
87224   assert( pPrior->pRightmost==p->pRightmost );
87225   dest = *pDest;
87226   if( pPrior->pOrderBy ){
87227     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
87228       selectOpName(p->op));
87229     rc = 1;
87230     goto multi_select_end;
87231   }
87232   if( pPrior->pLimit ){
87233     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
87234       selectOpName(p->op));
87235     rc = 1;
87236     goto multi_select_end;
87237   }
87238
87239   v = sqlite3GetVdbe(pParse);
87240   assert( v!=0 );  /* The VDBE already created by calling function */
87241
87242   /* Create the destination temporary table if necessary
87243   */
87244   if( dest.eDest==SRT_EphemTab ){
87245     assert( p->pEList );
87246     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
87247     dest.eDest = SRT_Table;
87248   }
87249
87250   /* Make sure all SELECTs in the statement have the same number of elements
87251   ** in their result sets.
87252   */
87253   assert( p->pEList && pPrior->pEList );
87254   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
87255     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
87256       " do not have the same number of result columns", selectOpName(p->op));
87257     rc = 1;
87258     goto multi_select_end;
87259   }
87260
87261   /* Compound SELECTs that have an ORDER BY clause are handled separately.
87262   */
87263   if( p->pOrderBy ){
87264     return multiSelectOrderBy(pParse, p, pDest);
87265   }
87266
87267   /* Generate code for the left and right SELECT statements.
87268   */
87269   switch( p->op ){
87270     case TK_ALL: {
87271       int addr = 0;
87272       assert( !pPrior->pLimit );
87273       pPrior->pLimit = p->pLimit;
87274       pPrior->pOffset = p->pOffset;
87275       rc = sqlite3Select(pParse, pPrior, &dest);
87276       p->pLimit = 0;
87277       p->pOffset = 0;
87278       if( rc ){
87279         goto multi_select_end;
87280       }
87281       p->pPrior = 0;
87282       p->iLimit = pPrior->iLimit;
87283       p->iOffset = pPrior->iOffset;
87284       if( p->iLimit ){
87285         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
87286         VdbeComment((v, "Jump ahead if LIMIT reached"));
87287       }
87288       rc = sqlite3Select(pParse, p, &dest);
87289       testcase( rc!=SQLITE_OK );
87290       pDelete = p->pPrior;
87291       p->pPrior = pPrior;
87292       if( addr ){
87293         sqlite3VdbeJumpHere(v, addr);
87294       }
87295       break;
87296     }
87297     case TK_EXCEPT:
87298     case TK_UNION: {
87299       int unionTab;    /* Cursor number of the temporary table holding result */
87300       u8 op = 0;       /* One of the SRT_ operations to apply to self */
87301       int priorOp;     /* The SRT_ operation to apply to prior selects */
87302       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
87303       int addr;
87304       SelectDest uniondest;
87305
87306       testcase( p->op==TK_EXCEPT );
87307       testcase( p->op==TK_UNION );
87308       priorOp = SRT_Union;
87309       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
87310         /* We can reuse a temporary table generated by a SELECT to our
87311         ** right.
87312         */
87313         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
87314                                      ** of a 3-way or more compound */
87315         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
87316         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
87317         unionTab = dest.iParm;
87318       }else{
87319         /* We will need to create our own temporary table to hold the
87320         ** intermediate results.
87321         */
87322         unionTab = pParse->nTab++;
87323         assert( p->pOrderBy==0 );
87324         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
87325         assert( p->addrOpenEphm[0] == -1 );
87326         p->addrOpenEphm[0] = addr;
87327         p->pRightmost->selFlags |= SF_UsesEphemeral;
87328         assert( p->pEList );
87329       }
87330
87331       /* Code the SELECT statements to our left
87332       */
87333       assert( !pPrior->pOrderBy );
87334       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
87335       rc = sqlite3Select(pParse, pPrior, &uniondest);
87336       if( rc ){
87337         goto multi_select_end;
87338       }
87339
87340       /* Code the current SELECT statement
87341       */
87342       if( p->op==TK_EXCEPT ){
87343         op = SRT_Except;
87344       }else{
87345         assert( p->op==TK_UNION );
87346         op = SRT_Union;
87347       }
87348       p->pPrior = 0;
87349       pLimit = p->pLimit;
87350       p->pLimit = 0;
87351       pOffset = p->pOffset;
87352       p->pOffset = 0;
87353       uniondest.eDest = op;
87354       rc = sqlite3Select(pParse, p, &uniondest);
87355       testcase( rc!=SQLITE_OK );
87356       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
87357       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
87358       sqlite3ExprListDelete(db, p->pOrderBy);
87359       pDelete = p->pPrior;
87360       p->pPrior = pPrior;
87361       p->pOrderBy = 0;
87362       sqlite3ExprDelete(db, p->pLimit);
87363       p->pLimit = pLimit;
87364       p->pOffset = pOffset;
87365       p->iLimit = 0;
87366       p->iOffset = 0;
87367
87368       /* Convert the data in the temporary table into whatever form
87369       ** it is that we currently need.
87370       */
87371       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
87372       if( dest.eDest!=priorOp ){
87373         int iCont, iBreak, iStart;
87374         assert( p->pEList );
87375         if( dest.eDest==SRT_Output ){
87376           Select *pFirst = p;
87377           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87378           generateColumnNames(pParse, 0, pFirst->pEList);
87379         }
87380         iBreak = sqlite3VdbeMakeLabel(v);
87381         iCont = sqlite3VdbeMakeLabel(v);
87382         computeLimitRegisters(pParse, p, iBreak);
87383         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
87384         iStart = sqlite3VdbeCurrentAddr(v);
87385         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
87386                         0, -1, &dest, iCont, iBreak);
87387         sqlite3VdbeResolveLabel(v, iCont);
87388         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
87389         sqlite3VdbeResolveLabel(v, iBreak);
87390         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
87391       }
87392       break;
87393     }
87394     default: assert( p->op==TK_INTERSECT ); {
87395       int tab1, tab2;
87396       int iCont, iBreak, iStart;
87397       Expr *pLimit, *pOffset;
87398       int addr;
87399       SelectDest intersectdest;
87400       int r1;
87401
87402       /* INTERSECT is different from the others since it requires
87403       ** two temporary tables.  Hence it has its own case.  Begin
87404       ** by allocating the tables we will need.
87405       */
87406       tab1 = pParse->nTab++;
87407       tab2 = pParse->nTab++;
87408       assert( p->pOrderBy==0 );
87409
87410       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
87411       assert( p->addrOpenEphm[0] == -1 );
87412       p->addrOpenEphm[0] = addr;
87413       p->pRightmost->selFlags |= SF_UsesEphemeral;
87414       assert( p->pEList );
87415
87416       /* Code the SELECTs to our left into temporary table "tab1".
87417       */
87418       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
87419       rc = sqlite3Select(pParse, pPrior, &intersectdest);
87420       if( rc ){
87421         goto multi_select_end;
87422       }
87423
87424       /* Code the current SELECT into temporary table "tab2"
87425       */
87426       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
87427       assert( p->addrOpenEphm[1] == -1 );
87428       p->addrOpenEphm[1] = addr;
87429       p->pPrior = 0;
87430       pLimit = p->pLimit;
87431       p->pLimit = 0;
87432       pOffset = p->pOffset;
87433       p->pOffset = 0;
87434       intersectdest.iParm = tab2;
87435       rc = sqlite3Select(pParse, p, &intersectdest);
87436       testcase( rc!=SQLITE_OK );
87437       pDelete = p->pPrior;
87438       p->pPrior = pPrior;
87439       sqlite3ExprDelete(db, p->pLimit);
87440       p->pLimit = pLimit;
87441       p->pOffset = pOffset;
87442
87443       /* Generate code to take the intersection of the two temporary
87444       ** tables.
87445       */
87446       assert( p->pEList );
87447       if( dest.eDest==SRT_Output ){
87448         Select *pFirst = p;
87449         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87450         generateColumnNames(pParse, 0, pFirst->pEList);
87451       }
87452       iBreak = sqlite3VdbeMakeLabel(v);
87453       iCont = sqlite3VdbeMakeLabel(v);
87454       computeLimitRegisters(pParse, p, iBreak);
87455       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
87456       r1 = sqlite3GetTempReg(pParse);
87457       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
87458       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
87459       sqlite3ReleaseTempReg(pParse, r1);
87460       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
87461                       0, -1, &dest, iCont, iBreak);
87462       sqlite3VdbeResolveLabel(v, iCont);
87463       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
87464       sqlite3VdbeResolveLabel(v, iBreak);
87465       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
87466       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
87467       break;
87468     }
87469   }
87470
87471   /* Compute collating sequences used by 
87472   ** temporary tables needed to implement the compound select.
87473   ** Attach the KeyInfo structure to all temporary tables.
87474   **
87475   ** This section is run by the right-most SELECT statement only.
87476   ** SELECT statements to the left always skip this part.  The right-most
87477   ** SELECT might also skip this part if it has no ORDER BY clause and
87478   ** no temp tables are required.
87479   */
87480   if( p->selFlags & SF_UsesEphemeral ){
87481     int i;                        /* Loop counter */
87482     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
87483     Select *pLoop;                /* For looping through SELECT statements */
87484     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
87485     int nCol;                     /* Number of columns in result set */
87486
87487     assert( p->pRightmost==p );
87488     nCol = p->pEList->nExpr;
87489     pKeyInfo = sqlite3DbMallocZero(db,
87490                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
87491     if( !pKeyInfo ){
87492       rc = SQLITE_NOMEM;
87493       goto multi_select_end;
87494     }
87495
87496     pKeyInfo->enc = ENC(db);
87497     pKeyInfo->nField = (u16)nCol;
87498
87499     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
87500       *apColl = multiSelectCollSeq(pParse, p, i);
87501       if( 0==*apColl ){
87502         *apColl = db->pDfltColl;
87503       }
87504     }
87505
87506     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
87507       for(i=0; i<2; i++){
87508         int addr = pLoop->addrOpenEphm[i];
87509         if( addr<0 ){
87510           /* If [0] is unused then [1] is also unused.  So we can
87511           ** always safely abort as soon as the first unused slot is found */
87512           assert( pLoop->addrOpenEphm[1]<0 );
87513           break;
87514         }
87515         sqlite3VdbeChangeP2(v, addr, nCol);
87516         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
87517         pLoop->addrOpenEphm[i] = -1;
87518       }
87519     }
87520     sqlite3DbFree(db, pKeyInfo);
87521   }
87522
87523 multi_select_end:
87524   pDest->iMem = dest.iMem;
87525   pDest->nMem = dest.nMem;
87526   sqlite3SelectDelete(db, pDelete);
87527   return rc;
87528 }
87529 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
87530
87531 /*
87532 ** Code an output subroutine for a coroutine implementation of a
87533 ** SELECT statment.
87534 **
87535 ** The data to be output is contained in pIn->iMem.  There are
87536 ** pIn->nMem columns to be output.  pDest is where the output should
87537 ** be sent.
87538 **
87539 ** regReturn is the number of the register holding the subroutine
87540 ** return address.
87541 **
87542 ** If regPrev>0 then it is a the first register in a vector that
87543 ** records the previous output.  mem[regPrev] is a flag that is false
87544 ** if there has been no previous output.  If regPrev>0 then code is
87545 ** generated to suppress duplicates.  pKeyInfo is used for comparing
87546 ** keys.
87547 **
87548 ** If the LIMIT found in p->iLimit is reached, jump immediately to
87549 ** iBreak.
87550 */
87551 static int generateOutputSubroutine(
87552   Parse *pParse,          /* Parsing context */
87553   Select *p,              /* The SELECT statement */
87554   SelectDest *pIn,        /* Coroutine supplying data */
87555   SelectDest *pDest,      /* Where to send the data */
87556   int regReturn,          /* The return address register */
87557   int regPrev,            /* Previous result register.  No uniqueness if 0 */
87558   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
87559   int p4type,             /* The p4 type for pKeyInfo */
87560   int iBreak              /* Jump here if we hit the LIMIT */
87561 ){
87562   Vdbe *v = pParse->pVdbe;
87563   int iContinue;
87564   int addr;
87565
87566   addr = sqlite3VdbeCurrentAddr(v);
87567   iContinue = sqlite3VdbeMakeLabel(v);
87568
87569   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
87570   */
87571   if( regPrev ){
87572     int j1, j2;
87573     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
87574     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
87575                               (char*)pKeyInfo, p4type);
87576     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
87577     sqlite3VdbeJumpHere(v, j1);
87578     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
87579     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
87580   }
87581   if( pParse->db->mallocFailed ) return 0;
87582
87583   /* Suppress the the first OFFSET entries if there is an OFFSET clause
87584   */
87585   codeOffset(v, p, iContinue);
87586
87587   switch( pDest->eDest ){
87588     /* Store the result as data using a unique key.
87589     */
87590     case SRT_Table:
87591     case SRT_EphemTab: {
87592       int r1 = sqlite3GetTempReg(pParse);
87593       int r2 = sqlite3GetTempReg(pParse);
87594       testcase( pDest->eDest==SRT_Table );
87595       testcase( pDest->eDest==SRT_EphemTab );
87596       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
87597       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
87598       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
87599       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87600       sqlite3ReleaseTempReg(pParse, r2);
87601       sqlite3ReleaseTempReg(pParse, r1);
87602       break;
87603     }
87604
87605 #ifndef SQLITE_OMIT_SUBQUERY
87606     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
87607     ** then there should be a single item on the stack.  Write this
87608     ** item into the set table with bogus data.
87609     */
87610     case SRT_Set: {
87611       int r1;
87612       assert( pIn->nMem==1 );
87613       p->affinity = 
87614          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
87615       r1 = sqlite3GetTempReg(pParse);
87616       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
87617       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
87618       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
87619       sqlite3ReleaseTempReg(pParse, r1);
87620       break;
87621     }
87622
87623 #if 0  /* Never occurs on an ORDER BY query */
87624     /* If any row exist in the result set, record that fact and abort.
87625     */
87626     case SRT_Exists: {
87627       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
87628       /* The LIMIT clause will terminate the loop for us */
87629       break;
87630     }
87631 #endif
87632
87633     /* If this is a scalar select that is part of an expression, then
87634     ** store the results in the appropriate memory cell and break out
87635     ** of the scan loop.
87636     */
87637     case SRT_Mem: {
87638       assert( pIn->nMem==1 );
87639       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
87640       /* The LIMIT clause will jump out of the loop for us */
87641       break;
87642     }
87643 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
87644
87645     /* The results are stored in a sequence of registers
87646     ** starting at pDest->iMem.  Then the co-routine yields.
87647     */
87648     case SRT_Coroutine: {
87649       if( pDest->iMem==0 ){
87650         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
87651         pDest->nMem = pIn->nMem;
87652       }
87653       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
87654       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87655       break;
87656     }
87657
87658     /* If none of the above, then the result destination must be
87659     ** SRT_Output.  This routine is never called with any other
87660     ** destination other than the ones handled above or SRT_Output.
87661     **
87662     ** For SRT_Output, results are stored in a sequence of registers.  
87663     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
87664     ** return the next row of result.
87665     */
87666     default: {
87667       assert( pDest->eDest==SRT_Output );
87668       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
87669       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
87670       break;
87671     }
87672   }
87673
87674   /* Jump to the end of the loop if the LIMIT is reached.
87675   */
87676   if( p->iLimit ){
87677     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
87678   }
87679
87680   /* Generate the subroutine return
87681   */
87682   sqlite3VdbeResolveLabel(v, iContinue);
87683   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
87684
87685   return addr;
87686 }
87687
87688 /*
87689 ** Alternative compound select code generator for cases when there
87690 ** is an ORDER BY clause.
87691 **
87692 ** We assume a query of the following form:
87693 **
87694 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
87695 **
87696 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
87697 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
87698 ** co-routines.  Then run the co-routines in parallel and merge the results
87699 ** into the output.  In addition to the two coroutines (called selectA and
87700 ** selectB) there are 7 subroutines:
87701 **
87702 **    outA:    Move the output of the selectA coroutine into the output
87703 **             of the compound query.
87704 **
87705 **    outB:    Move the output of the selectB coroutine into the output
87706 **             of the compound query.  (Only generated for UNION and
87707 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
87708 **             appears only in B.)
87709 **
87710 **    AltB:    Called when there is data from both coroutines and A<B.
87711 **
87712 **    AeqB:    Called when there is data from both coroutines and A==B.
87713 **
87714 **    AgtB:    Called when there is data from both coroutines and A>B.
87715 **
87716 **    EofA:    Called when data is exhausted from selectA.
87717 **
87718 **    EofB:    Called when data is exhausted from selectB.
87719 **
87720 ** The implementation of the latter five subroutines depend on which 
87721 ** <operator> is used:
87722 **
87723 **
87724 **             UNION ALL         UNION            EXCEPT          INTERSECT
87725 **          -------------  -----------------  --------------  -----------------
87726 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
87727 **
87728 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
87729 **
87730 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
87731 **
87732 **   EofA:   outB, nextB      outB, nextB          halt             halt
87733 **
87734 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
87735 **
87736 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
87737 ** causes an immediate jump to EofA and an EOF on B following nextB causes
87738 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
87739 ** following nextX causes a jump to the end of the select processing.
87740 **
87741 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
87742 ** within the output subroutine.  The regPrev register set holds the previously
87743 ** output value.  A comparison is made against this value and the output
87744 ** is skipped if the next results would be the same as the previous.
87745 **
87746 ** The implementation plan is to implement the two coroutines and seven
87747 ** subroutines first, then put the control logic at the bottom.  Like this:
87748 **
87749 **          goto Init
87750 **     coA: coroutine for left query (A)
87751 **     coB: coroutine for right query (B)
87752 **    outA: output one row of A
87753 **    outB: output one row of B (UNION and UNION ALL only)
87754 **    EofA: ...
87755 **    EofB: ...
87756 **    AltB: ...
87757 **    AeqB: ...
87758 **    AgtB: ...
87759 **    Init: initialize coroutine registers
87760 **          yield coA
87761 **          if eof(A) goto EofA
87762 **          yield coB
87763 **          if eof(B) goto EofB
87764 **    Cmpr: Compare A, B
87765 **          Jump AltB, AeqB, AgtB
87766 **     End: ...
87767 **
87768 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
87769 ** actually called using Gosub and they do not Return.  EofA and EofB loop
87770 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
87771 ** and AgtB jump to either L2 or to one of EofA or EofB.
87772 */
87773 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87774 static int multiSelectOrderBy(
87775   Parse *pParse,        /* Parsing context */
87776   Select *p,            /* The right-most of SELECTs to be coded */
87777   SelectDest *pDest     /* What to do with query results */
87778 ){
87779   int i, j;             /* Loop counters */
87780   Select *pPrior;       /* Another SELECT immediately to our left */
87781   Vdbe *v;              /* Generate code to this VDBE */
87782   SelectDest destA;     /* Destination for coroutine A */
87783   SelectDest destB;     /* Destination for coroutine B */
87784   int regAddrA;         /* Address register for select-A coroutine */
87785   int regEofA;          /* Flag to indicate when select-A is complete */
87786   int regAddrB;         /* Address register for select-B coroutine */
87787   int regEofB;          /* Flag to indicate when select-B is complete */
87788   int addrSelectA;      /* Address of the select-A coroutine */
87789   int addrSelectB;      /* Address of the select-B coroutine */
87790   int regOutA;          /* Address register for the output-A subroutine */
87791   int regOutB;          /* Address register for the output-B subroutine */
87792   int addrOutA;         /* Address of the output-A subroutine */
87793   int addrOutB = 0;     /* Address of the output-B subroutine */
87794   int addrEofA;         /* Address of the select-A-exhausted subroutine */
87795   int addrEofB;         /* Address of the select-B-exhausted subroutine */
87796   int addrAltB;         /* Address of the A<B subroutine */
87797   int addrAeqB;         /* Address of the A==B subroutine */
87798   int addrAgtB;         /* Address of the A>B subroutine */
87799   int regLimitA;        /* Limit register for select-A */
87800   int regLimitB;        /* Limit register for select-A */
87801   int regPrev;          /* A range of registers to hold previous output */
87802   int savedLimit;       /* Saved value of p->iLimit */
87803   int savedOffset;      /* Saved value of p->iOffset */
87804   int labelCmpr;        /* Label for the start of the merge algorithm */
87805   int labelEnd;         /* Label for the end of the overall SELECT stmt */
87806   int j1;               /* Jump instructions that get retargetted */
87807   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
87808   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
87809   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
87810   sqlite3 *db;          /* Database connection */
87811   ExprList *pOrderBy;   /* The ORDER BY clause */
87812   int nOrderBy;         /* Number of terms in the ORDER BY clause */
87813   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
87814
87815   assert( p->pOrderBy!=0 );
87816   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
87817   db = pParse->db;
87818   v = pParse->pVdbe;
87819   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
87820   labelEnd = sqlite3VdbeMakeLabel(v);
87821   labelCmpr = sqlite3VdbeMakeLabel(v);
87822
87823
87824   /* Patch up the ORDER BY clause
87825   */
87826   op = p->op;  
87827   pPrior = p->pPrior;
87828   assert( pPrior->pOrderBy==0 );
87829   pOrderBy = p->pOrderBy;
87830   assert( pOrderBy );
87831   nOrderBy = pOrderBy->nExpr;
87832
87833   /* For operators other than UNION ALL we have to make sure that
87834   ** the ORDER BY clause covers every term of the result set.  Add
87835   ** terms to the ORDER BY clause as necessary.
87836   */
87837   if( op!=TK_ALL ){
87838     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
87839       struct ExprList_item *pItem;
87840       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
87841         assert( pItem->iCol>0 );
87842         if( pItem->iCol==i ) break;
87843       }
87844       if( j==nOrderBy ){
87845         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
87846         if( pNew==0 ) return SQLITE_NOMEM;
87847         pNew->flags |= EP_IntValue;
87848         pNew->u.iValue = i;
87849         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
87850         pOrderBy->a[nOrderBy++].iCol = (u16)i;
87851       }
87852     }
87853   }
87854
87855   /* Compute the comparison permutation and keyinfo that is used with
87856   ** the permutation used to determine if the next
87857   ** row of results comes from selectA or selectB.  Also add explicit
87858   ** collations to the ORDER BY clause terms so that when the subqueries
87859   ** to the right and the left are evaluated, they use the correct
87860   ** collation.
87861   */
87862   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
87863   if( aPermute ){
87864     struct ExprList_item *pItem;
87865     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
87866       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
87867       aPermute[i] = pItem->iCol - 1;
87868     }
87869     pKeyMerge =
87870       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
87871     if( pKeyMerge ){
87872       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
87873       pKeyMerge->nField = (u16)nOrderBy;
87874       pKeyMerge->enc = ENC(db);
87875       for(i=0; i<nOrderBy; i++){
87876         CollSeq *pColl;
87877         Expr *pTerm = pOrderBy->a[i].pExpr;
87878         if( pTerm->flags & EP_ExpCollate ){
87879           pColl = pTerm->pColl;
87880         }else{
87881           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
87882           pTerm->flags |= EP_ExpCollate;
87883           pTerm->pColl = pColl;
87884         }
87885         pKeyMerge->aColl[i] = pColl;
87886         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
87887       }
87888     }
87889   }else{
87890     pKeyMerge = 0;
87891   }
87892
87893   /* Reattach the ORDER BY clause to the query.
87894   */
87895   p->pOrderBy = pOrderBy;
87896   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
87897
87898   /* Allocate a range of temporary registers and the KeyInfo needed
87899   ** for the logic that removes duplicate result rows when the
87900   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
87901   */
87902   if( op==TK_ALL ){
87903     regPrev = 0;
87904   }else{
87905     int nExpr = p->pEList->nExpr;
87906     assert( nOrderBy>=nExpr || db->mallocFailed );
87907     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
87908     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
87909     pKeyDup = sqlite3DbMallocZero(db,
87910                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
87911     if( pKeyDup ){
87912       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
87913       pKeyDup->nField = (u16)nExpr;
87914       pKeyDup->enc = ENC(db);
87915       for(i=0; i<nExpr; i++){
87916         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
87917         pKeyDup->aSortOrder[i] = 0;
87918       }
87919     }
87920   }
87921  
87922   /* Separate the left and the right query from one another
87923   */
87924   p->pPrior = 0;
87925   pPrior->pRightmost = 0;
87926   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
87927   if( pPrior->pPrior==0 ){
87928     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
87929   }
87930
87931   /* Compute the limit registers */
87932   computeLimitRegisters(pParse, p, labelEnd);
87933   if( p->iLimit && op==TK_ALL ){
87934     regLimitA = ++pParse->nMem;
87935     regLimitB = ++pParse->nMem;
87936     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
87937                                   regLimitA);
87938     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
87939   }else{
87940     regLimitA = regLimitB = 0;
87941   }
87942   sqlite3ExprDelete(db, p->pLimit);
87943   p->pLimit = 0;
87944   sqlite3ExprDelete(db, p->pOffset);
87945   p->pOffset = 0;
87946
87947   regAddrA = ++pParse->nMem;
87948   regEofA = ++pParse->nMem;
87949   regAddrB = ++pParse->nMem;
87950   regEofB = ++pParse->nMem;
87951   regOutA = ++pParse->nMem;
87952   regOutB = ++pParse->nMem;
87953   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
87954   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
87955
87956   /* Jump past the various subroutines and coroutines to the main
87957   ** merge loop
87958   */
87959   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
87960   addrSelectA = sqlite3VdbeCurrentAddr(v);
87961
87962
87963   /* Generate a coroutine to evaluate the SELECT statement to the
87964   ** left of the compound operator - the "A" select.
87965   */
87966   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
87967   pPrior->iLimit = regLimitA;
87968   sqlite3Select(pParse, pPrior, &destA);
87969   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
87970   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87971   VdbeNoopComment((v, "End coroutine for left SELECT"));
87972
87973   /* Generate a coroutine to evaluate the SELECT statement on 
87974   ** the right - the "B" select
87975   */
87976   addrSelectB = sqlite3VdbeCurrentAddr(v);
87977   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
87978   savedLimit = p->iLimit;
87979   savedOffset = p->iOffset;
87980   p->iLimit = regLimitB;
87981   p->iOffset = 0;  
87982   sqlite3Select(pParse, p, &destB);
87983   p->iLimit = savedLimit;
87984   p->iOffset = savedOffset;
87985   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
87986   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87987   VdbeNoopComment((v, "End coroutine for right SELECT"));
87988
87989   /* Generate a subroutine that outputs the current row of the A
87990   ** select as the next output row of the compound select.
87991   */
87992   VdbeNoopComment((v, "Output routine for A"));
87993   addrOutA = generateOutputSubroutine(pParse,
87994                  p, &destA, pDest, regOutA,
87995                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
87996   
87997   /* Generate a subroutine that outputs the current row of the B
87998   ** select as the next output row of the compound select.
87999   */
88000   if( op==TK_ALL || op==TK_UNION ){
88001     VdbeNoopComment((v, "Output routine for B"));
88002     addrOutB = generateOutputSubroutine(pParse,
88003                  p, &destB, pDest, regOutB,
88004                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
88005   }
88006
88007   /* Generate a subroutine to run when the results from select A
88008   ** are exhausted and only data in select B remains.
88009   */
88010   VdbeNoopComment((v, "eof-A subroutine"));
88011   if( op==TK_EXCEPT || op==TK_INTERSECT ){
88012     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
88013   }else{  
88014     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
88015     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
88016     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88017     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
88018   }
88019
88020   /* Generate a subroutine to run when the results from select B
88021   ** are exhausted and only data in select A remains.
88022   */
88023   if( op==TK_INTERSECT ){
88024     addrEofB = addrEofA;
88025   }else{  
88026     VdbeNoopComment((v, "eof-B subroutine"));
88027     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
88028     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88029     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88030     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
88031   }
88032
88033   /* Generate code to handle the case of A<B
88034   */
88035   VdbeNoopComment((v, "A-lt-B subroutine"));
88036   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88037   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88038   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88039   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88040
88041   /* Generate code to handle the case of A==B
88042   */
88043   if( op==TK_ALL ){
88044     addrAeqB = addrAltB;
88045   }else if( op==TK_INTERSECT ){
88046     addrAeqB = addrAltB;
88047     addrAltB++;
88048   }else{
88049     VdbeNoopComment((v, "A-eq-B subroutine"));
88050     addrAeqB =
88051     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88052     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88053     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88054   }
88055
88056   /* Generate code to handle the case of A>B
88057   */
88058   VdbeNoopComment((v, "A-gt-B subroutine"));
88059   addrAgtB = sqlite3VdbeCurrentAddr(v);
88060   if( op==TK_ALL || op==TK_UNION ){
88061     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
88062   }
88063   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88064   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88065   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88066
88067   /* This code runs once to initialize everything.
88068   */
88069   sqlite3VdbeJumpHere(v, j1);
88070   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
88071   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
88072   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
88073   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
88074   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88075   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88076
88077   /* Implement the main merge loop
88078   */
88079   sqlite3VdbeResolveLabel(v, labelCmpr);
88080   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
88081   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
88082                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
88083   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
88084
88085   /* Release temporary registers
88086   */
88087   if( regPrev ){
88088     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
88089   }
88090
88091   /* Jump to the this point in order to terminate the query.
88092   */
88093   sqlite3VdbeResolveLabel(v, labelEnd);
88094
88095   /* Set the number of output columns
88096   */
88097   if( pDest->eDest==SRT_Output ){
88098     Select *pFirst = pPrior;
88099     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88100     generateColumnNames(pParse, 0, pFirst->pEList);
88101   }
88102
88103   /* Reassembly the compound query so that it will be freed correctly
88104   ** by the calling function */
88105   if( p->pPrior ){
88106     sqlite3SelectDelete(db, p->pPrior);
88107   }
88108   p->pPrior = pPrior;
88109
88110   /*** TBD:  Insert subroutine calls to close cursors on incomplete
88111   **** subqueries ****/
88112   return SQLITE_OK;
88113 }
88114 #endif
88115
88116 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
88117 /* Forward Declarations */
88118 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
88119 static void substSelect(sqlite3*, Select *, int, ExprList *);
88120
88121 /*
88122 ** Scan through the expression pExpr.  Replace every reference to
88123 ** a column in table number iTable with a copy of the iColumn-th
88124 ** entry in pEList.  (But leave references to the ROWID column 
88125 ** unchanged.)
88126 **
88127 ** This routine is part of the flattening procedure.  A subquery
88128 ** whose result set is defined by pEList appears as entry in the
88129 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
88130 ** FORM clause entry is iTable.  This routine make the necessary 
88131 ** changes to pExpr so that it refers directly to the source table
88132 ** of the subquery rather the result set of the subquery.
88133 */
88134 static Expr *substExpr(
88135   sqlite3 *db,        /* Report malloc errors to this connection */
88136   Expr *pExpr,        /* Expr in which substitution occurs */
88137   int iTable,         /* Table to be substituted */
88138   ExprList *pEList    /* Substitute expressions */
88139 ){
88140   if( pExpr==0 ) return 0;
88141   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
88142     if( pExpr->iColumn<0 ){
88143       pExpr->op = TK_NULL;
88144     }else{
88145       Expr *pNew;
88146       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
88147       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88148       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
88149       if( pNew && pExpr->pColl ){
88150         pNew->pColl = pExpr->pColl;
88151       }
88152       sqlite3ExprDelete(db, pExpr);
88153       pExpr = pNew;
88154     }
88155   }else{
88156     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
88157     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
88158     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88159       substSelect(db, pExpr->x.pSelect, iTable, pEList);
88160     }else{
88161       substExprList(db, pExpr->x.pList, iTable, pEList);
88162     }
88163   }
88164   return pExpr;
88165 }
88166 static void substExprList(
88167   sqlite3 *db,         /* Report malloc errors here */
88168   ExprList *pList,     /* List to scan and in which to make substitutes */
88169   int iTable,          /* Table to be substituted */
88170   ExprList *pEList     /* Substitute values */
88171 ){
88172   int i;
88173   if( pList==0 ) return;
88174   for(i=0; i<pList->nExpr; i++){
88175     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
88176   }
88177 }
88178 static void substSelect(
88179   sqlite3 *db,         /* Report malloc errors here */
88180   Select *p,           /* SELECT statement in which to make substitutions */
88181   int iTable,          /* Table to be replaced */
88182   ExprList *pEList     /* Substitute values */
88183 ){
88184   SrcList *pSrc;
88185   struct SrcList_item *pItem;
88186   int i;
88187   if( !p ) return;
88188   substExprList(db, p->pEList, iTable, pEList);
88189   substExprList(db, p->pGroupBy, iTable, pEList);
88190   substExprList(db, p->pOrderBy, iTable, pEList);
88191   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
88192   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
88193   substSelect(db, p->pPrior, iTable, pEList);
88194   pSrc = p->pSrc;
88195   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
88196   if( ALWAYS(pSrc) ){
88197     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
88198       substSelect(db, pItem->pSelect, iTable, pEList);
88199     }
88200   }
88201 }
88202 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
88203
88204 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
88205 /*
88206 ** This routine attempts to flatten subqueries in order to speed
88207 ** execution.  It returns 1 if it makes changes and 0 if no flattening
88208 ** occurs.
88209 **
88210 ** To understand the concept of flattening, consider the following
88211 ** query:
88212 **
88213 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
88214 **
88215 ** The default way of implementing this query is to execute the
88216 ** subquery first and store the results in a temporary table, then
88217 ** run the outer query on that temporary table.  This requires two
88218 ** passes over the data.  Furthermore, because the temporary table
88219 ** has no indices, the WHERE clause on the outer query cannot be
88220 ** optimized.
88221 **
88222 ** This routine attempts to rewrite queries such as the above into
88223 ** a single flat select, like this:
88224 **
88225 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
88226 **
88227 ** The code generated for this simpification gives the same result
88228 ** but only has to scan the data once.  And because indices might 
88229 ** exist on the table t1, a complete scan of the data might be
88230 ** avoided.
88231 **
88232 ** Flattening is only attempted if all of the following are true:
88233 **
88234 **   (1)  The subquery and the outer query do not both use aggregates.
88235 **
88236 **   (2)  The subquery is not an aggregate or the outer query is not a join.
88237 **
88238 **   (3)  The subquery is not the right operand of a left outer join
88239 **        (Originally ticket #306.  Strenghtened by ticket #3300)
88240 **
88241 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
88242 **
88243 **   (5)  The subquery is not DISTINCT or the outer query does not use
88244 **        aggregates.
88245 **
88246 **   (6)  The subquery does not use aggregates or the outer query is not
88247 **        DISTINCT.
88248 **
88249 **   (7)  The subquery has a FROM clause.
88250 **
88251 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
88252 **
88253 **   (9)  The subquery does not use LIMIT or the outer query does not use
88254 **        aggregates.
88255 **
88256 **  (10)  The subquery does not use aggregates or the outer query does not
88257 **        use LIMIT.
88258 **
88259 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
88260 **
88261 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
88262 **        a separate restriction deriving from ticket #350.
88263 **
88264 **  (13)  The subquery and outer query do not both use LIMIT
88265 **
88266 **  (14)  The subquery does not use OFFSET
88267 **
88268 **  (15)  The outer query is not part of a compound select or the
88269 **        subquery does not have a LIMIT clause.
88270 **        (See ticket #2339 and ticket [02a8e81d44]).
88271 **
88272 **  (16)  The outer query is not an aggregate or the subquery does
88273 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
88274 **        until we introduced the group_concat() function.  
88275 **
88276 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
88277 **        compound clause made up entirely of non-aggregate queries, and 
88278 **        the parent query:
88279 **
88280 **          * is not itself part of a compound select,
88281 **          * is not an aggregate or DISTINCT query, and
88282 **          * has no other tables or sub-selects in the FROM clause.
88283 **
88284 **        The parent and sub-query may contain WHERE clauses. Subject to
88285 **        rules (11), (13) and (14), they may also contain ORDER BY,
88286 **        LIMIT and OFFSET clauses.
88287 **
88288 **  (18)  If the sub-query is a compound select, then all terms of the
88289 **        ORDER by clause of the parent must be simple references to 
88290 **        columns of the sub-query.
88291 **
88292 **  (19)  The subquery does not use LIMIT or the outer query does not
88293 **        have a WHERE clause.
88294 **
88295 **  (20)  If the sub-query is a compound select, then it must not use
88296 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
88297 **        somewhat by saying that the terms of the ORDER BY clause must
88298 **        appear as unmodified result columns in the outer query.  But
88299 **        have other optimizations in mind to deal with that case.
88300 **
88301 ** In this routine, the "p" parameter is a pointer to the outer query.
88302 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
88303 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
88304 **
88305 ** If flattening is not attempted, this routine is a no-op and returns 0.
88306 ** If flattening is attempted this routine returns 1.
88307 **
88308 ** All of the expression analysis must occur on both the outer query and
88309 ** the subquery before this routine runs.
88310 */
88311 static int flattenSubquery(
88312   Parse *pParse,       /* Parsing context */
88313   Select *p,           /* The parent or outer SELECT statement */
88314   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
88315   int isAgg,           /* True if outer SELECT uses aggregate functions */
88316   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
88317 ){
88318   const char *zSavedAuthContext = pParse->zAuthContext;
88319   Select *pParent;
88320   Select *pSub;       /* The inner query or "subquery" */
88321   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
88322   SrcList *pSrc;      /* The FROM clause of the outer query */
88323   SrcList *pSubSrc;   /* The FROM clause of the subquery */
88324   ExprList *pList;    /* The result set of the outer query */
88325   int iParent;        /* VDBE cursor number of the pSub result set temp table */
88326   int i;              /* Loop counter */
88327   Expr *pWhere;                    /* The WHERE clause */
88328   struct SrcList_item *pSubitem;   /* The subquery */
88329   sqlite3 *db = pParse->db;
88330
88331   /* Check to see if flattening is permitted.  Return 0 if not.
88332   */
88333   assert( p!=0 );
88334   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
88335   if( db->flags & SQLITE_QueryFlattener ) return 0;
88336   pSrc = p->pSrc;
88337   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
88338   pSubitem = &pSrc->a[iFrom];
88339   iParent = pSubitem->iCursor;
88340   pSub = pSubitem->pSelect;
88341   assert( pSub!=0 );
88342   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
88343   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
88344   pSubSrc = pSub->pSrc;
88345   assert( pSubSrc );
88346   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
88347   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
88348   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
88349   ** became arbitrary expressions, we were forced to add restrictions (13)
88350   ** and (14). */
88351   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
88352   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
88353   if( p->pRightmost && pSub->pLimit ){
88354     return 0;                                            /* Restriction (15) */
88355   }
88356   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
88357   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
88358          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
88359      return 0;       
88360   }
88361   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
88362      return 0;         /* Restriction (6)  */
88363   }
88364   if( p->pOrderBy && pSub->pOrderBy ){
88365      return 0;                                           /* Restriction (11) */
88366   }
88367   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
88368   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
88369
88370   /* OBSOLETE COMMENT 1:
88371   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
88372   ** not used as the right operand of an outer join.  Examples of why this
88373   ** is not allowed:
88374   **
88375   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
88376   **
88377   ** If we flatten the above, we would get
88378   **
88379   **         (t1 LEFT OUTER JOIN t2) JOIN t3
88380   **
88381   ** which is not at all the same thing.
88382   **
88383   ** OBSOLETE COMMENT 2:
88384   ** Restriction 12:  If the subquery is the right operand of a left outer
88385   ** join, make sure the subquery has no WHERE clause.
88386   ** An examples of why this is not allowed:
88387   **
88388   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
88389   **
88390   ** If we flatten the above, we would get
88391   **
88392   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
88393   **
88394   ** But the t2.x>0 test will always fail on a NULL row of t2, which
88395   ** effectively converts the OUTER JOIN into an INNER JOIN.
88396   **
88397   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
88398   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
88399   ** is fraught with danger.  Best to avoid the whole thing.  If the
88400   ** subquery is the right term of a LEFT JOIN, then do not flatten.
88401   */
88402   if( (pSubitem->jointype & JT_OUTER)!=0 ){
88403     return 0;
88404   }
88405
88406   /* Restriction 17: If the sub-query is a compound SELECT, then it must
88407   ** use only the UNION ALL operator. And none of the simple select queries
88408   ** that make up the compound SELECT are allowed to be aggregate or distinct
88409   ** queries.
88410   */
88411   if( pSub->pPrior ){
88412     if( pSub->pOrderBy ){
88413       return 0;  /* Restriction 20 */
88414     }
88415     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
88416       return 0;
88417     }
88418     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
88419       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
88420       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
88421       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
88422        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
88423        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
88424       ){
88425         return 0;
88426       }
88427     }
88428
88429     /* Restriction 18. */
88430     if( p->pOrderBy ){
88431       int ii;
88432       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
88433         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
88434       }
88435     }
88436   }
88437
88438   /***** If we reach this point, flattening is permitted. *****/
88439
88440   /* Authorize the subquery */
88441   pParse->zAuthContext = pSubitem->zName;
88442   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
88443   pParse->zAuthContext = zSavedAuthContext;
88444
88445   /* If the sub-query is a compound SELECT statement, then (by restrictions
88446   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
88447   ** be of the form:
88448   **
88449   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
88450   **
88451   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
88452   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
88453   ** OFFSET clauses and joins them to the left-hand-side of the original
88454   ** using UNION ALL operators. In this case N is the number of simple
88455   ** select statements in the compound sub-query.
88456   **
88457   ** Example:
88458   **
88459   **     SELECT a+1 FROM (
88460   **        SELECT x FROM tab
88461   **        UNION ALL
88462   **        SELECT y FROM tab
88463   **        UNION ALL
88464   **        SELECT abs(z*2) FROM tab2
88465   **     ) WHERE a!=5 ORDER BY 1
88466   **
88467   ** Transformed into:
88468   **
88469   **     SELECT x+1 FROM tab WHERE x+1!=5
88470   **     UNION ALL
88471   **     SELECT y+1 FROM tab WHERE y+1!=5
88472   **     UNION ALL
88473   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
88474   **     ORDER BY 1
88475   **
88476   ** We call this the "compound-subquery flattening".
88477   */
88478   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
88479     Select *pNew;
88480     ExprList *pOrderBy = p->pOrderBy;
88481     Expr *pLimit = p->pLimit;
88482     Select *pPrior = p->pPrior;
88483     p->pOrderBy = 0;
88484     p->pSrc = 0;
88485     p->pPrior = 0;
88486     p->pLimit = 0;
88487     pNew = sqlite3SelectDup(db, p, 0);
88488     p->pLimit = pLimit;
88489     p->pOrderBy = pOrderBy;
88490     p->pSrc = pSrc;
88491     p->op = TK_ALL;
88492     p->pRightmost = 0;
88493     if( pNew==0 ){
88494       pNew = pPrior;
88495     }else{
88496       pNew->pPrior = pPrior;
88497       pNew->pRightmost = 0;
88498     }
88499     p->pPrior = pNew;
88500     if( db->mallocFailed ) return 1;
88501   }
88502
88503   /* Begin flattening the iFrom-th entry of the FROM clause 
88504   ** in the outer query.
88505   */
88506   pSub = pSub1 = pSubitem->pSelect;
88507
88508   /* Delete the transient table structure associated with the
88509   ** subquery
88510   */
88511   sqlite3DbFree(db, pSubitem->zDatabase);
88512   sqlite3DbFree(db, pSubitem->zName);
88513   sqlite3DbFree(db, pSubitem->zAlias);
88514   pSubitem->zDatabase = 0;
88515   pSubitem->zName = 0;
88516   pSubitem->zAlias = 0;
88517   pSubitem->pSelect = 0;
88518
88519   /* Defer deleting the Table object associated with the
88520   ** subquery until code generation is
88521   ** complete, since there may still exist Expr.pTab entries that
88522   ** refer to the subquery even after flattening.  Ticket #3346.
88523   **
88524   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
88525   */
88526   if( ALWAYS(pSubitem->pTab!=0) ){
88527     Table *pTabToDel = pSubitem->pTab;
88528     if( pTabToDel->nRef==1 ){
88529       Parse *pToplevel = sqlite3ParseToplevel(pParse);
88530       pTabToDel->pNextZombie = pToplevel->pZombieTab;
88531       pToplevel->pZombieTab = pTabToDel;
88532     }else{
88533       pTabToDel->nRef--;
88534     }
88535     pSubitem->pTab = 0;
88536   }
88537
88538   /* The following loop runs once for each term in a compound-subquery
88539   ** flattening (as described above).  If we are doing a different kind
88540   ** of flattening - a flattening other than a compound-subquery flattening -
88541   ** then this loop only runs once.
88542   **
88543   ** This loop moves all of the FROM elements of the subquery into the
88544   ** the FROM clause of the outer query.  Before doing this, remember
88545   ** the cursor number for the original outer query FROM element in
88546   ** iParent.  The iParent cursor will never be used.  Subsequent code
88547   ** will scan expressions looking for iParent references and replace
88548   ** those references with expressions that resolve to the subquery FROM
88549   ** elements we are now copying in.
88550   */
88551   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
88552     int nSubSrc;
88553     u8 jointype = 0;
88554     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
88555     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
88556     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
88557
88558     if( pSrc ){
88559       assert( pParent==p );  /* First time through the loop */
88560       jointype = pSubitem->jointype;
88561     }else{
88562       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
88563       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88564       if( pSrc==0 ){
88565         assert( db->mallocFailed );
88566         break;
88567       }
88568     }
88569
88570     /* The subquery uses a single slot of the FROM clause of the outer
88571     ** query.  If the subquery has more than one element in its FROM clause,
88572     ** then expand the outer query to make space for it to hold all elements
88573     ** of the subquery.
88574     **
88575     ** Example:
88576     **
88577     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
88578     **
88579     ** The outer query has 3 slots in its FROM clause.  One slot of the
88580     ** outer query (the middle slot) is used by the subquery.  The next
88581     ** block of code will expand the out query to 4 slots.  The middle
88582     ** slot is expanded to two slots in order to make space for the
88583     ** two elements in the FROM clause of the subquery.
88584     */
88585     if( nSubSrc>1 ){
88586       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
88587       if( db->mallocFailed ){
88588         break;
88589       }
88590     }
88591
88592     /* Transfer the FROM clause terms from the subquery into the
88593     ** outer query.
88594     */
88595     for(i=0; i<nSubSrc; i++){
88596       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
88597       pSrc->a[i+iFrom] = pSubSrc->a[i];
88598       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
88599     }
88600     pSrc->a[iFrom].jointype = jointype;
88601   
88602     /* Now begin substituting subquery result set expressions for 
88603     ** references to the iParent in the outer query.
88604     ** 
88605     ** Example:
88606     **
88607     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
88608     **   \                     \_____________ subquery __________/          /
88609     **    \_____________________ outer query ______________________________/
88610     **
88611     ** We look at every expression in the outer query and every place we see
88612     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
88613     */
88614     pList = pParent->pEList;
88615     for(i=0; i<pList->nExpr; i++){
88616       if( pList->a[i].zName==0 ){
88617         const char *zSpan = pList->a[i].zSpan;
88618         if( ALWAYS(zSpan) ){
88619           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
88620         }
88621       }
88622     }
88623     substExprList(db, pParent->pEList, iParent, pSub->pEList);
88624     if( isAgg ){
88625       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
88626       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88627     }
88628     if( pSub->pOrderBy ){
88629       assert( pParent->pOrderBy==0 );
88630       pParent->pOrderBy = pSub->pOrderBy;
88631       pSub->pOrderBy = 0;
88632     }else if( pParent->pOrderBy ){
88633       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
88634     }
88635     if( pSub->pWhere ){
88636       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
88637     }else{
88638       pWhere = 0;
88639     }
88640     if( subqueryIsAgg ){
88641       assert( pParent->pHaving==0 );
88642       pParent->pHaving = pParent->pWhere;
88643       pParent->pWhere = pWhere;
88644       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88645       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
88646                                   sqlite3ExprDup(db, pSub->pHaving, 0));
88647       assert( pParent->pGroupBy==0 );
88648       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
88649     }else{
88650       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
88651       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
88652     }
88653   
88654     /* The flattened query is distinct if either the inner or the
88655     ** outer query is distinct. 
88656     */
88657     pParent->selFlags |= pSub->selFlags & SF_Distinct;
88658   
88659     /*
88660     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
88661     **
88662     ** One is tempted to try to add a and b to combine the limits.  But this
88663     ** does not work if either limit is negative.
88664     */
88665     if( pSub->pLimit ){
88666       pParent->pLimit = pSub->pLimit;
88667       pSub->pLimit = 0;
88668     }
88669   }
88670
88671   /* Finially, delete what is left of the subquery and return
88672   ** success.
88673   */
88674   sqlite3SelectDelete(db, pSub1);
88675
88676   return 1;
88677 }
88678 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
88679
88680 /*
88681 ** Analyze the SELECT statement passed as an argument to see if it
88682 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
88683 ** it is, or 0 otherwise. At present, a query is considered to be
88684 ** a min()/max() query if:
88685 **
88686 **   1. There is a single object in the FROM clause.
88687 **
88688 **   2. There is a single expression in the result set, and it is
88689 **      either min(x) or max(x), where x is a column reference.
88690 */
88691 static u8 minMaxQuery(Select *p){
88692   Expr *pExpr;
88693   ExprList *pEList = p->pEList;
88694
88695   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
88696   pExpr = pEList->a[0].pExpr;
88697   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88698   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
88699   pEList = pExpr->x.pList;
88700   if( pEList==0 || pEList->nExpr!=1 ) return 0;
88701   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
88702   assert( !ExprHasProperty(pExpr, EP_IntValue) );
88703   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
88704     return WHERE_ORDERBY_MIN;
88705   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
88706     return WHERE_ORDERBY_MAX;
88707   }
88708   return WHERE_ORDERBY_NORMAL;
88709 }
88710
88711 /*
88712 ** The select statement passed as the first argument is an aggregate query.
88713 ** The second argment is the associated aggregate-info object. This 
88714 ** function tests if the SELECT is of the form:
88715 **
88716 **   SELECT count(*) FROM <tbl>
88717 **
88718 ** where table is a database table, not a sub-select or view. If the query
88719 ** does match this pattern, then a pointer to the Table object representing
88720 ** <tbl> is returned. Otherwise, 0 is returned.
88721 */
88722 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
88723   Table *pTab;
88724   Expr *pExpr;
88725
88726   assert( !p->pGroupBy );
88727
88728   if( p->pWhere || p->pEList->nExpr!=1 
88729    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
88730   ){
88731     return 0;
88732   }
88733   pTab = p->pSrc->a[0].pTab;
88734   pExpr = p->pEList->a[0].pExpr;
88735   assert( pTab && !pTab->pSelect && pExpr );
88736
88737   if( IsVirtual(pTab) ) return 0;
88738   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88739   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
88740   if( pExpr->flags&EP_Distinct ) return 0;
88741
88742   return pTab;
88743 }
88744
88745 /*
88746 ** If the source-list item passed as an argument was augmented with an
88747 ** INDEXED BY clause, then try to locate the specified index. If there
88748 ** was such a clause and the named index cannot be found, return 
88749 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
88750 ** pFrom->pIndex and return SQLITE_OK.
88751 */
88752 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
88753   if( pFrom->pTab && pFrom->zIndex ){
88754     Table *pTab = pFrom->pTab;
88755     char *zIndex = pFrom->zIndex;
88756     Index *pIdx;
88757     for(pIdx=pTab->pIndex; 
88758         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
88759         pIdx=pIdx->pNext
88760     );
88761     if( !pIdx ){
88762       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
88763       pParse->checkSchema = 1;
88764       return SQLITE_ERROR;
88765     }
88766     pFrom->pIndex = pIdx;
88767   }
88768   return SQLITE_OK;
88769 }
88770
88771 /*
88772 ** This routine is a Walker callback for "expanding" a SELECT statement.
88773 ** "Expanding" means to do the following:
88774 **
88775 **    (1)  Make sure VDBE cursor numbers have been assigned to every
88776 **         element of the FROM clause.
88777 **
88778 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
88779 **         defines FROM clause.  When views appear in the FROM clause,
88780 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
88781 **         that implements the view.  A copy is made of the view's SELECT
88782 **         statement so that we can freely modify or delete that statement
88783 **         without worrying about messing up the presistent representation
88784 **         of the view.
88785 **
88786 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
88787 **         on joins and the ON and USING clause of joins.
88788 **
88789 **    (4)  Scan the list of columns in the result set (pEList) looking
88790 **         for instances of the "*" operator or the TABLE.* operator.
88791 **         If found, expand each "*" to be every column in every table
88792 **         and TABLE.* to be every column in TABLE.
88793 **
88794 */
88795 static int selectExpander(Walker *pWalker, Select *p){
88796   Parse *pParse = pWalker->pParse;
88797   int i, j, k;
88798   SrcList *pTabList;
88799   ExprList *pEList;
88800   struct SrcList_item *pFrom;
88801   sqlite3 *db = pParse->db;
88802
88803   if( db->mallocFailed  ){
88804     return WRC_Abort;
88805   }
88806   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
88807     return WRC_Prune;
88808   }
88809   p->selFlags |= SF_Expanded;
88810   pTabList = p->pSrc;
88811   pEList = p->pEList;
88812
88813   /* Make sure cursor numbers have been assigned to all entries in
88814   ** the FROM clause of the SELECT statement.
88815   */
88816   sqlite3SrcListAssignCursors(pParse, pTabList);
88817
88818   /* Look up every table named in the FROM clause of the select.  If
88819   ** an entry of the FROM clause is a subquery instead of a table or view,
88820   ** then create a transient table structure to describe the subquery.
88821   */
88822   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88823     Table *pTab;
88824     if( pFrom->pTab!=0 ){
88825       /* This statement has already been prepared.  There is no need
88826       ** to go further. */
88827       assert( i==0 );
88828       return WRC_Prune;
88829     }
88830     if( pFrom->zName==0 ){
88831 #ifndef SQLITE_OMIT_SUBQUERY
88832       Select *pSel = pFrom->pSelect;
88833       /* A sub-query in the FROM clause of a SELECT */
88834       assert( pSel!=0 );
88835       assert( pFrom->pTab==0 );
88836       sqlite3WalkSelect(pWalker, pSel);
88837       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
88838       if( pTab==0 ) return WRC_Abort;
88839       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
88840       pTab->nRef = 1;
88841       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
88842       while( pSel->pPrior ){ pSel = pSel->pPrior; }
88843       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
88844       pTab->iPKey = -1;
88845       pTab->tabFlags |= TF_Ephemeral;
88846 #endif
88847     }else{
88848       /* An ordinary table or view name in the FROM clause */
88849       assert( pFrom->pTab==0 );
88850       pFrom->pTab = pTab = 
88851         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
88852       if( pTab==0 ) return WRC_Abort;
88853       pTab->nRef++;
88854 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
88855       if( pTab->pSelect || IsVirtual(pTab) ){
88856         /* We reach here if the named table is a really a view */
88857         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
88858         assert( pFrom->pSelect==0 );
88859         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
88860         sqlite3WalkSelect(pWalker, pFrom->pSelect);
88861       }
88862 #endif
88863     }
88864
88865     /* Locate the index named by the INDEXED BY clause, if any. */
88866     if( sqlite3IndexedByLookup(pParse, pFrom) ){
88867       return WRC_Abort;
88868     }
88869   }
88870
88871   /* Process NATURAL keywords, and ON and USING clauses of joins.
88872   */
88873   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
88874     return WRC_Abort;
88875   }
88876
88877   /* For every "*" that occurs in the column list, insert the names of
88878   ** all columns in all tables.  And for every TABLE.* insert the names
88879   ** of all columns in TABLE.  The parser inserted a special expression
88880   ** with the TK_ALL operator for each "*" that it found in the column list.
88881   ** The following code just has to locate the TK_ALL expressions and expand
88882   ** each one to the list of all columns in all tables.
88883   **
88884   ** The first loop just checks to see if there are any "*" operators
88885   ** that need expanding.
88886   */
88887   for(k=0; k<pEList->nExpr; k++){
88888     Expr *pE = pEList->a[k].pExpr;
88889     if( pE->op==TK_ALL ) break;
88890     assert( pE->op!=TK_DOT || pE->pRight!=0 );
88891     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
88892     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
88893   }
88894   if( k<pEList->nExpr ){
88895     /*
88896     ** If we get here it means the result set contains one or more "*"
88897     ** operators that need to be expanded.  Loop through each expression
88898     ** in the result set and expand them one by one.
88899     */
88900     struct ExprList_item *a = pEList->a;
88901     ExprList *pNew = 0;
88902     int flags = pParse->db->flags;
88903     int longNames = (flags & SQLITE_FullColNames)!=0
88904                       && (flags & SQLITE_ShortColNames)==0;
88905
88906     for(k=0; k<pEList->nExpr; k++){
88907       Expr *pE = a[k].pExpr;
88908       assert( pE->op!=TK_DOT || pE->pRight!=0 );
88909       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
88910         /* This particular expression does not need to be expanded.
88911         */
88912         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
88913         if( pNew ){
88914           pNew->a[pNew->nExpr-1].zName = a[k].zName;
88915           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
88916           a[k].zName = 0;
88917           a[k].zSpan = 0;
88918         }
88919         a[k].pExpr = 0;
88920       }else{
88921         /* This expression is a "*" or a "TABLE.*" and needs to be
88922         ** expanded. */
88923         int tableSeen = 0;      /* Set to 1 when TABLE matches */
88924         char *zTName;            /* text of name of TABLE */
88925         if( pE->op==TK_DOT ){
88926           assert( pE->pLeft!=0 );
88927           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
88928           zTName = pE->pLeft->u.zToken;
88929         }else{
88930           zTName = 0;
88931         }
88932         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88933           Table *pTab = pFrom->pTab;
88934           char *zTabName = pFrom->zAlias;
88935           if( zTabName==0 ){
88936             zTabName = pTab->zName;
88937           }
88938           if( db->mallocFailed ) break;
88939           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
88940             continue;
88941           }
88942           tableSeen = 1;
88943           for(j=0; j<pTab->nCol; j++){
88944             Expr *pExpr, *pRight;
88945             char *zName = pTab->aCol[j].zName;
88946             char *zColname;  /* The computed column name */
88947             char *zToFree;   /* Malloced string that needs to be freed */
88948             Token sColname;  /* Computed column name as a token */
88949
88950             /* If a column is marked as 'hidden' (currently only possible
88951             ** for virtual tables), do not include it in the expanded
88952             ** result-set list.
88953             */
88954             if( IsHiddenColumn(&pTab->aCol[j]) ){
88955               assert(IsVirtual(pTab));
88956               continue;
88957             }
88958
88959             if( i>0 && zTName==0 ){
88960               if( (pFrom->jointype & JT_NATURAL)!=0
88961                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
88962               ){
88963                 /* In a NATURAL join, omit the join columns from the 
88964                 ** table to the right of the join */
88965                 continue;
88966               }
88967               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
88968                 /* In a join with a USING clause, omit columns in the
88969                 ** using clause from the table on the right. */
88970                 continue;
88971               }
88972             }
88973             pRight = sqlite3Expr(db, TK_ID, zName);
88974             zColname = zName;
88975             zToFree = 0;
88976             if( longNames || pTabList->nSrc>1 ){
88977               Expr *pLeft;
88978               pLeft = sqlite3Expr(db, TK_ID, zTabName);
88979               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
88980               if( longNames ){
88981                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
88982                 zToFree = zColname;
88983               }
88984             }else{
88985               pExpr = pRight;
88986             }
88987             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
88988             sColname.z = zColname;
88989             sColname.n = sqlite3Strlen30(zColname);
88990             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
88991             sqlite3DbFree(db, zToFree);
88992           }
88993         }
88994         if( !tableSeen ){
88995           if( zTName ){
88996             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
88997           }else{
88998             sqlite3ErrorMsg(pParse, "no tables specified");
88999           }
89000         }
89001       }
89002     }
89003     sqlite3ExprListDelete(db, pEList);
89004     p->pEList = pNew;
89005   }
89006 #if SQLITE_MAX_COLUMN
89007   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89008     sqlite3ErrorMsg(pParse, "too many columns in result set");
89009   }
89010 #endif
89011   return WRC_Continue;
89012 }
89013
89014 /*
89015 ** No-op routine for the parse-tree walker.
89016 **
89017 ** When this routine is the Walker.xExprCallback then expression trees
89018 ** are walked without any actions being taken at each node.  Presumably,
89019 ** when this routine is used for Walker.xExprCallback then 
89020 ** Walker.xSelectCallback is set to do something useful for every 
89021 ** subquery in the parser tree.
89022 */
89023 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
89024   UNUSED_PARAMETER2(NotUsed, NotUsed2);
89025   return WRC_Continue;
89026 }
89027
89028 /*
89029 ** This routine "expands" a SELECT statement and all of its subqueries.
89030 ** For additional information on what it means to "expand" a SELECT
89031 ** statement, see the comment on the selectExpand worker callback above.
89032 **
89033 ** Expanding a SELECT statement is the first step in processing a
89034 ** SELECT statement.  The SELECT statement must be expanded before
89035 ** name resolution is performed.
89036 **
89037 ** If anything goes wrong, an error message is written into pParse.
89038 ** The calling function can detect the problem by looking at pParse->nErr
89039 ** and/or pParse->db->mallocFailed.
89040 */
89041 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
89042   Walker w;
89043   w.xSelectCallback = selectExpander;
89044   w.xExprCallback = exprWalkNoop;
89045   w.pParse = pParse;
89046   sqlite3WalkSelect(&w, pSelect);
89047 }
89048
89049
89050 #ifndef SQLITE_OMIT_SUBQUERY
89051 /*
89052 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
89053 ** interface.
89054 **
89055 ** For each FROM-clause subquery, add Column.zType and Column.zColl
89056 ** information to the Table structure that represents the result set
89057 ** of that subquery.
89058 **
89059 ** The Table structure that represents the result set was constructed
89060 ** by selectExpander() but the type and collation information was omitted
89061 ** at that point because identifiers had not yet been resolved.  This
89062 ** routine is called after identifier resolution.
89063 */
89064 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
89065   Parse *pParse;
89066   int i;
89067   SrcList *pTabList;
89068   struct SrcList_item *pFrom;
89069
89070   assert( p->selFlags & SF_Resolved );
89071   if( (p->selFlags & SF_HasTypeInfo)==0 ){
89072     p->selFlags |= SF_HasTypeInfo;
89073     pParse = pWalker->pParse;
89074     pTabList = p->pSrc;
89075     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
89076       Table *pTab = pFrom->pTab;
89077       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
89078         /* A sub-query in the FROM clause of a SELECT */
89079         Select *pSel = pFrom->pSelect;
89080         assert( pSel );
89081         while( pSel->pPrior ) pSel = pSel->pPrior;
89082         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
89083       }
89084     }
89085   }
89086   return WRC_Continue;
89087 }
89088 #endif
89089
89090
89091 /*
89092 ** This routine adds datatype and collating sequence information to
89093 ** the Table structures of all FROM-clause subqueries in a
89094 ** SELECT statement.
89095 **
89096 ** Use this routine after name resolution.
89097 */
89098 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
89099 #ifndef SQLITE_OMIT_SUBQUERY
89100   Walker w;
89101   w.xSelectCallback = selectAddSubqueryTypeInfo;
89102   w.xExprCallback = exprWalkNoop;
89103   w.pParse = pParse;
89104   sqlite3WalkSelect(&w, pSelect);
89105 #endif
89106 }
89107
89108
89109 /*
89110 ** This routine sets of a SELECT statement for processing.  The
89111 ** following is accomplished:
89112 **
89113 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
89114 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
89115 **     *  ON and USING clauses are shifted into WHERE statements
89116 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
89117 **     *  Identifiers in expression are matched to tables.
89118 **
89119 ** This routine acts recursively on all subqueries within the SELECT.
89120 */
89121 SQLITE_PRIVATE void sqlite3SelectPrep(
89122   Parse *pParse,         /* The parser context */
89123   Select *p,             /* The SELECT statement being coded. */
89124   NameContext *pOuterNC  /* Name context for container */
89125 ){
89126   sqlite3 *db;
89127   if( NEVER(p==0) ) return;
89128   db = pParse->db;
89129   if( p->selFlags & SF_HasTypeInfo ) return;
89130   sqlite3SelectExpand(pParse, p);
89131   if( pParse->nErr || db->mallocFailed ) return;
89132   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
89133   if( pParse->nErr || db->mallocFailed ) return;
89134   sqlite3SelectAddTypeInfo(pParse, p);
89135 }
89136
89137 /*
89138 ** Reset the aggregate accumulator.
89139 **
89140 ** The aggregate accumulator is a set of memory cells that hold
89141 ** intermediate results while calculating an aggregate.  This
89142 ** routine simply stores NULLs in all of those memory cells.
89143 */
89144 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
89145   Vdbe *v = pParse->pVdbe;
89146   int i;
89147   struct AggInfo_func *pFunc;
89148   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
89149     return;
89150   }
89151   for(i=0; i<pAggInfo->nColumn; i++){
89152     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
89153   }
89154   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
89155     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
89156     if( pFunc->iDistinct>=0 ){
89157       Expr *pE = pFunc->pExpr;
89158       assert( !ExprHasProperty(pE, EP_xIsSelect) );
89159       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
89160         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
89161            "argument");
89162         pFunc->iDistinct = -1;
89163       }else{
89164         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
89165         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
89166                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89167       }
89168     }
89169   }
89170 }
89171
89172 /*
89173 ** Invoke the OP_AggFinalize opcode for every aggregate function
89174 ** in the AggInfo structure.
89175 */
89176 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
89177   Vdbe *v = pParse->pVdbe;
89178   int i;
89179   struct AggInfo_func *pF;
89180   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
89181     ExprList *pList = pF->pExpr->x.pList;
89182     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
89183     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
89184                       (void*)pF->pFunc, P4_FUNCDEF);
89185   }
89186 }
89187
89188 /*
89189 ** Update the accumulator memory cells for an aggregate based on
89190 ** the current cursor position.
89191 */
89192 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
89193   Vdbe *v = pParse->pVdbe;
89194   int i;
89195   struct AggInfo_func *pF;
89196   struct AggInfo_col *pC;
89197
89198   pAggInfo->directMode = 1;
89199   sqlite3ExprCacheClear(pParse);
89200   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
89201     int nArg;
89202     int addrNext = 0;
89203     int regAgg;
89204     ExprList *pList = pF->pExpr->x.pList;
89205     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
89206     if( pList ){
89207       nArg = pList->nExpr;
89208       regAgg = sqlite3GetTempRange(pParse, nArg);
89209       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
89210     }else{
89211       nArg = 0;
89212       regAgg = 0;
89213     }
89214     if( pF->iDistinct>=0 ){
89215       addrNext = sqlite3VdbeMakeLabel(v);
89216       assert( nArg==1 );
89217       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
89218     }
89219     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
89220       CollSeq *pColl = 0;
89221       struct ExprList_item *pItem;
89222       int j;
89223       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
89224       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
89225         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
89226       }
89227       if( !pColl ){
89228         pColl = pParse->db->pDfltColl;
89229       }
89230       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
89231     }
89232     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
89233                       (void*)pF->pFunc, P4_FUNCDEF);
89234     sqlite3VdbeChangeP5(v, (u8)nArg);
89235     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
89236     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
89237     if( addrNext ){
89238       sqlite3VdbeResolveLabel(v, addrNext);
89239       sqlite3ExprCacheClear(pParse);
89240     }
89241   }
89242
89243   /* Before populating the accumulator registers, clear the column cache.
89244   ** Otherwise, if any of the required column values are already present 
89245   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
89246   ** to pC->iMem. But by the time the value is used, the original register
89247   ** may have been used, invalidating the underlying buffer holding the
89248   ** text or blob value. See ticket [883034dcb5].
89249   **
89250   ** Another solution would be to change the OP_SCopy used to copy cached
89251   ** values to an OP_Copy.
89252   */
89253   sqlite3ExprCacheClear(pParse);
89254   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
89255     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
89256   }
89257   pAggInfo->directMode = 0;
89258   sqlite3ExprCacheClear(pParse);
89259 }
89260
89261 /*
89262 ** Generate code for the SELECT statement given in the p argument.  
89263 **
89264 ** The results are distributed in various ways depending on the
89265 ** contents of the SelectDest structure pointed to by argument pDest
89266 ** as follows:
89267 **
89268 **     pDest->eDest    Result
89269 **     ------------    -------------------------------------------
89270 **     SRT_Output      Generate a row of output (using the OP_ResultRow
89271 **                     opcode) for each row in the result set.
89272 **
89273 **     SRT_Mem         Only valid if the result is a single column.
89274 **                     Store the first column of the first result row
89275 **                     in register pDest->iParm then abandon the rest
89276 **                     of the query.  This destination implies "LIMIT 1".
89277 **
89278 **     SRT_Set         The result must be a single column.  Store each
89279 **                     row of result as the key in table pDest->iParm. 
89280 **                     Apply the affinity pDest->affinity before storing
89281 **                     results.  Used to implement "IN (SELECT ...)".
89282 **
89283 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
89284 **
89285 **     SRT_Except      Remove results from the temporary table pDest->iParm.
89286 **
89287 **     SRT_Table       Store results in temporary table pDest->iParm.
89288 **                     This is like SRT_EphemTab except that the table
89289 **                     is assumed to already be open.
89290 **
89291 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
89292 **                     the result there. The cursor is left open after
89293 **                     returning.  This is like SRT_Table except that
89294 **                     this destination uses OP_OpenEphemeral to create
89295 **                     the table first.
89296 **
89297 **     SRT_Coroutine   Generate a co-routine that returns a new row of
89298 **                     results each time it is invoked.  The entry point
89299 **                     of the co-routine is stored in register pDest->iParm.
89300 **
89301 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
89302 **                     set is not empty.
89303 **
89304 **     SRT_Discard     Throw the results away.  This is used by SELECT
89305 **                     statements within triggers whose only purpose is
89306 **                     the side-effects of functions.
89307 **
89308 ** This routine returns the number of errors.  If any errors are
89309 ** encountered, then an appropriate error message is left in
89310 ** pParse->zErrMsg.
89311 **
89312 ** This routine does NOT free the Select structure passed in.  The
89313 ** calling function needs to do that.
89314 */
89315 SQLITE_PRIVATE int sqlite3Select(
89316   Parse *pParse,         /* The parser context */
89317   Select *p,             /* The SELECT statement being coded. */
89318   SelectDest *pDest      /* What to do with the query results */
89319 ){
89320   int i, j;              /* Loop counters */
89321   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
89322   Vdbe *v;               /* The virtual machine under construction */
89323   int isAgg;             /* True for select lists like "count(*)" */
89324   ExprList *pEList;      /* List of columns to extract. */
89325   SrcList *pTabList;     /* List of tables to select from */
89326   Expr *pWhere;          /* The WHERE clause.  May be NULL */
89327   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
89328   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
89329   Expr *pHaving;         /* The HAVING clause.  May be NULL */
89330   int isDistinct;        /* True if the DISTINCT keyword is present */
89331   int distinct;          /* Table to use for the distinct set */
89332   int rc = 1;            /* Value to return from this function */
89333   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
89334   AggInfo sAggInfo;      /* Information used by aggregate queries */
89335   int iEnd;              /* Address of the end of the query */
89336   sqlite3 *db;           /* The database connection */
89337
89338   db = pParse->db;
89339   if( p==0 || db->mallocFailed || pParse->nErr ){
89340     return 1;
89341   }
89342   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
89343   memset(&sAggInfo, 0, sizeof(sAggInfo));
89344
89345   if( IgnorableOrderby(pDest) ){
89346     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
89347            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
89348     /* If ORDER BY makes no difference in the output then neither does
89349     ** DISTINCT so it can be removed too. */
89350     sqlite3ExprListDelete(db, p->pOrderBy);
89351     p->pOrderBy = 0;
89352     p->selFlags &= ~SF_Distinct;
89353   }
89354   sqlite3SelectPrep(pParse, p, 0);
89355   pOrderBy = p->pOrderBy;
89356   pTabList = p->pSrc;
89357   pEList = p->pEList;
89358   if( pParse->nErr || db->mallocFailed ){
89359     goto select_end;
89360   }
89361   isAgg = (p->selFlags & SF_Aggregate)!=0;
89362   assert( pEList!=0 );
89363
89364   /* Begin generating code.
89365   */
89366   v = sqlite3GetVdbe(pParse);
89367   if( v==0 ) goto select_end;
89368
89369   /* Generate code for all sub-queries in the FROM clause
89370   */
89371 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89372   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
89373     struct SrcList_item *pItem = &pTabList->a[i];
89374     SelectDest dest;
89375     Select *pSub = pItem->pSelect;
89376     int isAggSub;
89377
89378     if( pSub==0 || pItem->isPopulated ) continue;
89379
89380     /* Increment Parse.nHeight by the height of the largest expression
89381     ** tree refered to by this, the parent select. The child select
89382     ** may contain expression trees of at most
89383     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
89384     ** more conservative than necessary, but much easier than enforcing
89385     ** an exact limit.
89386     */
89387     pParse->nHeight += sqlite3SelectExprHeight(p);
89388
89389     /* Check to see if the subquery can be absorbed into the parent. */
89390     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
89391     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
89392       if( isAggSub ){
89393         isAgg = 1;
89394         p->selFlags |= SF_Aggregate;
89395       }
89396       i = -1;
89397     }else{
89398       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
89399       assert( pItem->isPopulated==0 );
89400       sqlite3Select(pParse, pSub, &dest);
89401       pItem->isPopulated = 1;
89402     }
89403     if( /*pParse->nErr ||*/ db->mallocFailed ){
89404       goto select_end;
89405     }
89406     pParse->nHeight -= sqlite3SelectExprHeight(p);
89407     pTabList = p->pSrc;
89408     if( !IgnorableOrderby(pDest) ){
89409       pOrderBy = p->pOrderBy;
89410     }
89411   }
89412   pEList = p->pEList;
89413 #endif
89414   pWhere = p->pWhere;
89415   pGroupBy = p->pGroupBy;
89416   pHaving = p->pHaving;
89417   isDistinct = (p->selFlags & SF_Distinct)!=0;
89418
89419 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89420   /* If there is are a sequence of queries, do the earlier ones first.
89421   */
89422   if( p->pPrior ){
89423     if( p->pRightmost==0 ){
89424       Select *pLoop, *pRight = 0;
89425       int cnt = 0;
89426       int mxSelect;
89427       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
89428         pLoop->pRightmost = p;
89429         pLoop->pNext = pRight;
89430         pRight = pLoop;
89431       }
89432       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
89433       if( mxSelect && cnt>mxSelect ){
89434         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
89435         return 1;
89436       }
89437     }
89438     return multiSelect(pParse, p, pDest);
89439   }
89440 #endif
89441
89442   /* If writing to memory or generating a set
89443   ** only a single column may be output.
89444   */
89445 #ifndef SQLITE_OMIT_SUBQUERY
89446   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
89447     goto select_end;
89448   }
89449 #endif
89450
89451   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
89452   ** GROUP BY might use an index, DISTINCT never does.
89453   */
89454   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
89455   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
89456     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
89457     pGroupBy = p->pGroupBy;
89458     p->selFlags &= ~SF_Distinct;
89459     isDistinct = 0;
89460   }
89461
89462   /* If there is both a GROUP BY and an ORDER BY clause and they are
89463   ** identical, then disable the ORDER BY clause since the GROUP BY
89464   ** will cause elements to come out in the correct order.  This is
89465   ** an optimization - the correct answer should result regardless.
89466   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
89467   ** to disable this optimization for testing purposes.
89468   */
89469   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
89470          && (db->flags & SQLITE_GroupByOrder)==0 ){
89471     pOrderBy = 0;
89472   }
89473
89474   /* If there is an ORDER BY clause, then this sorting
89475   ** index might end up being unused if the data can be 
89476   ** extracted in pre-sorted order.  If that is the case, then the
89477   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
89478   ** we figure out that the sorting index is not needed.  The addrSortIndex
89479   ** variable is used to facilitate that change.
89480   */
89481   if( pOrderBy ){
89482     KeyInfo *pKeyInfo;
89483     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
89484     pOrderBy->iECursor = pParse->nTab++;
89485     p->addrOpenEphm[2] = addrSortIndex =
89486       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
89487                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
89488                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89489   }else{
89490     addrSortIndex = -1;
89491   }
89492
89493   /* If the output is destined for a temporary table, open that table.
89494   */
89495   if( pDest->eDest==SRT_EphemTab ){
89496     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
89497   }
89498
89499   /* Set the limiter.
89500   */
89501   iEnd = sqlite3VdbeMakeLabel(v);
89502   computeLimitRegisters(pParse, p, iEnd);
89503
89504   /* Open a virtual index to use for the distinct set.
89505   */
89506   if( isDistinct ){
89507     KeyInfo *pKeyInfo;
89508     assert( isAgg || pGroupBy );
89509     distinct = pParse->nTab++;
89510     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
89511     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
89512                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89513   }else{
89514     distinct = -1;
89515   }
89516
89517   /* Aggregate and non-aggregate queries are handled differently */
89518   if( !isAgg && pGroupBy==0 ){
89519     /* This case is for non-aggregate queries
89520     ** Begin the database scan
89521     */
89522     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
89523     if( pWInfo==0 ) goto select_end;
89524
89525     /* If sorting index that was created by a prior OP_OpenEphemeral 
89526     ** instruction ended up not being needed, then change the OP_OpenEphemeral
89527     ** into an OP_Noop.
89528     */
89529     if( addrSortIndex>=0 && pOrderBy==0 ){
89530       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
89531       p->addrOpenEphm[2] = -1;
89532     }
89533
89534     /* Use the standard inner loop
89535     */
89536     assert(!isDistinct);
89537     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
89538                     pWInfo->iContinue, pWInfo->iBreak);
89539
89540     /* End the database scan loop.
89541     */
89542     sqlite3WhereEnd(pWInfo);
89543   }else{
89544     /* This is the processing for aggregate queries */
89545     NameContext sNC;    /* Name context for processing aggregate information */
89546     int iAMem;          /* First Mem address for storing current GROUP BY */
89547     int iBMem;          /* First Mem address for previous GROUP BY */
89548     int iUseFlag;       /* Mem address holding flag indicating that at least
89549                         ** one row of the input to the aggregator has been
89550                         ** processed */
89551     int iAbortFlag;     /* Mem address which causes query abort if positive */
89552     int groupBySort;    /* Rows come from source in GROUP BY order */
89553     int addrEnd;        /* End of processing for this SELECT */
89554
89555     /* Remove any and all aliases between the result set and the
89556     ** GROUP BY clause.
89557     */
89558     if( pGroupBy ){
89559       int k;                        /* Loop counter */
89560       struct ExprList_item *pItem;  /* For looping over expression in a list */
89561
89562       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
89563         pItem->iAlias = 0;
89564       }
89565       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
89566         pItem->iAlias = 0;
89567       }
89568     }
89569
89570  
89571     /* Create a label to jump to when we want to abort the query */
89572     addrEnd = sqlite3VdbeMakeLabel(v);
89573
89574     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
89575     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
89576     ** SELECT statement.
89577     */
89578     memset(&sNC, 0, sizeof(sNC));
89579     sNC.pParse = pParse;
89580     sNC.pSrcList = pTabList;
89581     sNC.pAggInfo = &sAggInfo;
89582     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
89583     sAggInfo.pGroupBy = pGroupBy;
89584     sqlite3ExprAnalyzeAggList(&sNC, pEList);
89585     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
89586     if( pHaving ){
89587       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
89588     }
89589     sAggInfo.nAccumulator = sAggInfo.nColumn;
89590     for(i=0; i<sAggInfo.nFunc; i++){
89591       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
89592       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
89593     }
89594     if( db->mallocFailed ) goto select_end;
89595
89596     /* Processing for aggregates with GROUP BY is very different and
89597     ** much more complex than aggregates without a GROUP BY.
89598     */
89599     if( pGroupBy ){
89600       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
89601       int j1;             /* A-vs-B comparision jump */
89602       int addrOutputRow;  /* Start of subroutine that outputs a result row */
89603       int regOutputRow;   /* Return address register for output subroutine */
89604       int addrSetAbort;   /* Set the abort flag and return */
89605       int addrTopOfLoop;  /* Top of the input loop */
89606       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
89607       int addrReset;      /* Subroutine for resetting the accumulator */
89608       int regReset;       /* Return address register for reset subroutine */
89609
89610       /* If there is a GROUP BY clause we might need a sorting index to
89611       ** implement it.  Allocate that sorting index now.  If it turns out
89612       ** that we do not need it after all, the OpenEphemeral instruction
89613       ** will be converted into a Noop.  
89614       */
89615       sAggInfo.sortingIdx = pParse->nTab++;
89616       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
89617       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
89618           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
89619           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89620
89621       /* Initialize memory locations used by GROUP BY aggregate processing
89622       */
89623       iUseFlag = ++pParse->nMem;
89624       iAbortFlag = ++pParse->nMem;
89625       regOutputRow = ++pParse->nMem;
89626       addrOutputRow = sqlite3VdbeMakeLabel(v);
89627       regReset = ++pParse->nMem;
89628       addrReset = sqlite3VdbeMakeLabel(v);
89629       iAMem = pParse->nMem + 1;
89630       pParse->nMem += pGroupBy->nExpr;
89631       iBMem = pParse->nMem + 1;
89632       pParse->nMem += pGroupBy->nExpr;
89633       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
89634       VdbeComment((v, "clear abort flag"));
89635       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
89636       VdbeComment((v, "indicate accumulator empty"));
89637
89638       /* Begin a loop that will extract all source rows in GROUP BY order.
89639       ** This might involve two separate loops with an OP_Sort in between, or
89640       ** it might be a single loop that uses an index to extract information
89641       ** in the right order to begin with.
89642       */
89643       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89644       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
89645       if( pWInfo==0 ) goto select_end;
89646       if( pGroupBy==0 ){
89647         /* The optimizer is able to deliver rows in group by order so
89648         ** we do not have to sort.  The OP_OpenEphemeral table will be
89649         ** cancelled later because we still need to use the pKeyInfo
89650         */
89651         pGroupBy = p->pGroupBy;
89652         groupBySort = 0;
89653       }else{
89654         /* Rows are coming out in undetermined order.  We have to push
89655         ** each row into a sorting index, terminate the first loop,
89656         ** then loop over the sorting index in order to get the output
89657         ** in sorted order
89658         */
89659         int regBase;
89660         int regRecord;
89661         int nCol;
89662         int nGroupBy;
89663
89664         groupBySort = 1;
89665         nGroupBy = pGroupBy->nExpr;
89666         nCol = nGroupBy + 1;
89667         j = nGroupBy+1;
89668         for(i=0; i<sAggInfo.nColumn; i++){
89669           if( sAggInfo.aCol[i].iSorterColumn>=j ){
89670             nCol++;
89671             j++;
89672           }
89673         }
89674         regBase = sqlite3GetTempRange(pParse, nCol);
89675         sqlite3ExprCacheClear(pParse);
89676         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
89677         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
89678         j = nGroupBy+1;
89679         for(i=0; i<sAggInfo.nColumn; i++){
89680           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
89681           if( pCol->iSorterColumn>=j ){
89682             int r1 = j + regBase;
89683             int r2;
89684
89685             r2 = sqlite3ExprCodeGetColumn(pParse, 
89686                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
89687             if( r1!=r2 ){
89688               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
89689             }
89690             j++;
89691           }
89692         }
89693         regRecord = sqlite3GetTempReg(pParse);
89694         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
89695         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
89696         sqlite3ReleaseTempReg(pParse, regRecord);
89697         sqlite3ReleaseTempRange(pParse, regBase, nCol);
89698         sqlite3WhereEnd(pWInfo);
89699         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
89700         VdbeComment((v, "GROUP BY sort"));
89701         sAggInfo.useSortingIdx = 1;
89702         sqlite3ExprCacheClear(pParse);
89703       }
89704
89705       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
89706       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
89707       ** Then compare the current GROUP BY terms against the GROUP BY terms
89708       ** from the previous row currently stored in a0, a1, a2...
89709       */
89710       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
89711       sqlite3ExprCacheClear(pParse);
89712       for(j=0; j<pGroupBy->nExpr; j++){
89713         if( groupBySort ){
89714           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
89715         }else{
89716           sAggInfo.directMode = 1;
89717           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
89718         }
89719       }
89720       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
89721                           (char*)pKeyInfo, P4_KEYINFO);
89722       j1 = sqlite3VdbeCurrentAddr(v);
89723       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
89724
89725       /* Generate code that runs whenever the GROUP BY changes.
89726       ** Changes in the GROUP BY are detected by the previous code
89727       ** block.  If there were no changes, this block is skipped.
89728       **
89729       ** This code copies current group by terms in b0,b1,b2,...
89730       ** over to a0,a1,a2.  It then calls the output subroutine
89731       ** and resets the aggregate accumulator registers in preparation
89732       ** for the next GROUP BY batch.
89733       */
89734       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
89735       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89736       VdbeComment((v, "output one row"));
89737       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
89738       VdbeComment((v, "check abort flag"));
89739       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89740       VdbeComment((v, "reset accumulator"));
89741
89742       /* Update the aggregate accumulators based on the content of
89743       ** the current row
89744       */
89745       sqlite3VdbeJumpHere(v, j1);
89746       updateAccumulator(pParse, &sAggInfo);
89747       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
89748       VdbeComment((v, "indicate data in accumulator"));
89749
89750       /* End of the loop
89751       */
89752       if( groupBySort ){
89753         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
89754       }else{
89755         sqlite3WhereEnd(pWInfo);
89756         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
89757       }
89758
89759       /* Output the final row of result
89760       */
89761       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89762       VdbeComment((v, "output final row"));
89763
89764       /* Jump over the subroutines
89765       */
89766       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
89767
89768       /* Generate a subroutine that outputs a single row of the result
89769       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
89770       ** is less than or equal to zero, the subroutine is a no-op.  If
89771       ** the processing calls for the query to abort, this subroutine
89772       ** increments the iAbortFlag memory location before returning in
89773       ** order to signal the caller to abort.
89774       */
89775       addrSetAbort = sqlite3VdbeCurrentAddr(v);
89776       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
89777       VdbeComment((v, "set abort flag"));
89778       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89779       sqlite3VdbeResolveLabel(v, addrOutputRow);
89780       addrOutputRow = sqlite3VdbeCurrentAddr(v);
89781       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
89782       VdbeComment((v, "Groupby result generator entry point"));
89783       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89784       finalizeAggFunctions(pParse, &sAggInfo);
89785       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
89786       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
89787                       distinct, pDest,
89788                       addrOutputRow+1, addrSetAbort);
89789       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89790       VdbeComment((v, "end groupby result generator"));
89791
89792       /* Generate a subroutine that will reset the group-by accumulator
89793       */
89794       sqlite3VdbeResolveLabel(v, addrReset);
89795       resetAccumulator(pParse, &sAggInfo);
89796       sqlite3VdbeAddOp1(v, OP_Return, regReset);
89797      
89798     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
89799     else {
89800       ExprList *pDel = 0;
89801 #ifndef SQLITE_OMIT_BTREECOUNT
89802       Table *pTab;
89803       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
89804         /* If isSimpleCount() returns a pointer to a Table structure, then
89805         ** the SQL statement is of the form:
89806         **
89807         **   SELECT count(*) FROM <tbl>
89808         **
89809         ** where the Table structure returned represents table <tbl>.
89810         **
89811         ** This statement is so common that it is optimized specially. The
89812         ** OP_Count instruction is executed either on the intkey table that
89813         ** contains the data for table <tbl> or on one of its indexes. It
89814         ** is better to execute the op on an index, as indexes are almost
89815         ** always spread across less pages than their corresponding tables.
89816         */
89817         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89818         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
89819         Index *pIdx;                         /* Iterator variable */
89820         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
89821         Index *pBest = 0;                    /* Best index found so far */
89822         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
89823
89824         sqlite3CodeVerifySchema(pParse, iDb);
89825         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
89826
89827         /* Search for the index that has the least amount of columns. If
89828         ** there is such an index, and it has less columns than the table
89829         ** does, then we can assume that it consumes less space on disk and
89830         ** will therefore be cheaper to scan to determine the query result.
89831         ** In this case set iRoot to the root page number of the index b-tree
89832         ** and pKeyInfo to the KeyInfo structure required to navigate the
89833         ** index.
89834         **
89835         ** In practice the KeyInfo structure will not be used. It is only 
89836         ** passed to keep OP_OpenRead happy.
89837         */
89838         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89839           if( !pBest || pIdx->nColumn<pBest->nColumn ){
89840             pBest = pIdx;
89841           }
89842         }
89843         if( pBest && pBest->nColumn<pTab->nCol ){
89844           iRoot = pBest->tnum;
89845           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
89846         }
89847
89848         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
89849         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
89850         if( pKeyInfo ){
89851           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
89852         }
89853         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
89854         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
89855       }else
89856 #endif /* SQLITE_OMIT_BTREECOUNT */
89857       {
89858         /* Check if the query is of one of the following forms:
89859         **
89860         **   SELECT min(x) FROM ...
89861         **   SELECT max(x) FROM ...
89862         **
89863         ** If it is, then ask the code in where.c to attempt to sort results
89864         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
89865         ** If where.c is able to produce results sorted in this order, then
89866         ** add vdbe code to break out of the processing loop after the 
89867         ** first iteration (since the first iteration of the loop is 
89868         ** guaranteed to operate on the row with the minimum or maximum 
89869         ** value of x, the only row required).
89870         **
89871         ** A special flag must be passed to sqlite3WhereBegin() to slightly
89872         ** modify behaviour as follows:
89873         **
89874         **   + If the query is a "SELECT min(x)", then the loop coded by
89875         **     where.c should not iterate over any values with a NULL value
89876         **     for x.
89877         **
89878         **   + The optimizer code in where.c (the thing that decides which
89879         **     index or indices to use) should place a different priority on 
89880         **     satisfying the 'ORDER BY' clause than it does in other cases.
89881         **     Refer to code and comments in where.c for details.
89882         */
89883         ExprList *pMinMax = 0;
89884         u8 flag = minMaxQuery(p);
89885         if( flag ){
89886           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
89887           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
89888           pDel = pMinMax;
89889           if( pMinMax && !db->mallocFailed ){
89890             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
89891             pMinMax->a[0].pExpr->op = TK_COLUMN;
89892           }
89893         }
89894   
89895         /* This case runs if the aggregate has no GROUP BY clause.  The
89896         ** processing is much simpler since there is only a single row
89897         ** of output.
89898         */
89899         resetAccumulator(pParse, &sAggInfo);
89900         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
89901         if( pWInfo==0 ){
89902           sqlite3ExprListDelete(db, pDel);
89903           goto select_end;
89904         }
89905         updateAccumulator(pParse, &sAggInfo);
89906         if( !pMinMax && flag ){
89907           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
89908           VdbeComment((v, "%s() by index",
89909                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
89910         }
89911         sqlite3WhereEnd(pWInfo);
89912         finalizeAggFunctions(pParse, &sAggInfo);
89913       }
89914
89915       pOrderBy = 0;
89916       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
89917       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
89918                       pDest, addrEnd, addrEnd);
89919       sqlite3ExprListDelete(db, pDel);
89920     }
89921     sqlite3VdbeResolveLabel(v, addrEnd);
89922     
89923   } /* endif aggregate query */
89924
89925   /* If there is an ORDER BY clause, then we need to sort the results
89926   ** and send them to the callback one by one.
89927   */
89928   if( pOrderBy ){
89929     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
89930   }
89931
89932   /* Jump here to skip this query
89933   */
89934   sqlite3VdbeResolveLabel(v, iEnd);
89935
89936   /* The SELECT was successfully coded.   Set the return code to 0
89937   ** to indicate no errors.
89938   */
89939   rc = 0;
89940
89941   /* Control jumps to here if an error is encountered above, or upon
89942   ** successful coding of the SELECT.
89943   */
89944 select_end:
89945
89946   /* Identify column names if results of the SELECT are to be output.
89947   */
89948   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
89949     generateColumnNames(pParse, pTabList, pEList);
89950   }
89951
89952   sqlite3DbFree(db, sAggInfo.aCol);
89953   sqlite3DbFree(db, sAggInfo.aFunc);
89954   return rc;
89955 }
89956
89957 #if defined(SQLITE_DEBUG)
89958 /*
89959 *******************************************************************************
89960 ** The following code is used for testing and debugging only.  The code
89961 ** that follows does not appear in normal builds.
89962 **
89963 ** These routines are used to print out the content of all or part of a 
89964 ** parse structures such as Select or Expr.  Such printouts are useful
89965 ** for helping to understand what is happening inside the code generator
89966 ** during the execution of complex SELECT statements.
89967 **
89968 ** These routine are not called anywhere from within the normal
89969 ** code base.  Then are intended to be called from within the debugger
89970 ** or from temporary "printf" statements inserted for debugging.
89971 */
89972 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
89973   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89974     sqlite3DebugPrintf("(%s", p->u.zToken);
89975   }else{
89976     sqlite3DebugPrintf("(%d", p->op);
89977   }
89978   if( p->pLeft ){
89979     sqlite3DebugPrintf(" ");
89980     sqlite3PrintExpr(p->pLeft);
89981   }
89982   if( p->pRight ){
89983     sqlite3DebugPrintf(" ");
89984     sqlite3PrintExpr(p->pRight);
89985   }
89986   sqlite3DebugPrintf(")");
89987 }
89988 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
89989   int i;
89990   for(i=0; i<pList->nExpr; i++){
89991     sqlite3PrintExpr(pList->a[i].pExpr);
89992     if( i<pList->nExpr-1 ){
89993       sqlite3DebugPrintf(", ");
89994     }
89995   }
89996 }
89997 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
89998   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
89999   sqlite3PrintExprList(p->pEList);
90000   sqlite3DebugPrintf("\n");
90001   if( p->pSrc ){
90002     char *zPrefix;
90003     int i;
90004     zPrefix = "FROM";
90005     for(i=0; i<p->pSrc->nSrc; i++){
90006       struct SrcList_item *pItem = &p->pSrc->a[i];
90007       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
90008       zPrefix = "";
90009       if( pItem->pSelect ){
90010         sqlite3DebugPrintf("(\n");
90011         sqlite3PrintSelect(pItem->pSelect, indent+10);
90012         sqlite3DebugPrintf("%*s)", indent+8, "");
90013       }else if( pItem->zName ){
90014         sqlite3DebugPrintf("%s", pItem->zName);
90015       }
90016       if( pItem->pTab ){
90017         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
90018       }
90019       if( pItem->zAlias ){
90020         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
90021       }
90022       if( i<p->pSrc->nSrc-1 ){
90023         sqlite3DebugPrintf(",");
90024       }
90025       sqlite3DebugPrintf("\n");
90026     }
90027   }
90028   if( p->pWhere ){
90029     sqlite3DebugPrintf("%*s WHERE ", indent, "");
90030     sqlite3PrintExpr(p->pWhere);
90031     sqlite3DebugPrintf("\n");
90032   }
90033   if( p->pGroupBy ){
90034     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
90035     sqlite3PrintExprList(p->pGroupBy);
90036     sqlite3DebugPrintf("\n");
90037   }
90038   if( p->pHaving ){
90039     sqlite3DebugPrintf("%*s HAVING ", indent, "");
90040     sqlite3PrintExpr(p->pHaving);
90041     sqlite3DebugPrintf("\n");
90042   }
90043   if( p->pOrderBy ){
90044     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
90045     sqlite3PrintExprList(p->pOrderBy);
90046     sqlite3DebugPrintf("\n");
90047   }
90048 }
90049 /* End of the structure debug printing code
90050 *****************************************************************************/
90051 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
90052
90053 /************** End of select.c **********************************************/
90054 /************** Begin file table.c *******************************************/
90055 /*
90056 ** 2001 September 15
90057 **
90058 ** The author disclaims copyright to this source code.  In place of
90059 ** a legal notice, here is a blessing:
90060 **
90061 **    May you do good and not evil.
90062 **    May you find forgiveness for yourself and forgive others.
90063 **    May you share freely, never taking more than you give.
90064 **
90065 *************************************************************************
90066 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
90067 ** interface routines.  These are just wrappers around the main
90068 ** interface routine of sqlite3_exec().
90069 **
90070 ** These routines are in a separate files so that they will not be linked
90071 ** if they are not used.
90072 */
90073
90074 #ifndef SQLITE_OMIT_GET_TABLE
90075
90076 /*
90077 ** This structure is used to pass data from sqlite3_get_table() through
90078 ** to the callback function is uses to build the result.
90079 */
90080 typedef struct TabResult {
90081   char **azResult;   /* Accumulated output */
90082   char *zErrMsg;     /* Error message text, if an error occurs */
90083   int nAlloc;        /* Slots allocated for azResult[] */
90084   int nRow;          /* Number of rows in the result */
90085   int nColumn;       /* Number of columns in the result */
90086   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
90087   int rc;            /* Return code from sqlite3_exec() */
90088 } TabResult;
90089
90090 /*
90091 ** This routine is called once for each row in the result table.  Its job
90092 ** is to fill in the TabResult structure appropriately, allocating new
90093 ** memory as necessary.
90094 */
90095 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
90096   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
90097   int need;                         /* Slots needed in p->azResult[] */
90098   int i;                            /* Loop counter */
90099   char *z;                          /* A single column of result */
90100
90101   /* Make sure there is enough space in p->azResult to hold everything
90102   ** we need to remember from this invocation of the callback.
90103   */
90104   if( p->nRow==0 && argv!=0 ){
90105     need = nCol*2;
90106   }else{
90107     need = nCol;
90108   }
90109   if( p->nData + need > p->nAlloc ){
90110     char **azNew;
90111     p->nAlloc = p->nAlloc*2 + need;
90112     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
90113     if( azNew==0 ) goto malloc_failed;
90114     p->azResult = azNew;
90115   }
90116
90117   /* If this is the first row, then generate an extra row containing
90118   ** the names of all columns.
90119   */
90120   if( p->nRow==0 ){
90121     p->nColumn = nCol;
90122     for(i=0; i<nCol; i++){
90123       z = sqlite3_mprintf("%s", colv[i]);
90124       if( z==0 ) goto malloc_failed;
90125       p->azResult[p->nData++] = z;
90126     }
90127   }else if( p->nColumn!=nCol ){
90128     sqlite3_free(p->zErrMsg);
90129     p->zErrMsg = sqlite3_mprintf(
90130        "sqlite3_get_table() called with two or more incompatible queries"
90131     );
90132     p->rc = SQLITE_ERROR;
90133     return 1;
90134   }
90135
90136   /* Copy over the row data
90137   */
90138   if( argv!=0 ){
90139     for(i=0; i<nCol; i++){
90140       if( argv[i]==0 ){
90141         z = 0;
90142       }else{
90143         int n = sqlite3Strlen30(argv[i])+1;
90144         z = sqlite3_malloc( n );
90145         if( z==0 ) goto malloc_failed;
90146         memcpy(z, argv[i], n);
90147       }
90148       p->azResult[p->nData++] = z;
90149     }
90150     p->nRow++;
90151   }
90152   return 0;
90153
90154 malloc_failed:
90155   p->rc = SQLITE_NOMEM;
90156   return 1;
90157 }
90158
90159 /*
90160 ** Query the database.  But instead of invoking a callback for each row,
90161 ** malloc() for space to hold the result and return the entire results
90162 ** at the conclusion of the call.
90163 **
90164 ** The result that is written to ***pazResult is held in memory obtained
90165 ** from malloc().  But the caller cannot free this memory directly.  
90166 ** Instead, the entire table should be passed to sqlite3_free_table() when
90167 ** the calling procedure is finished using it.
90168 */
90169 SQLITE_API int sqlite3_get_table(
90170   sqlite3 *db,                /* The database on which the SQL executes */
90171   const char *zSql,           /* The SQL to be executed */
90172   char ***pazResult,          /* Write the result table here */
90173   int *pnRow,                 /* Write the number of rows in the result here */
90174   int *pnColumn,              /* Write the number of columns of result here */
90175   char **pzErrMsg             /* Write error messages here */
90176 ){
90177   int rc;
90178   TabResult res;
90179
90180   *pazResult = 0;
90181   if( pnColumn ) *pnColumn = 0;
90182   if( pnRow ) *pnRow = 0;
90183   if( pzErrMsg ) *pzErrMsg = 0;
90184   res.zErrMsg = 0;
90185   res.nRow = 0;
90186   res.nColumn = 0;
90187   res.nData = 1;
90188   res.nAlloc = 20;
90189   res.rc = SQLITE_OK;
90190   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
90191   if( res.azResult==0 ){
90192      db->errCode = SQLITE_NOMEM;
90193      return SQLITE_NOMEM;
90194   }
90195   res.azResult[0] = 0;
90196   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
90197   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
90198   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
90199   if( (rc&0xff)==SQLITE_ABORT ){
90200     sqlite3_free_table(&res.azResult[1]);
90201     if( res.zErrMsg ){
90202       if( pzErrMsg ){
90203         sqlite3_free(*pzErrMsg);
90204         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
90205       }
90206       sqlite3_free(res.zErrMsg);
90207     }
90208     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
90209     return res.rc;
90210   }
90211   sqlite3_free(res.zErrMsg);
90212   if( rc!=SQLITE_OK ){
90213     sqlite3_free_table(&res.azResult[1]);
90214     return rc;
90215   }
90216   if( res.nAlloc>res.nData ){
90217     char **azNew;
90218     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
90219     if( azNew==0 ){
90220       sqlite3_free_table(&res.azResult[1]);
90221       db->errCode = SQLITE_NOMEM;
90222       return SQLITE_NOMEM;
90223     }
90224     res.azResult = azNew;
90225   }
90226   *pazResult = &res.azResult[1];
90227   if( pnColumn ) *pnColumn = res.nColumn;
90228   if( pnRow ) *pnRow = res.nRow;
90229   return rc;
90230 }
90231
90232 /*
90233 ** This routine frees the space the sqlite3_get_table() malloced.
90234 */
90235 SQLITE_API void sqlite3_free_table(
90236   char **azResult            /* Result returned from from sqlite3_get_table() */
90237 ){
90238   if( azResult ){
90239     int i, n;
90240     azResult--;
90241     assert( azResult!=0 );
90242     n = SQLITE_PTR_TO_INT(azResult[0]);
90243     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
90244     sqlite3_free(azResult);
90245   }
90246 }
90247
90248 #endif /* SQLITE_OMIT_GET_TABLE */
90249
90250 /************** End of table.c ***********************************************/
90251 /************** Begin file trigger.c *****************************************/
90252 /*
90253 **
90254 ** The author disclaims copyright to this source code.  In place of
90255 ** a legal notice, here is a blessing:
90256 **
90257 **    May you do good and not evil.
90258 **    May you find forgiveness for yourself and forgive others.
90259 **    May you share freely, never taking more than you give.
90260 **
90261 *************************************************************************
90262 ** This file contains the implementation for TRIGGERs
90263 */
90264
90265 #ifndef SQLITE_OMIT_TRIGGER
90266 /*
90267 ** Delete a linked list of TriggerStep structures.
90268 */
90269 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
90270   while( pTriggerStep ){
90271     TriggerStep * pTmp = pTriggerStep;
90272     pTriggerStep = pTriggerStep->pNext;
90273
90274     sqlite3ExprDelete(db, pTmp->pWhere);
90275     sqlite3ExprListDelete(db, pTmp->pExprList);
90276     sqlite3SelectDelete(db, pTmp->pSelect);
90277     sqlite3IdListDelete(db, pTmp->pIdList);
90278
90279     sqlite3DbFree(db, pTmp);
90280   }
90281 }
90282
90283 /*
90284 ** Given table pTab, return a list of all the triggers attached to 
90285 ** the table. The list is connected by Trigger.pNext pointers.
90286 **
90287 ** All of the triggers on pTab that are in the same database as pTab
90288 ** are already attached to pTab->pTrigger.  But there might be additional
90289 ** triggers on pTab in the TEMP schema.  This routine prepends all
90290 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
90291 ** and returns the combined list.
90292 **
90293 ** To state it another way:  This routine returns a list of all triggers
90294 ** that fire off of pTab.  The list will include any TEMP triggers on
90295 ** pTab as well as the triggers lised in pTab->pTrigger.
90296 */
90297 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
90298   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
90299   Trigger *pList = 0;                  /* List of triggers to return */
90300
90301   if( pParse->disableTriggers ){
90302     return 0;
90303   }
90304
90305   if( pTmpSchema!=pTab->pSchema ){
90306     HashElem *p;
90307     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
90308       Trigger *pTrig = (Trigger *)sqliteHashData(p);
90309       if( pTrig->pTabSchema==pTab->pSchema
90310        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
90311       ){
90312         pTrig->pNext = (pList ? pList : pTab->pTrigger);
90313         pList = pTrig;
90314       }
90315     }
90316   }
90317
90318   return (pList ? pList : pTab->pTrigger);
90319 }
90320
90321 /*
90322 ** This is called by the parser when it sees a CREATE TRIGGER statement
90323 ** up to the point of the BEGIN before the trigger actions.  A Trigger
90324 ** structure is generated based on the information available and stored
90325 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
90326 ** sqlite3FinishTrigger() function is called to complete the trigger
90327 ** construction process.
90328 */
90329 SQLITE_PRIVATE void sqlite3BeginTrigger(
90330   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
90331   Token *pName1,      /* The name of the trigger */
90332   Token *pName2,      /* The name of the trigger */
90333   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
90334   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
90335   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
90336   SrcList *pTableName,/* The name of the table/view the trigger applies to */
90337   Expr *pWhen,        /* WHEN clause */
90338   int isTemp,         /* True if the TEMPORARY keyword is present */
90339   int noErr           /* Suppress errors if the trigger already exists */
90340 ){
90341   Trigger *pTrigger = 0;  /* The new trigger */
90342   Table *pTab;            /* Table that the trigger fires off of */
90343   char *zName = 0;        /* Name of the trigger */
90344   sqlite3 *db = pParse->db;  /* The database connection */
90345   int iDb;                /* The database to store the trigger in */
90346   Token *pName;           /* The unqualified db name */
90347   DbFixer sFix;           /* State vector for the DB fixer */
90348   int iTabDb;             /* Index of the database holding pTab */
90349
90350   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
90351   assert( pName2!=0 );
90352   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
90353   assert( op>0 && op<0xff );
90354   if( isTemp ){
90355     /* If TEMP was specified, then the trigger name may not be qualified. */
90356     if( pName2->n>0 ){
90357       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
90358       goto trigger_cleanup;
90359     }
90360     iDb = 1;
90361     pName = pName1;
90362   }else{
90363     /* Figure out the db that the the trigger will be created in */
90364     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90365     if( iDb<0 ){
90366       goto trigger_cleanup;
90367     }
90368   }
90369
90370   /* If the trigger name was unqualified, and the table is a temp table,
90371   ** then set iDb to 1 to create the trigger in the temporary database.
90372   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
90373   ** exist, the error is caught by the block below.
90374   */
90375   if( !pTableName || db->mallocFailed ){
90376     goto trigger_cleanup;
90377   }
90378   pTab = sqlite3SrcListLookup(pParse, pTableName);
90379   if( db->init.busy==0 && pName2->n==0 && pTab
90380         && pTab->pSchema==db->aDb[1].pSchema ){
90381     iDb = 1;
90382   }
90383
90384   /* Ensure the table name matches database name and that the table exists */
90385   if( db->mallocFailed ) goto trigger_cleanup;
90386   assert( pTableName->nSrc==1 );
90387   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
90388       sqlite3FixSrcList(&sFix, pTableName) ){
90389     goto trigger_cleanup;
90390   }
90391   pTab = sqlite3SrcListLookup(pParse, pTableName);
90392   if( !pTab ){
90393     /* The table does not exist. */
90394     if( db->init.iDb==1 ){
90395       /* Ticket #3810.
90396       ** Normally, whenever a table is dropped, all associated triggers are
90397       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
90398       ** and the table is dropped by a different database connection, the
90399       ** trigger is not visible to the database connection that does the
90400       ** drop so the trigger cannot be dropped.  This results in an
90401       ** "orphaned trigger" - a trigger whose associated table is missing.
90402       */
90403       db->init.orphanTrigger = 1;
90404     }
90405     goto trigger_cleanup;
90406   }
90407   if( IsVirtual(pTab) ){
90408     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
90409     goto trigger_cleanup;
90410   }
90411
90412   /* Check that the trigger name is not reserved and that no trigger of the
90413   ** specified name exists */
90414   zName = sqlite3NameFromToken(db, pName);
90415   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
90416     goto trigger_cleanup;
90417   }
90418   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
90419                       zName, sqlite3Strlen30(zName)) ){
90420     if( !noErr ){
90421       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
90422     }
90423     goto trigger_cleanup;
90424   }
90425
90426   /* Do not create a trigger on a system table */
90427   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
90428     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
90429     pParse->nErr++;
90430     goto trigger_cleanup;
90431   }
90432
90433   /* INSTEAD of triggers are only for views and views only support INSTEAD
90434   ** of triggers.
90435   */
90436   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
90437     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
90438         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
90439     goto trigger_cleanup;
90440   }
90441   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
90442     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
90443         " trigger on table: %S", pTableName, 0);
90444     goto trigger_cleanup;
90445   }
90446   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90447
90448 #ifndef SQLITE_OMIT_AUTHORIZATION
90449   {
90450     int code = SQLITE_CREATE_TRIGGER;
90451     const char *zDb = db->aDb[iTabDb].zName;
90452     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
90453     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
90454     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
90455       goto trigger_cleanup;
90456     }
90457     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
90458       goto trigger_cleanup;
90459     }
90460   }
90461 #endif
90462
90463   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
90464   ** cannot appear on views.  So we might as well translate every
90465   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
90466   ** elsewhere.
90467   */
90468   if (tr_tm == TK_INSTEAD){
90469     tr_tm = TK_BEFORE;
90470   }
90471
90472   /* Build the Trigger object */
90473   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
90474   if( pTrigger==0 ) goto trigger_cleanup;
90475   pTrigger->zName = zName;
90476   zName = 0;
90477   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
90478   pTrigger->pSchema = db->aDb[iDb].pSchema;
90479   pTrigger->pTabSchema = pTab->pSchema;
90480   pTrigger->op = (u8)op;
90481   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
90482   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90483   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
90484   assert( pParse->pNewTrigger==0 );
90485   pParse->pNewTrigger = pTrigger;
90486
90487 trigger_cleanup:
90488   sqlite3DbFree(db, zName);
90489   sqlite3SrcListDelete(db, pTableName);
90490   sqlite3IdListDelete(db, pColumns);
90491   sqlite3ExprDelete(db, pWhen);
90492   if( !pParse->pNewTrigger ){
90493     sqlite3DeleteTrigger(db, pTrigger);
90494   }else{
90495     assert( pParse->pNewTrigger==pTrigger );
90496   }
90497 }
90498
90499 /*
90500 ** This routine is called after all of the trigger actions have been parsed
90501 ** in order to complete the process of building the trigger.
90502 */
90503 SQLITE_PRIVATE void sqlite3FinishTrigger(
90504   Parse *pParse,          /* Parser context */
90505   TriggerStep *pStepList, /* The triggered program */
90506   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
90507 ){
90508   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
90509   char *zName;                            /* Name of trigger */
90510   sqlite3 *db = pParse->db;               /* The database */
90511   DbFixer sFix;                           /* Fixer object */
90512   int iDb;                                /* Database containing the trigger */
90513   Token nameToken;                        /* Trigger name for error reporting */
90514
90515   pTrig = pParse->pNewTrigger;
90516   pParse->pNewTrigger = 0;
90517   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
90518   zName = pTrig->zName;
90519   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
90520   pTrig->step_list = pStepList;
90521   while( pStepList ){
90522     pStepList->pTrig = pTrig;
90523     pStepList = pStepList->pNext;
90524   }
90525   nameToken.z = pTrig->zName;
90526   nameToken.n = sqlite3Strlen30(nameToken.z);
90527   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
90528           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
90529     goto triggerfinish_cleanup;
90530   }
90531
90532   /* if we are not initializing,
90533   ** build the sqlite_master entry
90534   */
90535   if( !db->init.busy ){
90536     Vdbe *v;
90537     char *z;
90538
90539     /* Make an entry in the sqlite_master table */
90540     v = sqlite3GetVdbe(pParse);
90541     if( v==0 ) goto triggerfinish_cleanup;
90542     sqlite3BeginWriteOperation(pParse, 0, iDb);
90543     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
90544     sqlite3NestedParse(pParse,
90545        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
90546        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
90547        pTrig->table, z);
90548     sqlite3DbFree(db, z);
90549     sqlite3ChangeCookie(pParse, iDb);
90550     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
90551         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
90552     );
90553   }
90554
90555   if( db->init.busy ){
90556     Trigger *pLink = pTrig;
90557     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
90558     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
90559     if( pTrig ){
90560       db->mallocFailed = 1;
90561     }else if( pLink->pSchema==pLink->pTabSchema ){
90562       Table *pTab;
90563       int n = sqlite3Strlen30(pLink->table);
90564       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
90565       assert( pTab!=0 );
90566       pLink->pNext = pTab->pTrigger;
90567       pTab->pTrigger = pLink;
90568     }
90569   }
90570
90571 triggerfinish_cleanup:
90572   sqlite3DeleteTrigger(db, pTrig);
90573   assert( !pParse->pNewTrigger );
90574   sqlite3DeleteTriggerStep(db, pStepList);
90575 }
90576
90577 /*
90578 ** Turn a SELECT statement (that the pSelect parameter points to) into
90579 ** a trigger step.  Return a pointer to a TriggerStep structure.
90580 **
90581 ** The parser calls this routine when it finds a SELECT statement in
90582 ** body of a TRIGGER.  
90583 */
90584 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
90585   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
90586   if( pTriggerStep==0 ) {
90587     sqlite3SelectDelete(db, pSelect);
90588     return 0;
90589   }
90590   pTriggerStep->op = TK_SELECT;
90591   pTriggerStep->pSelect = pSelect;
90592   pTriggerStep->orconf = OE_Default;
90593   return pTriggerStep;
90594 }
90595
90596 /*
90597 ** Allocate space to hold a new trigger step.  The allocated space
90598 ** holds both the TriggerStep object and the TriggerStep.target.z string.
90599 **
90600 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
90601 */
90602 static TriggerStep *triggerStepAllocate(
90603   sqlite3 *db,                /* Database connection */
90604   u8 op,                      /* Trigger opcode */
90605   Token *pName                /* The target name */
90606 ){
90607   TriggerStep *pTriggerStep;
90608
90609   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
90610   if( pTriggerStep ){
90611     char *z = (char*)&pTriggerStep[1];
90612     memcpy(z, pName->z, pName->n);
90613     pTriggerStep->target.z = z;
90614     pTriggerStep->target.n = pName->n;
90615     pTriggerStep->op = op;
90616   }
90617   return pTriggerStep;
90618 }
90619
90620 /*
90621 ** Build a trigger step out of an INSERT statement.  Return a pointer
90622 ** to the new trigger step.
90623 **
90624 ** The parser calls this routine when it sees an INSERT inside the
90625 ** body of a trigger.
90626 */
90627 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
90628   sqlite3 *db,        /* The database connection */
90629   Token *pTableName,  /* Name of the table into which we insert */
90630   IdList *pColumn,    /* List of columns in pTableName to insert into */
90631   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
90632   Select *pSelect,    /* A SELECT statement that supplies values */
90633   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
90634 ){
90635   TriggerStep *pTriggerStep;
90636
90637   assert(pEList == 0 || pSelect == 0);
90638   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
90639
90640   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
90641   if( pTriggerStep ){
90642     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90643     pTriggerStep->pIdList = pColumn;
90644     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90645     pTriggerStep->orconf = orconf;
90646   }else{
90647     sqlite3IdListDelete(db, pColumn);
90648   }
90649   sqlite3ExprListDelete(db, pEList);
90650   sqlite3SelectDelete(db, pSelect);
90651
90652   return pTriggerStep;
90653 }
90654
90655 /*
90656 ** Construct a trigger step that implements an UPDATE statement and return
90657 ** a pointer to that trigger step.  The parser calls this routine when it
90658 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
90659 */
90660 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
90661   sqlite3 *db,         /* The database connection */
90662   Token *pTableName,   /* Name of the table to be updated */
90663   ExprList *pEList,    /* The SET clause: list of column and new values */
90664   Expr *pWhere,        /* The WHERE clause */
90665   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
90666 ){
90667   TriggerStep *pTriggerStep;
90668
90669   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
90670   if( pTriggerStep ){
90671     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90672     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90673     pTriggerStep->orconf = orconf;
90674   }
90675   sqlite3ExprListDelete(db, pEList);
90676   sqlite3ExprDelete(db, pWhere);
90677   return pTriggerStep;
90678 }
90679
90680 /*
90681 ** Construct a trigger step that implements a DELETE statement and return
90682 ** a pointer to that trigger step.  The parser calls this routine when it
90683 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
90684 */
90685 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
90686   sqlite3 *db,            /* Database connection */
90687   Token *pTableName,      /* The table from which rows are deleted */
90688   Expr *pWhere            /* The WHERE clause */
90689 ){
90690   TriggerStep *pTriggerStep;
90691
90692   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
90693   if( pTriggerStep ){
90694     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90695     pTriggerStep->orconf = OE_Default;
90696   }
90697   sqlite3ExprDelete(db, pWhere);
90698   return pTriggerStep;
90699 }
90700
90701 /* 
90702 ** Recursively delete a Trigger structure
90703 */
90704 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
90705   if( pTrigger==0 ) return;
90706   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
90707   sqlite3DbFree(db, pTrigger->zName);
90708   sqlite3DbFree(db, pTrigger->table);
90709   sqlite3ExprDelete(db, pTrigger->pWhen);
90710   sqlite3IdListDelete(db, pTrigger->pColumns);
90711   sqlite3DbFree(db, pTrigger);
90712 }
90713
90714 /*
90715 ** This function is called to drop a trigger from the database schema. 
90716 **
90717 ** This may be called directly from the parser and therefore identifies
90718 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
90719 ** same job as this routine except it takes a pointer to the trigger
90720 ** instead of the trigger name.
90721 **/
90722 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
90723   Trigger *pTrigger = 0;
90724   int i;
90725   const char *zDb;
90726   const char *zName;
90727   int nName;
90728   sqlite3 *db = pParse->db;
90729
90730   if( db->mallocFailed ) goto drop_trigger_cleanup;
90731   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
90732     goto drop_trigger_cleanup;
90733   }
90734
90735   assert( pName->nSrc==1 );
90736   zDb = pName->a[0].zDatabase;
90737   zName = pName->a[0].zName;
90738   nName = sqlite3Strlen30(zName);
90739   for(i=OMIT_TEMPDB; i<db->nDb; i++){
90740     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
90741     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
90742     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
90743     if( pTrigger ) break;
90744   }
90745   if( !pTrigger ){
90746     if( !noErr ){
90747       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
90748     }
90749     pParse->checkSchema = 1;
90750     goto drop_trigger_cleanup;
90751   }
90752   sqlite3DropTriggerPtr(pParse, pTrigger);
90753
90754 drop_trigger_cleanup:
90755   sqlite3SrcListDelete(db, pName);
90756 }
90757
90758 /*
90759 ** Return a pointer to the Table structure for the table that a trigger
90760 ** is set on.
90761 */
90762 static Table *tableOfTrigger(Trigger *pTrigger){
90763   int n = sqlite3Strlen30(pTrigger->table);
90764   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
90765 }
90766
90767
90768 /*
90769 ** Drop a trigger given a pointer to that trigger. 
90770 */
90771 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
90772   Table   *pTable;
90773   Vdbe *v;
90774   sqlite3 *db = pParse->db;
90775   int iDb;
90776
90777   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
90778   assert( iDb>=0 && iDb<db->nDb );
90779   pTable = tableOfTrigger(pTrigger);
90780   assert( pTable );
90781   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
90782 #ifndef SQLITE_OMIT_AUTHORIZATION
90783   {
90784     int code = SQLITE_DROP_TRIGGER;
90785     const char *zDb = db->aDb[iDb].zName;
90786     const char *zTab = SCHEMA_TABLE(iDb);
90787     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
90788     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
90789       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
90790       return;
90791     }
90792   }
90793 #endif
90794
90795   /* Generate code to destroy the database record of the trigger.
90796   */
90797   assert( pTable!=0 );
90798   if( (v = sqlite3GetVdbe(pParse))!=0 ){
90799     int base;
90800     static const VdbeOpList dropTrigger[] = {
90801       { OP_Rewind,     0, ADDR(9),  0},
90802       { OP_String8,    0, 1,        0}, /* 1 */
90803       { OP_Column,     0, 1,        2},
90804       { OP_Ne,         2, ADDR(8),  1},
90805       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
90806       { OP_Column,     0, 0,        2},
90807       { OP_Ne,         2, ADDR(8),  1},
90808       { OP_Delete,     0, 0,        0},
90809       { OP_Next,       0, ADDR(1),  0}, /* 8 */
90810     };
90811
90812     sqlite3BeginWriteOperation(pParse, 0, iDb);
90813     sqlite3OpenMasterTable(pParse, iDb);
90814     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
90815     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
90816     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
90817     sqlite3ChangeCookie(pParse, iDb);
90818     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
90819     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
90820     if( pParse->nMem<3 ){
90821       pParse->nMem = 3;
90822     }
90823   }
90824 }
90825
90826 /*
90827 ** Remove a trigger from the hash tables of the sqlite* pointer.
90828 */
90829 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
90830   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
90831   Trigger *pTrigger;
90832   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
90833   if( ALWAYS(pTrigger) ){
90834     if( pTrigger->pSchema==pTrigger->pTabSchema ){
90835       Table *pTab = tableOfTrigger(pTrigger);
90836       Trigger **pp;
90837       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
90838       *pp = (*pp)->pNext;
90839     }
90840     sqlite3DeleteTrigger(db, pTrigger);
90841     db->flags |= SQLITE_InternChanges;
90842   }
90843 }
90844
90845 /*
90846 ** pEList is the SET clause of an UPDATE statement.  Each entry
90847 ** in pEList is of the format <id>=<expr>.  If any of the entries
90848 ** in pEList have an <id> which matches an identifier in pIdList,
90849 ** then return TRUE.  If pIdList==NULL, then it is considered a
90850 ** wildcard that matches anything.  Likewise if pEList==NULL then
90851 ** it matches anything so always return true.  Return false only
90852 ** if there is no match.
90853 */
90854 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
90855   int e;
90856   if( pIdList==0 || NEVER(pEList==0) ) return 1;
90857   for(e=0; e<pEList->nExpr; e++){
90858     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
90859   }
90860   return 0; 
90861 }
90862
90863 /*
90864 ** Return a list of all triggers on table pTab if there exists at least
90865 ** one trigger that must be fired when an operation of type 'op' is 
90866 ** performed on the table, and, if that operation is an UPDATE, if at
90867 ** least one of the columns in pChanges is being modified.
90868 */
90869 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
90870   Parse *pParse,          /* Parse context */
90871   Table *pTab,            /* The table the contains the triggers */
90872   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
90873   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
90874   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
90875 ){
90876   int mask = 0;
90877   Trigger *pList = sqlite3TriggerList(pParse, pTab);
90878   Trigger *p;
90879   assert( pList==0 || IsVirtual(pTab)==0 );
90880   for(p=pList; p; p=p->pNext){
90881     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
90882       mask |= p->tr_tm;
90883     }
90884   }
90885   if( pMask ){
90886     *pMask = mask;
90887   }
90888   return (mask ? pList : 0);
90889 }
90890
90891 /*
90892 ** Convert the pStep->target token into a SrcList and return a pointer
90893 ** to that SrcList.
90894 **
90895 ** This routine adds a specific database name, if needed, to the target when
90896 ** forming the SrcList.  This prevents a trigger in one database from
90897 ** referring to a target in another database.  An exception is when the
90898 ** trigger is in TEMP in which case it can refer to any other database it
90899 ** wants.
90900 */
90901 static SrcList *targetSrcList(
90902   Parse *pParse,       /* The parsing context */
90903   TriggerStep *pStep   /* The trigger containing the target token */
90904 ){
90905   int iDb;             /* Index of the database to use */
90906   SrcList *pSrc;       /* SrcList to be returned */
90907
90908   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
90909   if( pSrc ){
90910     assert( pSrc->nSrc>0 );
90911     assert( pSrc->a!=0 );
90912     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
90913     if( iDb==0 || iDb>=2 ){
90914       sqlite3 *db = pParse->db;
90915       assert( iDb<pParse->db->nDb );
90916       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
90917     }
90918   }
90919   return pSrc;
90920 }
90921
90922 /*
90923 ** Generate VDBE code for the statements inside the body of a single 
90924 ** trigger.
90925 */
90926 static int codeTriggerProgram(
90927   Parse *pParse,            /* The parser context */
90928   TriggerStep *pStepList,   /* List of statements inside the trigger body */
90929   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
90930 ){
90931   TriggerStep *pStep;
90932   Vdbe *v = pParse->pVdbe;
90933   sqlite3 *db = pParse->db;
90934
90935   assert( pParse->pTriggerTab && pParse->pToplevel );
90936   assert( pStepList );
90937   assert( v!=0 );
90938   for(pStep=pStepList; pStep; pStep=pStep->pNext){
90939     /* Figure out the ON CONFLICT policy that will be used for this step
90940     ** of the trigger program. If the statement that caused this trigger
90941     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
90942     ** the ON CONFLICT policy that was specified as part of the trigger
90943     ** step statement. Example:
90944     **
90945     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
90946     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
90947     **   END;
90948     **
90949     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
90950     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
90951     */
90952     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
90953
90954     switch( pStep->op ){
90955       case TK_UPDATE: {
90956         sqlite3Update(pParse, 
90957           targetSrcList(pParse, pStep),
90958           sqlite3ExprListDup(db, pStep->pExprList, 0), 
90959           sqlite3ExprDup(db, pStep->pWhere, 0), 
90960           pParse->eOrconf
90961         );
90962         break;
90963       }
90964       case TK_INSERT: {
90965         sqlite3Insert(pParse, 
90966           targetSrcList(pParse, pStep),
90967           sqlite3ExprListDup(db, pStep->pExprList, 0), 
90968           sqlite3SelectDup(db, pStep->pSelect, 0), 
90969           sqlite3IdListDup(db, pStep->pIdList), 
90970           pParse->eOrconf
90971         );
90972         break;
90973       }
90974       case TK_DELETE: {
90975         sqlite3DeleteFrom(pParse, 
90976           targetSrcList(pParse, pStep),
90977           sqlite3ExprDup(db, pStep->pWhere, 0)
90978         );
90979         break;
90980       }
90981       default: assert( pStep->op==TK_SELECT ); {
90982         SelectDest sDest;
90983         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
90984         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
90985         sqlite3Select(pParse, pSelect, &sDest);
90986         sqlite3SelectDelete(db, pSelect);
90987         break;
90988       }
90989     } 
90990     if( pStep->op!=TK_SELECT ){
90991       sqlite3VdbeAddOp0(v, OP_ResetCount);
90992     }
90993   }
90994
90995   return 0;
90996 }
90997
90998 #ifdef SQLITE_DEBUG
90999 /*
91000 ** This function is used to add VdbeComment() annotations to a VDBE
91001 ** program. It is not used in production code, only for debugging.
91002 */
91003 static const char *onErrorText(int onError){
91004   switch( onError ){
91005     case OE_Abort:    return "abort";
91006     case OE_Rollback: return "rollback";
91007     case OE_Fail:     return "fail";
91008     case OE_Replace:  return "replace";
91009     case OE_Ignore:   return "ignore";
91010     case OE_Default:  return "default";
91011   }
91012   return "n/a";
91013 }
91014 #endif
91015
91016 /*
91017 ** Parse context structure pFrom has just been used to create a sub-vdbe
91018 ** (trigger program). If an error has occurred, transfer error information
91019 ** from pFrom to pTo.
91020 */
91021 static void transferParseError(Parse *pTo, Parse *pFrom){
91022   assert( pFrom->zErrMsg==0 || pFrom->nErr );
91023   assert( pTo->zErrMsg==0 || pTo->nErr );
91024   if( pTo->nErr==0 ){
91025     pTo->zErrMsg = pFrom->zErrMsg;
91026     pTo->nErr = pFrom->nErr;
91027   }else{
91028     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
91029   }
91030 }
91031
91032 /*
91033 ** Create and populate a new TriggerPrg object with a sub-program 
91034 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
91035 */
91036 static TriggerPrg *codeRowTrigger(
91037   Parse *pParse,       /* Current parse context */
91038   Trigger *pTrigger,   /* Trigger to code */
91039   Table *pTab,         /* The table pTrigger is attached to */
91040   int orconf           /* ON CONFLICT policy to code trigger program with */
91041 ){
91042   Parse *pTop = sqlite3ParseToplevel(pParse);
91043   sqlite3 *db = pParse->db;   /* Database handle */
91044   TriggerPrg *pPrg;           /* Value to return */
91045   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
91046   Vdbe *v;                    /* Temporary VM */
91047   NameContext sNC;            /* Name context for sub-vdbe */
91048   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
91049   Parse *pSubParse;           /* Parse context for sub-vdbe */
91050   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
91051
91052   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91053
91054   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
91055   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
91056   ** list of the top-level Parse object sooner rather than later.  */
91057   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
91058   if( !pPrg ) return 0;
91059   pPrg->pNext = pTop->pTriggerPrg;
91060   pTop->pTriggerPrg = pPrg;
91061   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
91062   if( !pProgram ) return 0;
91063   pProgram->nRef = 1;
91064   pPrg->pTrigger = pTrigger;
91065   pPrg->orconf = orconf;
91066   pPrg->aColmask[0] = 0xffffffff;
91067   pPrg->aColmask[1] = 0xffffffff;
91068
91069   /* Allocate and populate a new Parse context to use for coding the 
91070   ** trigger sub-program.  */
91071   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
91072   if( !pSubParse ) return 0;
91073   memset(&sNC, 0, sizeof(sNC));
91074   sNC.pParse = pSubParse;
91075   pSubParse->db = db;
91076   pSubParse->pTriggerTab = pTab;
91077   pSubParse->pToplevel = pTop;
91078   pSubParse->zAuthContext = pTrigger->zName;
91079   pSubParse->eTriggerOp = pTrigger->op;
91080   pSubParse->nQueryLoop = pParse->nQueryLoop;
91081
91082   v = sqlite3GetVdbe(pSubParse);
91083   if( v ){
91084     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
91085       pTrigger->zName, onErrorText(orconf),
91086       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
91087         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
91088         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
91089         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
91090       pTab->zName
91091     ));
91092 #ifndef SQLITE_OMIT_TRACE
91093     sqlite3VdbeChangeP4(v, -1, 
91094       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
91095     );
91096 #endif
91097
91098     /* If one was specified, code the WHEN clause. If it evaluates to false
91099     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
91100     ** OP_Halt inserted at the end of the program.  */
91101     if( pTrigger->pWhen ){
91102       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
91103       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
91104        && db->mallocFailed==0 
91105       ){
91106         iEndTrigger = sqlite3VdbeMakeLabel(v);
91107         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
91108       }
91109       sqlite3ExprDelete(db, pWhen);
91110     }
91111
91112     /* Code the trigger program into the sub-vdbe. */
91113     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
91114
91115     /* Insert an OP_Halt at the end of the sub-program. */
91116     if( iEndTrigger ){
91117       sqlite3VdbeResolveLabel(v, iEndTrigger);
91118     }
91119     sqlite3VdbeAddOp0(v, OP_Halt);
91120     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
91121
91122     transferParseError(pParse, pSubParse);
91123     if( db->mallocFailed==0 ){
91124       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
91125     }
91126     pProgram->nMem = pSubParse->nMem;
91127     pProgram->nCsr = pSubParse->nTab;
91128     pProgram->token = (void *)pTrigger;
91129     pPrg->aColmask[0] = pSubParse->oldmask;
91130     pPrg->aColmask[1] = pSubParse->newmask;
91131     sqlite3VdbeDelete(v);
91132   }
91133
91134   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
91135   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
91136   sqlite3StackFree(db, pSubParse);
91137
91138   return pPrg;
91139 }
91140     
91141 /*
91142 ** Return a pointer to a TriggerPrg object containing the sub-program for
91143 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
91144 ** TriggerPrg object exists, a new object is allocated and populated before
91145 ** being returned.
91146 */
91147 static TriggerPrg *getRowTrigger(
91148   Parse *pParse,       /* Current parse context */
91149   Trigger *pTrigger,   /* Trigger to code */
91150   Table *pTab,         /* The table trigger pTrigger is attached to */
91151   int orconf           /* ON CONFLICT algorithm. */
91152 ){
91153   Parse *pRoot = sqlite3ParseToplevel(pParse);
91154   TriggerPrg *pPrg;
91155
91156   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91157
91158   /* It may be that this trigger has already been coded (or is in the
91159   ** process of being coded). If this is the case, then an entry with
91160   ** a matching TriggerPrg.pTrigger field will be present somewhere
91161   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
91162   for(pPrg=pRoot->pTriggerPrg; 
91163       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
91164       pPrg=pPrg->pNext
91165   );
91166
91167   /* If an existing TriggerPrg could not be located, create a new one. */
91168   if( !pPrg ){
91169     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
91170   }
91171
91172   return pPrg;
91173 }
91174
91175 /*
91176 ** Generate code for the trigger program associated with trigger p on 
91177 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
91178 ** function are the same as those described in the header function for
91179 ** sqlite3CodeRowTrigger()
91180 */
91181 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
91182   Parse *pParse,       /* Parse context */
91183   Trigger *p,          /* Trigger to code */
91184   Table *pTab,         /* The table to code triggers from */
91185   int reg,             /* Reg array containing OLD.* and NEW.* values */
91186   int orconf,          /* ON CONFLICT policy */
91187   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
91188 ){
91189   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
91190   TriggerPrg *pPrg;
91191   pPrg = getRowTrigger(pParse, p, pTab, orconf);
91192   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
91193
91194   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
91195   ** is a pointer to the sub-vdbe containing the trigger program.  */
91196   if( pPrg ){
91197     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
91198     pPrg->pProgram->nRef++;
91199     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
91200     VdbeComment(
91201         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
91202
91203     /* Set the P5 operand of the OP_Program instruction to non-zero if
91204     ** recursive invocation of this trigger program is disallowed. Recursive
91205     ** invocation is disallowed if (a) the sub-program is really a trigger,
91206     ** not a foreign key action, and (b) the flag to enable recursive triggers
91207     ** is clear.  */
91208     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
91209   }
91210 }
91211
91212 /*
91213 ** This is called to code the required FOR EACH ROW triggers for an operation
91214 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
91215 ** is given by the op paramater. The tr_tm parameter determines whether the
91216 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
91217 ** parameter pChanges is passed the list of columns being modified.
91218 **
91219 ** If there are no triggers that fire at the specified time for the specified
91220 ** operation on pTab, this function is a no-op.
91221 **
91222 ** The reg argument is the address of the first in an array of registers 
91223 ** that contain the values substituted for the new.* and old.* references
91224 ** in the trigger program. If N is the number of columns in table pTab
91225 ** (a copy of pTab->nCol), then registers are populated as follows:
91226 **
91227 **   Register       Contains
91228 **   ------------------------------------------------------
91229 **   reg+0          OLD.rowid
91230 **   reg+1          OLD.* value of left-most column of pTab
91231 **   ...            ...
91232 **   reg+N          OLD.* value of right-most column of pTab
91233 **   reg+N+1        NEW.rowid
91234 **   reg+N+2        OLD.* value of left-most column of pTab
91235 **   ...            ...
91236 **   reg+N+N+1      NEW.* value of right-most column of pTab
91237 **
91238 ** For ON DELETE triggers, the registers containing the NEW.* values will
91239 ** never be accessed by the trigger program, so they are not allocated or 
91240 ** populated by the caller (there is no data to populate them with anyway). 
91241 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
91242 ** are never accessed, and so are not allocated by the caller. So, for an
91243 ** ON INSERT trigger, the value passed to this function as parameter reg
91244 ** is not a readable register, although registers (reg+N) through 
91245 ** (reg+N+N+1) are.
91246 **
91247 ** Parameter orconf is the default conflict resolution algorithm for the
91248 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
91249 ** is the instruction that control should jump to if a trigger program
91250 ** raises an IGNORE exception.
91251 */
91252 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
91253   Parse *pParse,       /* Parse context */
91254   Trigger *pTrigger,   /* List of triggers on table pTab */
91255   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
91256   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
91257   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
91258   Table *pTab,         /* The table to code triggers from */
91259   int reg,             /* The first in an array of registers (see above) */
91260   int orconf,          /* ON CONFLICT policy */
91261   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
91262 ){
91263   Trigger *p;          /* Used to iterate through pTrigger list */
91264
91265   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
91266   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
91267   assert( (op==TK_UPDATE)==(pChanges!=0) );
91268
91269   for(p=pTrigger; p; p=p->pNext){
91270
91271     /* Sanity checking:  The schema for the trigger and for the table are
91272     ** always defined.  The trigger must be in the same schema as the table
91273     ** or else it must be a TEMP trigger. */
91274     assert( p->pSchema!=0 );
91275     assert( p->pTabSchema!=0 );
91276     assert( p->pSchema==p->pTabSchema 
91277          || p->pSchema==pParse->db->aDb[1].pSchema );
91278
91279     /* Determine whether we should code this trigger */
91280     if( p->op==op 
91281      && p->tr_tm==tr_tm 
91282      && checkColumnOverlap(p->pColumns, pChanges)
91283     ){
91284       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
91285     }
91286   }
91287 }
91288
91289 /*
91290 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
91291 ** This function returns a 32-bit bitmask indicating which columns of the 
91292 ** old.* or new.* tables actually are used by triggers. This information 
91293 ** may be used by the caller, for example, to avoid having to load the entire
91294 ** old.* record into memory when executing an UPDATE or DELETE command.
91295 **
91296 ** Bit 0 of the returned mask is set if the left-most column of the
91297 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
91298 ** the second leftmost column value is required, and so on. If there
91299 ** are more than 32 columns in the table, and at least one of the columns
91300 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
91301 **
91302 ** It is not possible to determine if the old.rowid or new.rowid column is 
91303 ** accessed by triggers. The caller must always assume that it is.
91304 **
91305 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
91306 ** applies to the old.* table. If 1, the new.* table.
91307 **
91308 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
91309 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
91310 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
91311 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
91312 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
91313 */
91314 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
91315   Parse *pParse,       /* Parse context */
91316   Trigger *pTrigger,   /* List of triggers on table pTab */
91317   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
91318   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
91319   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91320   Table *pTab,         /* The table to code triggers from */
91321   int orconf           /* Default ON CONFLICT policy for trigger steps */
91322 ){
91323   const int op = pChanges ? TK_UPDATE : TK_DELETE;
91324   u32 mask = 0;
91325   Trigger *p;
91326
91327   assert( isNew==1 || isNew==0 );
91328   for(p=pTrigger; p; p=p->pNext){
91329     if( p->op==op && (tr_tm&p->tr_tm)
91330      && checkColumnOverlap(p->pColumns,pChanges)
91331     ){
91332       TriggerPrg *pPrg;
91333       pPrg = getRowTrigger(pParse, p, pTab, orconf);
91334       if( pPrg ){
91335         mask |= pPrg->aColmask[isNew];
91336       }
91337     }
91338   }
91339
91340   return mask;
91341 }
91342
91343 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
91344
91345 /************** End of trigger.c *********************************************/
91346 /************** Begin file update.c ******************************************/
91347 /*
91348 ** 2001 September 15
91349 **
91350 ** The author disclaims copyright to this source code.  In place of
91351 ** a legal notice, here is a blessing:
91352 **
91353 **    May you do good and not evil.
91354 **    May you find forgiveness for yourself and forgive others.
91355 **    May you share freely, never taking more than you give.
91356 **
91357 sqlite*************************************************************************
91358 ** This file contains C code routines that are called by the parser
91359 ** to handle UPDATE statements.
91360 */
91361
91362 #ifndef SQLITE_OMIT_VIRTUALTABLE
91363 /* Forward declaration */
91364 static void updateVirtualTable(
91365   Parse *pParse,       /* The parsing context */
91366   SrcList *pSrc,       /* The virtual table to be modified */
91367   Table *pTab,         /* The virtual table */
91368   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91369   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
91370   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91371   Expr *pWhere         /* WHERE clause of the UPDATE statement */
91372 );
91373 #endif /* SQLITE_OMIT_VIRTUALTABLE */
91374
91375 /*
91376 ** The most recently coded instruction was an OP_Column to retrieve the
91377 ** i-th column of table pTab. This routine sets the P4 parameter of the 
91378 ** OP_Column to the default value, if any.
91379 **
91380 ** The default value of a column is specified by a DEFAULT clause in the 
91381 ** column definition. This was either supplied by the user when the table
91382 ** was created, or added later to the table definition by an ALTER TABLE
91383 ** command. If the latter, then the row-records in the table btree on disk
91384 ** may not contain a value for the column and the default value, taken
91385 ** from the P4 parameter of the OP_Column instruction, is returned instead.
91386 ** If the former, then all row-records are guaranteed to include a value
91387 ** for the column and the P4 value is not required.
91388 **
91389 ** Column definitions created by an ALTER TABLE command may only have 
91390 ** literal default values specified: a number, null or a string. (If a more
91391 ** complicated default expression value was provided, it is evaluated 
91392 ** when the ALTER TABLE is executed and one of the literal values written
91393 ** into the sqlite_master table.)
91394 **
91395 ** Therefore, the P4 parameter is only required if the default value for
91396 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
91397 ** function is capable of transforming these types of expressions into
91398 ** sqlite3_value objects.
91399 **
91400 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
91401 ** on register iReg. This is used when an equivalent integer value is 
91402 ** stored in place of an 8-byte floating point value in order to save 
91403 ** space.
91404 */
91405 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
91406   assert( pTab!=0 );
91407   if( !pTab->pSelect ){
91408     sqlite3_value *pValue;
91409     u8 enc = ENC(sqlite3VdbeDb(v));
91410     Column *pCol = &pTab->aCol[i];
91411     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
91412     assert( i<pTab->nCol );
91413     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
91414                          pCol->affinity, &pValue);
91415     if( pValue ){
91416       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
91417     }
91418 #ifndef SQLITE_OMIT_FLOATING_POINT
91419     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
91420       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
91421     }
91422 #endif
91423   }
91424 }
91425
91426 /*
91427 ** Process an UPDATE statement.
91428 **
91429 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
91430 **          \_______/ \________/     \______/       \________________/
91431 *            onError   pTabList      pChanges             pWhere
91432 */
91433 SQLITE_PRIVATE void sqlite3Update(
91434   Parse *pParse,         /* The parser context */
91435   SrcList *pTabList,     /* The table in which we should change things */
91436   ExprList *pChanges,    /* Things to be changed */
91437   Expr *pWhere,          /* The WHERE clause.  May be null */
91438   int onError            /* How to handle constraint errors */
91439 ){
91440   int i, j;              /* Loop counters */
91441   Table *pTab;           /* The table to be updated */
91442   int addr = 0;          /* VDBE instruction address of the start of the loop */
91443   WhereInfo *pWInfo;     /* Information about the WHERE clause */
91444   Vdbe *v;               /* The virtual database engine */
91445   Index *pIdx;           /* For looping over indices */
91446   int nIdx;              /* Number of indices that need updating */
91447   int iCur;              /* VDBE Cursor number of pTab */
91448   sqlite3 *db;           /* The database structure */
91449   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
91450   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
91451                          ** an expression for the i-th column of the table.
91452                          ** aXRef[i]==-1 if the i-th column is not changed. */
91453   int chngRowid;         /* True if the record number is being changed */
91454   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
91455   int openAll = 0;       /* True if all indices need to be opened */
91456   AuthContext sContext;  /* The authorization context */
91457   NameContext sNC;       /* The name-context to resolve expressions in */
91458   int iDb;               /* Database containing the table being updated */
91459   int okOnePass;         /* True for one-pass algorithm without the FIFO */
91460   int hasFK;             /* True if foreign key processing is required */
91461
91462 #ifndef SQLITE_OMIT_TRIGGER
91463   int isView;            /* True when updating a view (INSTEAD OF trigger) */
91464   Trigger *pTrigger;     /* List of triggers on pTab, if required */
91465   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91466 #endif
91467   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
91468
91469   /* Register Allocations */
91470   int regRowCount = 0;   /* A count of rows changed */
91471   int regOldRowid;       /* The old rowid */
91472   int regNewRowid;       /* The new rowid */
91473   int regNew;
91474   int regOld = 0;
91475   int regRowSet = 0;     /* Rowset of rows to be updated */
91476   int regRec;            /* Register used for new table record to insert */
91477
91478   memset(&sContext, 0, sizeof(sContext));
91479   db = pParse->db;
91480   if( pParse->nErr || db->mallocFailed ){
91481     goto update_cleanup;
91482   }
91483   assert( pTabList->nSrc==1 );
91484
91485   /* Locate the table which we want to update. 
91486   */
91487   pTab = sqlite3SrcListLookup(pParse, pTabList);
91488   if( pTab==0 ) goto update_cleanup;
91489   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91490
91491   /* Figure out if we have any triggers and if the table being
91492   ** updated is a view.
91493   */
91494 #ifndef SQLITE_OMIT_TRIGGER
91495   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
91496   isView = pTab->pSelect!=0;
91497   assert( pTrigger || tmask==0 );
91498 #else
91499 # define pTrigger 0
91500 # define isView 0
91501 # define tmask 0
91502 #endif
91503 #ifdef SQLITE_OMIT_VIEW
91504 # undef isView
91505 # define isView 0
91506 #endif
91507
91508   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
91509     goto update_cleanup;
91510   }
91511   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
91512     goto update_cleanup;
91513   }
91514   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
91515   if( aXRef==0 ) goto update_cleanup;
91516   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
91517
91518   /* Allocate a cursors for the main database table and for all indices.
91519   ** The index cursors might not be used, but if they are used they
91520   ** need to occur right after the database cursor.  So go ahead and
91521   ** allocate enough space, just in case.
91522   */
91523   pTabList->a[0].iCursor = iCur = pParse->nTab++;
91524   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91525     pParse->nTab++;
91526   }
91527
91528   /* Initialize the name-context */
91529   memset(&sNC, 0, sizeof(sNC));
91530   sNC.pParse = pParse;
91531   sNC.pSrcList = pTabList;
91532
91533   /* Resolve the column names in all the expressions of the
91534   ** of the UPDATE statement.  Also find the column index
91535   ** for each column to be updated in the pChanges array.  For each
91536   ** column to be updated, make sure we have authorization to change
91537   ** that column.
91538   */
91539   chngRowid = 0;
91540   for(i=0; i<pChanges->nExpr; i++){
91541     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
91542       goto update_cleanup;
91543     }
91544     for(j=0; j<pTab->nCol; j++){
91545       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
91546         if( j==pTab->iPKey ){
91547           chngRowid = 1;
91548           pRowidExpr = pChanges->a[i].pExpr;
91549         }
91550         aXRef[j] = i;
91551         break;
91552       }
91553     }
91554     if( j>=pTab->nCol ){
91555       if( sqlite3IsRowid(pChanges->a[i].zName) ){
91556         chngRowid = 1;
91557         pRowidExpr = pChanges->a[i].pExpr;
91558       }else{
91559         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
91560         pParse->checkSchema = 1;
91561         goto update_cleanup;
91562       }
91563     }
91564 #ifndef SQLITE_OMIT_AUTHORIZATION
91565     {
91566       int rc;
91567       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
91568                            pTab->aCol[j].zName, db->aDb[iDb].zName);
91569       if( rc==SQLITE_DENY ){
91570         goto update_cleanup;
91571       }else if( rc==SQLITE_IGNORE ){
91572         aXRef[j] = -1;
91573       }
91574     }
91575 #endif
91576   }
91577
91578   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
91579
91580   /* Allocate memory for the array aRegIdx[].  There is one entry in the
91581   ** array for each index associated with table being updated.  Fill in
91582   ** the value with a register number for indices that are to be used
91583   ** and with zero for unused indices.
91584   */
91585   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91586   if( nIdx>0 ){
91587     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
91588     if( aRegIdx==0 ) goto update_cleanup;
91589   }
91590   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91591     int reg;
91592     if( chngRowid ){
91593       reg = ++pParse->nMem;
91594     }else{
91595       reg = 0;
91596       for(i=0; i<pIdx->nColumn; i++){
91597         if( aXRef[pIdx->aiColumn[i]]>=0 ){
91598           reg = ++pParse->nMem;
91599           break;
91600         }
91601       }
91602     }
91603     aRegIdx[j] = reg;
91604   }
91605
91606   /* Begin generating code. */
91607   v = sqlite3GetVdbe(pParse);
91608   if( v==0 ) goto update_cleanup;
91609   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
91610   sqlite3BeginWriteOperation(pParse, 1, iDb);
91611
91612 #ifndef SQLITE_OMIT_VIRTUALTABLE
91613   /* Virtual tables must be handled separately */
91614   if( IsVirtual(pTab) ){
91615     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
91616                        pWhere);
91617     pWhere = 0;
91618     pTabList = 0;
91619     goto update_cleanup;
91620   }
91621 #endif
91622
91623   /* Allocate required registers. */
91624   regOldRowid = regNewRowid = ++pParse->nMem;
91625   if( pTrigger || hasFK ){
91626     regOld = pParse->nMem + 1;
91627     pParse->nMem += pTab->nCol;
91628   }
91629   if( chngRowid || pTrigger || hasFK ){
91630     regNewRowid = ++pParse->nMem;
91631   }
91632   regNew = pParse->nMem + 1;
91633   pParse->nMem += pTab->nCol;
91634   regRec = ++pParse->nMem;
91635
91636   /* Start the view context. */
91637   if( isView ){
91638     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
91639   }
91640
91641   /* If we are trying to update a view, realize that view into
91642   ** a ephemeral table.
91643   */
91644 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
91645   if( isView ){
91646     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
91647   }
91648 #endif
91649
91650   /* Resolve the column names in all the expressions in the
91651   ** WHERE clause.
91652   */
91653   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
91654     goto update_cleanup;
91655   }
91656
91657   /* Begin the database scan
91658   */
91659   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
91660   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
91661   if( pWInfo==0 ) goto update_cleanup;
91662   okOnePass = pWInfo->okOnePass;
91663
91664   /* Remember the rowid of every item to be updated.
91665   */
91666   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
91667   if( !okOnePass ){
91668     regRowSet = ++pParse->nMem;
91669     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
91670   }
91671
91672   /* End the database scan loop.
91673   */
91674   sqlite3WhereEnd(pWInfo);
91675
91676   /* Initialize the count of updated rows
91677   */
91678   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
91679     regRowCount = ++pParse->nMem;
91680     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
91681   }
91682
91683   if( !isView ){
91684     /* 
91685     ** Open every index that needs updating.  Note that if any
91686     ** index could potentially invoke a REPLACE conflict resolution 
91687     ** action, then we need to open all indices because we might need
91688     ** to be deleting some records.
91689     */
91690     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
91691     if( onError==OE_Replace ){
91692       openAll = 1;
91693     }else{
91694       openAll = 0;
91695       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91696         if( pIdx->onError==OE_Replace ){
91697           openAll = 1;
91698           break;
91699         }
91700       }
91701     }
91702     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91703       if( openAll || aRegIdx[i]>0 ){
91704         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91705         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
91706                        (char*)pKey, P4_KEYINFO_HANDOFF);
91707         assert( pParse->nTab>iCur+i+1 );
91708       }
91709     }
91710   }
91711
91712   /* Top of the update loop */
91713   if( okOnePass ){
91714     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
91715     addr = sqlite3VdbeAddOp0(v, OP_Goto);
91716     sqlite3VdbeJumpHere(v, a1);
91717   }else{
91718     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
91719   }
91720
91721   /* Make cursor iCur point to the record that is being updated. If
91722   ** this record does not exist for some reason (deleted by a trigger,
91723   ** for example, then jump to the next iteration of the RowSet loop.  */
91724   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91725
91726   /* If the record number will change, set register regNewRowid to
91727   ** contain the new value. If the record number is not being modified,
91728   ** then regNewRowid is the same register as regOldRowid, which is
91729   ** already populated.  */
91730   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
91731   if( chngRowid ){
91732     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
91733     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
91734   }
91735
91736   /* If there are triggers on this table, populate an array of registers 
91737   ** with the required old.* column data.  */
91738   if( hasFK || pTrigger ){
91739     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
91740     oldmask |= sqlite3TriggerColmask(pParse, 
91741         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
91742     );
91743     for(i=0; i<pTab->nCol; i++){
91744       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
91745         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
91746       }else{
91747         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
91748       }
91749     }
91750     if( chngRowid==0 ){
91751       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
91752     }
91753   }
91754
91755   /* Populate the array of registers beginning at regNew with the new
91756   ** row data. This array is used to check constaints, create the new
91757   ** table and index records, and as the values for any new.* references
91758   ** made by triggers.
91759   **
91760   ** If there are one or more BEFORE triggers, then do not populate the
91761   ** registers associated with columns that are (a) not modified by
91762   ** this UPDATE statement and (b) not accessed by new.* references. The
91763   ** values for registers not modified by the UPDATE must be reloaded from 
91764   ** the database after the BEFORE triggers are fired anyway (as the trigger 
91765   ** may have modified them). So not loading those that are not going to
91766   ** be used eliminates some redundant opcodes.
91767   */
91768   newmask = sqlite3TriggerColmask(
91769       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
91770   );
91771   for(i=0; i<pTab->nCol; i++){
91772     if( i==pTab->iPKey ){
91773       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
91774     }else{
91775       j = aXRef[i];
91776       if( j>=0 ){
91777         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
91778       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
91779         /* This branch loads the value of a column that will not be changed 
91780         ** into a register. This is done if there are no BEFORE triggers, or
91781         ** if there are one or more BEFORE triggers that use this value via
91782         ** a new.* reference in a trigger program.
91783         */
91784         testcase( i==31 );
91785         testcase( i==32 );
91786         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91787         sqlite3ColumnDefault(v, pTab, i, regNew+i);
91788       }
91789     }
91790   }
91791
91792   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
91793   ** verified. One could argue that this is wrong.
91794   */
91795   if( tmask&TRIGGER_BEFORE ){
91796     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
91797     sqlite3TableAffinityStr(v, pTab);
91798     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
91799         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
91800
91801     /* The row-trigger may have deleted the row being updated. In this
91802     ** case, jump to the next row. No updates or AFTER triggers are 
91803     ** required. This behaviour - what happens when the row being updated
91804     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
91805     ** documentation.
91806     */
91807     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91808
91809     /* If it did not delete it, the row-trigger may still have modified 
91810     ** some of the columns of the row being updated. Load the values for 
91811     ** all columns not modified by the update statement into their 
91812     ** registers in case this has happened.
91813     */
91814     for(i=0; i<pTab->nCol; i++){
91815       if( aXRef[i]<0 && i!=pTab->iPKey ){
91816         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91817         sqlite3ColumnDefault(v, pTab, i, regNew+i);
91818       }
91819     }
91820   }
91821
91822   if( !isView ){
91823     int j1;                       /* Address of jump instruction */
91824
91825     /* Do constraint checks. */
91826     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
91827         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
91828
91829     /* Do FK constraint checks. */
91830     if( hasFK ){
91831       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
91832     }
91833
91834     /* Delete the index entries associated with the current record.  */
91835     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
91836     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
91837   
91838     /* If changing the record number, delete the old record.  */
91839     if( hasFK || chngRowid ){
91840       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
91841     }
91842     sqlite3VdbeJumpHere(v, j1);
91843
91844     if( hasFK ){
91845       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
91846     }
91847   
91848     /* Insert the new index entries and the new record. */
91849     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
91850
91851     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
91852     ** handle rows (possibly in other tables) that refer via a foreign key
91853     ** to the row just updated. */ 
91854     if( hasFK ){
91855       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
91856     }
91857   }
91858
91859   /* Increment the row counter 
91860   */
91861   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
91862     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91863   }
91864
91865   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
91866       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
91867
91868   /* Repeat the above with the next record to be updated, until
91869   ** all record selected by the WHERE clause have been updated.
91870   */
91871   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
91872   sqlite3VdbeJumpHere(v, addr);
91873
91874   /* Close all tables */
91875   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91876     if( openAll || aRegIdx[i]>0 ){
91877       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
91878     }
91879   }
91880   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
91881
91882   /* Update the sqlite_sequence table by storing the content of the
91883   ** maximum rowid counter values recorded while inserting into
91884   ** autoincrement tables.
91885   */
91886   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91887     sqlite3AutoincrementEnd(pParse);
91888   }
91889
91890   /*
91891   ** Return the number of rows that were changed. If this routine is 
91892   ** generating code because of a call to sqlite3NestedParse(), do not
91893   ** invoke the callback function.
91894   */
91895   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
91896     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91897     sqlite3VdbeSetNumCols(v, 1);
91898     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
91899   }
91900
91901 update_cleanup:
91902   sqlite3AuthContextPop(&sContext);
91903   sqlite3DbFree(db, aRegIdx);
91904   sqlite3DbFree(db, aXRef);
91905   sqlite3SrcListDelete(db, pTabList);
91906   sqlite3ExprListDelete(db, pChanges);
91907   sqlite3ExprDelete(db, pWhere);
91908   return;
91909 }
91910 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91911 ** thely may interfere with compilation of other functions in this file
91912 ** (or in another file, if this file becomes part of the amalgamation).  */
91913 #ifdef isView
91914  #undef isView
91915 #endif
91916 #ifdef pTrigger
91917  #undef pTrigger
91918 #endif
91919
91920 #ifndef SQLITE_OMIT_VIRTUALTABLE
91921 /*
91922 ** Generate code for an UPDATE of a virtual table.
91923 **
91924 ** The strategy is that we create an ephemerial table that contains
91925 ** for each row to be changed:
91926 **
91927 **   (A)  The original rowid of that row.
91928 **   (B)  The revised rowid for the row. (note1)
91929 **   (C)  The content of every column in the row.
91930 **
91931 ** Then we loop over this ephemeral table and for each row in
91932 ** the ephermeral table call VUpdate.
91933 **
91934 ** When finished, drop the ephemeral table.
91935 **
91936 ** (note1) Actually, if we know in advance that (A) is always the same
91937 ** as (B) we only store (A), then duplicate (A) when pulling
91938 ** it out of the ephemeral table before calling VUpdate.
91939 */
91940 static void updateVirtualTable(
91941   Parse *pParse,       /* The parsing context */
91942   SrcList *pSrc,       /* The virtual table to be modified */
91943   Table *pTab,         /* The virtual table */
91944   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91945   Expr *pRowid,        /* Expression used to recompute the rowid */
91946   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91947   Expr *pWhere         /* WHERE clause of the UPDATE statement */
91948 ){
91949   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
91950   ExprList *pEList = 0;     /* The result set of the SELECT statement */
91951   Select *pSelect = 0;      /* The SELECT statement */
91952   Expr *pExpr;              /* Temporary expression */
91953   int ephemTab;             /* Table holding the result of the SELECT */
91954   int i;                    /* Loop counter */
91955   int addr;                 /* Address of top of loop */
91956   int iReg;                 /* First register in set passed to OP_VUpdate */
91957   sqlite3 *db = pParse->db; /* Database connection */
91958   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
91959   SelectDest dest;
91960
91961   /* Construct the SELECT statement that will find the new values for
91962   ** all updated rows. 
91963   */
91964   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
91965   if( pRowid ){
91966     pEList = sqlite3ExprListAppend(pParse, pEList,
91967                                    sqlite3ExprDup(db, pRowid, 0));
91968   }
91969   assert( pTab->iPKey<0 );
91970   for(i=0; i<pTab->nCol; i++){
91971     if( aXRef[i]>=0 ){
91972       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
91973     }else{
91974       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
91975     }
91976     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
91977   }
91978   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
91979   
91980   /* Create the ephemeral table into which the update results will
91981   ** be stored.
91982   */
91983   assert( v );
91984   ephemTab = pParse->nTab++;
91985   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
91986
91987   /* fill the ephemeral table 
91988   */
91989   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
91990   sqlite3Select(pParse, pSelect, &dest);
91991
91992   /* Generate code to scan the ephemeral table and call VUpdate. */
91993   iReg = ++pParse->nMem;
91994   pParse->nMem += pTab->nCol+1;
91995   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
91996   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
91997   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
91998   for(i=0; i<pTab->nCol; i++){
91999     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
92000   }
92001   sqlite3VtabMakeWritable(pParse, pTab);
92002   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
92003   sqlite3MayAbort(pParse);
92004   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
92005   sqlite3VdbeJumpHere(v, addr);
92006   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
92007
92008   /* Cleanup */
92009   sqlite3SelectDelete(db, pSelect);  
92010 }
92011 #endif /* SQLITE_OMIT_VIRTUALTABLE */
92012
92013 /************** End of update.c **********************************************/
92014 /************** Begin file vacuum.c ******************************************/
92015 /*
92016 ** 2003 April 6
92017 **
92018 ** The author disclaims copyright to this source code.  In place of
92019 ** a legal notice, here is a blessing:
92020 **
92021 **    May you do good and not evil.
92022 **    May you find forgiveness for yourself and forgive others.
92023 **    May you share freely, never taking more than you give.
92024 **
92025 *************************************************************************
92026 ** This file contains code used to implement the VACUUM command.
92027 **
92028 ** Most of the code in this file may be omitted by defining the
92029 ** SQLITE_OMIT_VACUUM macro.
92030 */
92031
92032 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
92033 /*
92034 ** Finalize a prepared statement.  If there was an error, store the
92035 ** text of the error message in *pzErrMsg.  Return the result code.
92036 */
92037 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
92038   int rc;
92039   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
92040   if( rc ){
92041     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92042   }
92043   return rc;
92044 }
92045
92046 /*
92047 ** Execute zSql on database db. Return an error code.
92048 */
92049 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92050   sqlite3_stmt *pStmt;
92051   VVA_ONLY( int rc; )
92052   if( !zSql ){
92053     return SQLITE_NOMEM;
92054   }
92055   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
92056     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92057     return sqlite3_errcode(db);
92058   }
92059   VVA_ONLY( rc = ) sqlite3_step(pStmt);
92060   assert( rc!=SQLITE_ROW );
92061   return vacuumFinalize(db, pStmt, pzErrMsg);
92062 }
92063
92064 /*
92065 ** Execute zSql on database db. The statement returns exactly
92066 ** one column. Execute this as SQL on the same database.
92067 */
92068 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92069   sqlite3_stmt *pStmt;
92070   int rc;
92071
92072   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
92073   if( rc!=SQLITE_OK ) return rc;
92074
92075   while( SQLITE_ROW==sqlite3_step(pStmt) ){
92076     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
92077     if( rc!=SQLITE_OK ){
92078       vacuumFinalize(db, pStmt, pzErrMsg);
92079       return rc;
92080     }
92081   }
92082
92083   return vacuumFinalize(db, pStmt, pzErrMsg);
92084 }
92085
92086 /*
92087 ** The non-standard VACUUM command is used to clean up the database,
92088 ** collapse free space, etc.  It is modelled after the VACUUM command
92089 ** in PostgreSQL.
92090 **
92091 ** In version 1.0.x of SQLite, the VACUUM command would call
92092 ** gdbm_reorganize() on all the database tables.  But beginning
92093 ** with 2.0.0, SQLite no longer uses GDBM so this command has
92094 ** become a no-op.
92095 */
92096 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
92097   Vdbe *v = sqlite3GetVdbe(pParse);
92098   if( v ){
92099     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
92100   }
92101   return;
92102 }
92103
92104 /*
92105 ** This routine implements the OP_Vacuum opcode of the VDBE.
92106 */
92107 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
92108   int rc = SQLITE_OK;     /* Return code from service routines */
92109   Btree *pMain;           /* The database being vacuumed */
92110   Btree *pTemp;           /* The temporary database we vacuum into */
92111   char *zSql = 0;         /* SQL statements */
92112   int saved_flags;        /* Saved value of the db->flags */
92113   int saved_nChange;      /* Saved value of db->nChange */
92114   int saved_nTotalChange; /* Saved value of db->nTotalChange */
92115   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
92116   Db *pDb = 0;            /* Database to detach at end of vacuum */
92117   int isMemDb;            /* True if vacuuming a :memory: database */
92118   int nRes;               /* Bytes of reserved space at the end of each page */
92119   int nDb;                /* Number of attached databases */
92120
92121   if( !db->autoCommit ){
92122     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
92123     return SQLITE_ERROR;
92124   }
92125
92126   /* Save the current value of the database flags so that it can be 
92127   ** restored before returning. Then set the writable-schema flag, and
92128   ** disable CHECK and foreign key constraints.  */
92129   saved_flags = db->flags;
92130   saved_nChange = db->nChange;
92131   saved_nTotalChange = db->nTotalChange;
92132   saved_xTrace = db->xTrace;
92133   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
92134   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
92135   db->xTrace = 0;
92136
92137   pMain = db->aDb[0].pBt;
92138   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
92139
92140   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
92141   ** can be set to 'off' for this file, as it is not recovered if a crash
92142   ** occurs anyway. The integrity of the database is maintained by a
92143   ** (possibly synchronous) transaction opened on the main database before
92144   ** sqlite3BtreeCopyFile() is called.
92145   **
92146   ** An optimisation would be to use a non-journaled pager.
92147   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
92148   ** that actually made the VACUUM run slower.  Very little journalling
92149   ** actually occurs when doing a vacuum since the vacuum_db is initially
92150   ** empty.  Only the journal header is written.  Apparently it takes more
92151   ** time to parse and run the PRAGMA to turn journalling off than it does
92152   ** to write the journal header file.
92153   */
92154   nDb = db->nDb;
92155   if( sqlite3TempInMemory(db) ){
92156     zSql = "ATTACH ':memory:' AS vacuum_db;";
92157   }else{
92158     zSql = "ATTACH '' AS vacuum_db;";
92159   }
92160   rc = execSql(db, pzErrMsg, zSql);
92161   if( db->nDb>nDb ){
92162     pDb = &db->aDb[db->nDb-1];
92163     assert( strcmp(pDb->zName,"vacuum_db")==0 );
92164   }
92165   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92166   pTemp = db->aDb[db->nDb-1].pBt;
92167
92168   /* The call to execSql() to attach the temp database has left the file
92169   ** locked (as there was more than one active statement when the transaction
92170   ** to read the schema was concluded. Unlock it here so that this doesn't
92171   ** cause problems for the call to BtreeSetPageSize() below.  */
92172   sqlite3BtreeCommit(pTemp);
92173
92174   nRes = sqlite3BtreeGetReserve(pMain);
92175
92176   /* A VACUUM cannot change the pagesize of an encrypted database. */
92177 #ifdef SQLITE_HAS_CODEC
92178   if( db->nextPagesize ){
92179     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
92180     int nKey;
92181     char *zKey;
92182     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
92183     if( nKey ) db->nextPagesize = 0;
92184   }
92185 #endif
92186
92187   /* Do not attempt to change the page size for a WAL database */
92188   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
92189                                                ==PAGER_JOURNALMODE_WAL ){
92190     db->nextPagesize = 0;
92191   }
92192
92193   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
92194    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
92195    || NEVER(db->mallocFailed)
92196   ){
92197     rc = SQLITE_NOMEM;
92198     goto end_of_vacuum;
92199   }
92200   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
92201   if( rc!=SQLITE_OK ){
92202     goto end_of_vacuum;
92203   }
92204
92205 #ifndef SQLITE_OMIT_AUTOVACUUM
92206   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
92207                                            sqlite3BtreeGetAutoVacuum(pMain));
92208 #endif
92209
92210   /* Begin a transaction */
92211   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
92212   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92213
92214   /* Query the schema of the main database. Create a mirror schema
92215   ** in the temporary database.
92216   */
92217   rc = execExecSql(db, pzErrMsg,
92218       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
92219       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
92220       "   AND rootpage>0"
92221   );
92222   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92223   rc = execExecSql(db, pzErrMsg,
92224       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
92225       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
92226   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92227   rc = execExecSql(db, pzErrMsg,
92228       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
92229       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
92230   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92231
92232   /* Loop through the tables in the main database. For each, do
92233   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
92234   ** the contents to the temporary database.
92235   */
92236   rc = execExecSql(db, pzErrMsg,
92237       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
92238       "|| ' SELECT * FROM main.' || quote(name) || ';'"
92239       "FROM main.sqlite_master "
92240       "WHERE type = 'table' AND name!='sqlite_sequence' "
92241       "  AND rootpage>0"
92242   );
92243   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92244
92245   /* Copy over the sequence table
92246   */
92247   rc = execExecSql(db, pzErrMsg,
92248       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
92249       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
92250   );
92251   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92252   rc = execExecSql(db, pzErrMsg,
92253       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
92254       "|| ' SELECT * FROM main.' || quote(name) || ';' "
92255       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
92256   );
92257   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92258
92259
92260   /* Copy the triggers, views, and virtual tables from the main database
92261   ** over to the temporary database.  None of these objects has any
92262   ** associated storage, so all we have to do is copy their entries
92263   ** from the SQLITE_MASTER table.
92264   */
92265   rc = execSql(db, pzErrMsg,
92266       "INSERT INTO vacuum_db.sqlite_master "
92267       "  SELECT type, name, tbl_name, rootpage, sql"
92268       "    FROM main.sqlite_master"
92269       "   WHERE type='view' OR type='trigger'"
92270       "      OR (type='table' AND rootpage=0)"
92271   );
92272   if( rc ) goto end_of_vacuum;
92273
92274   /* At this point, unless the main db was completely empty, there is now a
92275   ** transaction open on the vacuum database, but not on the main database.
92276   ** Open a btree level transaction on the main database. This allows a
92277   ** call to sqlite3BtreeCopyFile(). The main database btree level
92278   ** transaction is then committed, so the SQL level never knows it was
92279   ** opened for writing. This way, the SQL transaction used to create the
92280   ** temporary database never needs to be committed.
92281   */
92282   {
92283     u32 meta;
92284     int i;
92285
92286     /* This array determines which meta meta values are preserved in the
92287     ** vacuum.  Even entries are the meta value number and odd entries
92288     ** are an increment to apply to the meta value after the vacuum.
92289     ** The increment is used to increase the schema cookie so that other
92290     ** connections to the same database will know to reread the schema.
92291     */
92292     static const unsigned char aCopy[] = {
92293        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
92294        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
92295        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
92296        BTREE_USER_VERSION,       0,  /* Preserve the user version */
92297     };
92298
92299     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
92300     assert( 1==sqlite3BtreeIsInTrans(pMain) );
92301
92302     /* Copy Btree meta values */
92303     for(i=0; i<ArraySize(aCopy); i+=2){
92304       /* GetMeta() and UpdateMeta() cannot fail in this context because
92305       ** we already have page 1 loaded into cache and marked dirty. */
92306       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
92307       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
92308       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
92309     }
92310
92311     rc = sqlite3BtreeCopyFile(pMain, pTemp);
92312     if( rc!=SQLITE_OK ) goto end_of_vacuum;
92313     rc = sqlite3BtreeCommit(pTemp);
92314     if( rc!=SQLITE_OK ) goto end_of_vacuum;
92315 #ifndef SQLITE_OMIT_AUTOVACUUM
92316     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
92317 #endif
92318   }
92319
92320   assert( rc==SQLITE_OK );
92321   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
92322
92323 end_of_vacuum:
92324   /* Restore the original value of db->flags */
92325   db->flags = saved_flags;
92326   db->nChange = saved_nChange;
92327   db->nTotalChange = saved_nTotalChange;
92328   db->xTrace = saved_xTrace;
92329   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
92330
92331   /* Currently there is an SQL level transaction open on the vacuum
92332   ** database. No locks are held on any other files (since the main file
92333   ** was committed at the btree level). So it safe to end the transaction
92334   ** by manually setting the autoCommit flag to true and detaching the
92335   ** vacuum database. The vacuum_db journal file is deleted when the pager
92336   ** is closed by the DETACH.
92337   */
92338   db->autoCommit = 1;
92339
92340   if( pDb ){
92341     sqlite3BtreeClose(pDb->pBt);
92342     pDb->pBt = 0;
92343     pDb->pSchema = 0;
92344   }
92345
92346   sqlite3ResetInternalSchema(db, 0);
92347
92348   return rc;
92349 }
92350 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
92351
92352 /************** End of vacuum.c **********************************************/
92353 /************** Begin file vtab.c ********************************************/
92354 /*
92355 ** 2006 June 10
92356 **
92357 ** The author disclaims copyright to this source code.  In place of
92358 ** a legal notice, here is a blessing:
92359 **
92360 **    May you do good and not evil.
92361 **    May you find forgiveness for yourself and forgive others.
92362 **    May you share freely, never taking more than you give.
92363 **
92364 *************************************************************************
92365 ** This file contains code used to help implement virtual tables.
92366 */
92367 #ifndef SQLITE_OMIT_VIRTUALTABLE
92368
92369 /*
92370 ** The actual function that does the work of creating a new module.
92371 ** This function implements the sqlite3_create_module() and
92372 ** sqlite3_create_module_v2() interfaces.
92373 */
92374 static int createModule(
92375   sqlite3 *db,                    /* Database in which module is registered */
92376   const char *zName,              /* Name assigned to this module */
92377   const sqlite3_module *pModule,  /* The definition of the module */
92378   void *pAux,                     /* Context pointer for xCreate/xConnect */
92379   void (*xDestroy)(void *)        /* Module destructor function */
92380 ){
92381   int rc, nName;
92382   Module *pMod;
92383
92384   sqlite3_mutex_enter(db->mutex);
92385   nName = sqlite3Strlen30(zName);
92386   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
92387   if( pMod ){
92388     Module *pDel;
92389     char *zCopy = (char *)(&pMod[1]);
92390     memcpy(zCopy, zName, nName+1);
92391     pMod->zName = zCopy;
92392     pMod->pModule = pModule;
92393     pMod->pAux = pAux;
92394     pMod->xDestroy = xDestroy;
92395     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
92396     if( pDel && pDel->xDestroy ){
92397       pDel->xDestroy(pDel->pAux);
92398     }
92399     sqlite3DbFree(db, pDel);
92400     if( pDel==pMod ){
92401       db->mallocFailed = 1;
92402     }
92403     sqlite3ResetInternalSchema(db, 0);
92404   }else if( xDestroy ){
92405     xDestroy(pAux);
92406   }
92407   rc = sqlite3ApiExit(db, SQLITE_OK);
92408   sqlite3_mutex_leave(db->mutex);
92409   return rc;
92410 }
92411
92412
92413 /*
92414 ** External API function used to create a new virtual-table module.
92415 */
92416 SQLITE_API int sqlite3_create_module(
92417   sqlite3 *db,                    /* Database in which module is registered */
92418   const char *zName,              /* Name assigned to this module */
92419   const sqlite3_module *pModule,  /* The definition of the module */
92420   void *pAux                      /* Context pointer for xCreate/xConnect */
92421 ){
92422   return createModule(db, zName, pModule, pAux, 0);
92423 }
92424
92425 /*
92426 ** External API function used to create a new virtual-table module.
92427 */
92428 SQLITE_API int sqlite3_create_module_v2(
92429   sqlite3 *db,                    /* Database in which module is registered */
92430   const char *zName,              /* Name assigned to this module */
92431   const sqlite3_module *pModule,  /* The definition of the module */
92432   void *pAux,                     /* Context pointer for xCreate/xConnect */
92433   void (*xDestroy)(void *)        /* Module destructor function */
92434 ){
92435   return createModule(db, zName, pModule, pAux, xDestroy);
92436 }
92437
92438 /*
92439 ** Lock the virtual table so that it cannot be disconnected.
92440 ** Locks nest.  Every lock should have a corresponding unlock.
92441 ** If an unlock is omitted, resources leaks will occur.  
92442 **
92443 ** If a disconnect is attempted while a virtual table is locked,
92444 ** the disconnect is deferred until all locks have been removed.
92445 */
92446 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
92447   pVTab->nRef++;
92448 }
92449
92450
92451 /*
92452 ** pTab is a pointer to a Table structure representing a virtual-table.
92453 ** Return a pointer to the VTable object used by connection db to access 
92454 ** this virtual-table, if one has been created, or NULL otherwise.
92455 */
92456 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
92457   VTable *pVtab;
92458   assert( IsVirtual(pTab) );
92459   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
92460   return pVtab;
92461 }
92462
92463 /*
92464 ** Decrement the ref-count on a virtual table object. When the ref-count
92465 ** reaches zero, call the xDisconnect() method to delete the object.
92466 */
92467 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
92468   sqlite3 *db = pVTab->db;
92469
92470   assert( db );
92471   assert( pVTab->nRef>0 );
92472   assert( sqlite3SafetyCheckOk(db) );
92473
92474   pVTab->nRef--;
92475   if( pVTab->nRef==0 ){
92476     sqlite3_vtab *p = pVTab->pVtab;
92477     if( p ){
92478       p->pModule->xDisconnect(p);
92479     }
92480     sqlite3DbFree(db, pVTab);
92481   }
92482 }
92483
92484 /*
92485 ** Table p is a virtual table. This function moves all elements in the
92486 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
92487 ** database connections to be disconnected at the next opportunity. 
92488 ** Except, if argument db is not NULL, then the entry associated with
92489 ** connection db is left in the p->pVTable list.
92490 */
92491 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
92492   VTable *pRet = 0;
92493   VTable *pVTable = p->pVTable;
92494   p->pVTable = 0;
92495
92496   /* Assert that the mutex (if any) associated with the BtShared database 
92497   ** that contains table p is held by the caller. See header comments 
92498   ** above function sqlite3VtabUnlockList() for an explanation of why
92499   ** this makes it safe to access the sqlite3.pDisconnect list of any
92500   ** database connection that may have an entry in the p->pVTable list.  */
92501   assert( db==0 ||
92502     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
92503   );
92504
92505   while( pVTable ){
92506     sqlite3 *db2 = pVTable->db;
92507     VTable *pNext = pVTable->pNext;
92508     assert( db2 );
92509     if( db2==db ){
92510       pRet = pVTable;
92511       p->pVTable = pRet;
92512       pRet->pNext = 0;
92513     }else{
92514       pVTable->pNext = db2->pDisconnect;
92515       db2->pDisconnect = pVTable;
92516     }
92517     pVTable = pNext;
92518   }
92519
92520   assert( !db || pRet );
92521   return pRet;
92522 }
92523
92524
92525 /*
92526 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
92527 **
92528 ** This function may only be called when the mutexes associated with all
92529 ** shared b-tree databases opened using connection db are held by the 
92530 ** caller. This is done to protect the sqlite3.pDisconnect list. The
92531 ** sqlite3.pDisconnect list is accessed only as follows:
92532 **
92533 **   1) By this function. In this case, all BtShared mutexes and the mutex
92534 **      associated with the database handle itself must be held.
92535 **
92536 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
92537 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
92538 **      associated with the database the virtual table is stored in is held
92539 **      or, if the virtual table is stored in a non-sharable database, then
92540 **      the database handle mutex is held.
92541 **
92542 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
92543 ** by multiple threads. It is thread-safe.
92544 */
92545 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
92546   VTable *p = db->pDisconnect;
92547   db->pDisconnect = 0;
92548
92549   assert( sqlite3BtreeHoldsAllMutexes(db) );
92550   assert( sqlite3_mutex_held(db->mutex) );
92551
92552   if( p ){
92553     sqlite3ExpirePreparedStatements(db);
92554     do {
92555       VTable *pNext = p->pNext;
92556       sqlite3VtabUnlock(p);
92557       p = pNext;
92558     }while( p );
92559   }
92560 }
92561
92562 /*
92563 ** Clear any and all virtual-table information from the Table record.
92564 ** This routine is called, for example, just before deleting the Table
92565 ** record.
92566 **
92567 ** Since it is a virtual-table, the Table structure contains a pointer
92568 ** to the head of a linked list of VTable structures. Each VTable 
92569 ** structure is associated with a single sqlite3* user of the schema.
92570 ** The reference count of the VTable structure associated with database 
92571 ** connection db is decremented immediately (which may lead to the 
92572 ** structure being xDisconnected and free). Any other VTable structures
92573 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
92574 ** database connection.
92575 */
92576 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
92577   vtabDisconnectAll(0, p);
92578   if( p->azModuleArg ){
92579     int i;
92580     for(i=0; i<p->nModuleArg; i++){
92581       sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
92582     }
92583     sqlite3DbFree(p->dbMem, p->azModuleArg);
92584   }
92585 }
92586
92587 /*
92588 ** Add a new module argument to pTable->azModuleArg[].
92589 ** The string is not copied - the pointer is stored.  The
92590 ** string will be freed automatically when the table is
92591 ** deleted.
92592 */
92593 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
92594   int i = pTable->nModuleArg++;
92595   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
92596   char **azModuleArg;
92597   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
92598   if( azModuleArg==0 ){
92599     int j;
92600     for(j=0; j<i; j++){
92601       sqlite3DbFree(db, pTable->azModuleArg[j]);
92602     }
92603     sqlite3DbFree(db, zArg);
92604     sqlite3DbFree(db, pTable->azModuleArg);
92605     pTable->nModuleArg = 0;
92606   }else{
92607     azModuleArg[i] = zArg;
92608     azModuleArg[i+1] = 0;
92609   }
92610   pTable->azModuleArg = azModuleArg;
92611 }
92612
92613 /*
92614 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
92615 ** statement.  The module name has been parsed, but the optional list
92616 ** of parameters that follow the module name are still pending.
92617 */
92618 SQLITE_PRIVATE void sqlite3VtabBeginParse(
92619   Parse *pParse,        /* Parsing context */
92620   Token *pName1,        /* Name of new table, or database name */
92621   Token *pName2,        /* Name of new table or NULL */
92622   Token *pModuleName    /* Name of the module for the virtual table */
92623 ){
92624   int iDb;              /* The database the table is being created in */
92625   Table *pTable;        /* The new virtual table */
92626   sqlite3 *db;          /* Database connection */
92627
92628   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
92629   pTable = pParse->pNewTable;
92630   if( pTable==0 ) return;
92631   assert( 0==pTable->pIndex );
92632
92633   db = pParse->db;
92634   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
92635   assert( iDb>=0 );
92636
92637   pTable->tabFlags |= TF_Virtual;
92638   pTable->nModuleArg = 0;
92639   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
92640   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
92641   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
92642   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
92643
92644 #ifndef SQLITE_OMIT_AUTHORIZATION
92645   /* Creating a virtual table invokes the authorization callback twice.
92646   ** The first invocation, to obtain permission to INSERT a row into the
92647   ** sqlite_master table, has already been made by sqlite3StartTable().
92648   ** The second call, to obtain permission to create the table, is made now.
92649   */
92650   if( pTable->azModuleArg ){
92651     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
92652             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
92653   }
92654 #endif
92655 }
92656
92657 /*
92658 ** This routine takes the module argument that has been accumulating
92659 ** in pParse->zArg[] and appends it to the list of arguments on the
92660 ** virtual table currently under construction in pParse->pTable.
92661 */
92662 static void addArgumentToVtab(Parse *pParse){
92663   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
92664     const char *z = (const char*)pParse->sArg.z;
92665     int n = pParse->sArg.n;
92666     sqlite3 *db = pParse->db;
92667     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
92668   }
92669 }
92670
92671 /*
92672 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
92673 ** has been completely parsed.
92674 */
92675 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
92676   Table *pTab = pParse->pNewTable;  /* The table being constructed */
92677   sqlite3 *db = pParse->db;         /* The database connection */
92678
92679   if( pTab==0 ) return;
92680   addArgumentToVtab(pParse);
92681   pParse->sArg.z = 0;
92682   if( pTab->nModuleArg<1 ) return;
92683   
92684   /* If the CREATE VIRTUAL TABLE statement is being entered for the
92685   ** first time (in other words if the virtual table is actually being
92686   ** created now instead of just being read out of sqlite_master) then
92687   ** do additional initialization work and store the statement text
92688   ** in the sqlite_master table.
92689   */
92690   if( !db->init.busy ){
92691     char *zStmt;
92692     char *zWhere;
92693     int iDb;
92694     Vdbe *v;
92695
92696     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
92697     if( pEnd ){
92698       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
92699     }
92700     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
92701
92702     /* A slot for the record has already been allocated in the 
92703     ** SQLITE_MASTER table.  We just need to update that slot with all
92704     ** the information we've collected.  
92705     **
92706     ** The VM register number pParse->regRowid holds the rowid of an
92707     ** entry in the sqlite_master table tht was created for this vtab
92708     ** by sqlite3StartTable().
92709     */
92710     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92711     sqlite3NestedParse(pParse,
92712       "UPDATE %Q.%s "
92713          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
92714        "WHERE rowid=#%d",
92715       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
92716       pTab->zName,
92717       pTab->zName,
92718       zStmt,
92719       pParse->regRowid
92720     );
92721     sqlite3DbFree(db, zStmt);
92722     v = sqlite3GetVdbe(pParse);
92723     sqlite3ChangeCookie(pParse, iDb);
92724
92725     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92726     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
92727     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
92728     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
92729                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
92730   }
92731
92732   /* If we are rereading the sqlite_master table create the in-memory
92733   ** record of the table. The xConnect() method is not called until
92734   ** the first time the virtual table is used in an SQL statement. This
92735   ** allows a schema that contains virtual tables to be loaded before
92736   ** the required virtual table implementations are registered.  */
92737   else {
92738     Table *pOld;
92739     Schema *pSchema = pTab->pSchema;
92740     const char *zName = pTab->zName;
92741     int nName = sqlite3Strlen30(zName);
92742     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
92743     if( pOld ){
92744       db->mallocFailed = 1;
92745       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
92746       return;
92747     }
92748     pSchema->db = pParse->db;
92749     pParse->pNewTable = 0;
92750   }
92751 }
92752
92753 /*
92754 ** The parser calls this routine when it sees the first token
92755 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
92756 */
92757 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
92758   addArgumentToVtab(pParse);
92759   pParse->sArg.z = 0;
92760   pParse->sArg.n = 0;
92761 }
92762
92763 /*
92764 ** The parser calls this routine for each token after the first token
92765 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
92766 */
92767 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
92768   Token *pArg = &pParse->sArg;
92769   if( pArg->z==0 ){
92770     pArg->z = p->z;
92771     pArg->n = p->n;
92772   }else{
92773     assert(pArg->z < p->z);
92774     pArg->n = (int)(&p->z[p->n] - pArg->z);
92775   }
92776 }
92777
92778 /*
92779 ** Invoke a virtual table constructor (either xCreate or xConnect). The
92780 ** pointer to the function to invoke is passed as the fourth parameter
92781 ** to this procedure.
92782 */
92783 static int vtabCallConstructor(
92784   sqlite3 *db, 
92785   Table *pTab,
92786   Module *pMod,
92787   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
92788   char **pzErr
92789 ){
92790   VTable *pVTable;
92791   int rc;
92792   const char *const*azArg = (const char *const*)pTab->azModuleArg;
92793   int nArg = pTab->nModuleArg;
92794   char *zErr = 0;
92795   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
92796
92797   if( !zModuleName ){
92798     return SQLITE_NOMEM;
92799   }
92800
92801   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
92802   if( !pVTable ){
92803     sqlite3DbFree(db, zModuleName);
92804     return SQLITE_NOMEM;
92805   }
92806   pVTable->db = db;
92807   pVTable->pMod = pMod;
92808
92809   assert( !db->pVTab );
92810   assert( xConstruct );
92811   db->pVTab = pTab;
92812
92813   /* Invoke the virtual table constructor */
92814   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
92815   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
92816
92817   if( SQLITE_OK!=rc ){
92818     if( zErr==0 ){
92819       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
92820     }else {
92821       *pzErr = sqlite3MPrintf(db, "%s", zErr);
92822       sqlite3DbFree(db, zErr);
92823     }
92824     sqlite3DbFree(db, pVTable);
92825   }else if( ALWAYS(pVTable->pVtab) ){
92826     /* Justification of ALWAYS():  A correct vtab constructor must allocate
92827     ** the sqlite3_vtab object if successful.  */
92828     pVTable->pVtab->pModule = pMod->pModule;
92829     pVTable->nRef = 1;
92830     if( db->pVTab ){
92831       const char *zFormat = "vtable constructor did not declare schema: %s";
92832       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
92833       sqlite3VtabUnlock(pVTable);
92834       rc = SQLITE_ERROR;
92835     }else{
92836       int iCol;
92837       /* If everything went according to plan, link the new VTable structure
92838       ** into the linked list headed by pTab->pVTable. Then loop through the 
92839       ** columns of the table to see if any of them contain the token "hidden".
92840       ** If so, set the Column.isHidden flag and remove the token from
92841       ** the type string.  */
92842       pVTable->pNext = pTab->pVTable;
92843       pTab->pVTable = pVTable;
92844
92845       for(iCol=0; iCol<pTab->nCol; iCol++){
92846         char *zType = pTab->aCol[iCol].zType;
92847         int nType;
92848         int i = 0;
92849         if( !zType ) continue;
92850         nType = sqlite3Strlen30(zType);
92851         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
92852           for(i=0; i<nType; i++){
92853             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
92854              && (zType[i+7]=='\0' || zType[i+7]==' ')
92855             ){
92856               i++;
92857               break;
92858             }
92859           }
92860         }
92861         if( i<nType ){
92862           int j;
92863           int nDel = 6 + (zType[i+6] ? 1 : 0);
92864           for(j=i; (j+nDel)<=nType; j++){
92865             zType[j] = zType[j+nDel];
92866           }
92867           if( zType[i]=='\0' && i>0 ){
92868             assert(zType[i-1]==' ');
92869             zType[i-1] = '\0';
92870           }
92871           pTab->aCol[iCol].isHidden = 1;
92872         }
92873       }
92874     }
92875   }
92876
92877   sqlite3DbFree(db, zModuleName);
92878   db->pVTab = 0;
92879   return rc;
92880 }
92881
92882 /*
92883 ** This function is invoked by the parser to call the xConnect() method
92884 ** of the virtual table pTab. If an error occurs, an error code is returned 
92885 ** and an error left in pParse.
92886 **
92887 ** This call is a no-op if table pTab is not a virtual table.
92888 */
92889 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
92890   sqlite3 *db = pParse->db;
92891   const char *zMod;
92892   Module *pMod;
92893   int rc;
92894
92895   assert( pTab );
92896   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
92897     return SQLITE_OK;
92898   }
92899
92900   /* Locate the required virtual table module */
92901   zMod = pTab->azModuleArg[0];
92902   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92903
92904   if( !pMod ){
92905     const char *zModule = pTab->azModuleArg[0];
92906     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
92907     rc = SQLITE_ERROR;
92908   }else{
92909     char *zErr = 0;
92910     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
92911     if( rc!=SQLITE_OK ){
92912       sqlite3ErrorMsg(pParse, "%s", zErr);
92913     }
92914     sqlite3DbFree(db, zErr);
92915   }
92916
92917   return rc;
92918 }
92919
92920 /*
92921 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
92922 */
92923 static int addToVTrans(sqlite3 *db, VTable *pVTab){
92924   const int ARRAY_INCR = 5;
92925
92926   /* Grow the sqlite3.aVTrans array if required */
92927   if( (db->nVTrans%ARRAY_INCR)==0 ){
92928     VTable **aVTrans;
92929     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
92930     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
92931     if( !aVTrans ){
92932       return SQLITE_NOMEM;
92933     }
92934     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
92935     db->aVTrans = aVTrans;
92936   }
92937
92938   /* Add pVtab to the end of sqlite3.aVTrans */
92939   db->aVTrans[db->nVTrans++] = pVTab;
92940   sqlite3VtabLock(pVTab);
92941   return SQLITE_OK;
92942 }
92943
92944 /*
92945 ** This function is invoked by the vdbe to call the xCreate method
92946 ** of the virtual table named zTab in database iDb. 
92947 **
92948 ** If an error occurs, *pzErr is set to point an an English language
92949 ** description of the error and an SQLITE_XXX error code is returned.
92950 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
92951 */
92952 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
92953   int rc = SQLITE_OK;
92954   Table *pTab;
92955   Module *pMod;
92956   const char *zMod;
92957
92958   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
92959   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
92960
92961   /* Locate the required virtual table module */
92962   zMod = pTab->azModuleArg[0];
92963   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92964
92965   /* If the module has been registered and includes a Create method, 
92966   ** invoke it now. If the module has not been registered, return an 
92967   ** error. Otherwise, do nothing.
92968   */
92969   if( !pMod ){
92970     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
92971     rc = SQLITE_ERROR;
92972   }else{
92973     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
92974   }
92975
92976   /* Justification of ALWAYS():  The xConstructor method is required to
92977   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
92978   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
92979       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
92980   }
92981
92982   return rc;
92983 }
92984
92985 /*
92986 ** This function is used to set the schema of a virtual table.  It is only
92987 ** valid to call this function from within the xCreate() or xConnect() of a
92988 ** virtual table module.
92989 */
92990 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
92991   Parse *pParse;
92992
92993   int rc = SQLITE_OK;
92994   Table *pTab;
92995   char *zErr = 0;
92996
92997   sqlite3_mutex_enter(db->mutex);
92998   pTab = db->pVTab;
92999   if( !pTab ){
93000     sqlite3Error(db, SQLITE_MISUSE, 0);
93001     sqlite3_mutex_leave(db->mutex);
93002     return SQLITE_MISUSE_BKPT;
93003   }
93004   assert( (pTab->tabFlags & TF_Virtual)!=0 );
93005
93006   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
93007   if( pParse==0 ){
93008     rc = SQLITE_NOMEM;
93009   }else{
93010     pParse->declareVtab = 1;
93011     pParse->db = db;
93012     pParse->nQueryLoop = 1;
93013   
93014     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
93015      && pParse->pNewTable
93016      && !db->mallocFailed
93017      && !pParse->pNewTable->pSelect
93018      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
93019     ){
93020       if( !pTab->aCol ){
93021         pTab->aCol = pParse->pNewTable->aCol;
93022         pTab->nCol = pParse->pNewTable->nCol;
93023         pParse->pNewTable->nCol = 0;
93024         pParse->pNewTable->aCol = 0;
93025       }
93026       db->pVTab = 0;
93027     }else{
93028       sqlite3Error(db, SQLITE_ERROR, zErr);
93029       sqlite3DbFree(db, zErr);
93030       rc = SQLITE_ERROR;
93031     }
93032     pParse->declareVtab = 0;
93033   
93034     if( pParse->pVdbe ){
93035       sqlite3VdbeFinalize(pParse->pVdbe);
93036     }
93037     sqlite3DeleteTable(pParse->pNewTable);
93038     sqlite3StackFree(db, pParse);
93039   }
93040
93041   assert( (rc&0xff)==rc );
93042   rc = sqlite3ApiExit(db, rc);
93043   sqlite3_mutex_leave(db->mutex);
93044   return rc;
93045 }
93046
93047 /*
93048 ** This function is invoked by the vdbe to call the xDestroy method
93049 ** of the virtual table named zTab in database iDb. This occurs
93050 ** when a DROP TABLE is mentioned.
93051 **
93052 ** This call is a no-op if zTab is not a virtual table.
93053 */
93054 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
93055   int rc = SQLITE_OK;
93056   Table *pTab;
93057
93058   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
93059   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
93060     VTable *p = vtabDisconnectAll(db, pTab);
93061
93062     assert( rc==SQLITE_OK );
93063     rc = p->pMod->pModule->xDestroy(p->pVtab);
93064
93065     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
93066     if( rc==SQLITE_OK ){
93067       assert( pTab->pVTable==p && p->pNext==0 );
93068       p->pVtab = 0;
93069       pTab->pVTable = 0;
93070       sqlite3VtabUnlock(p);
93071     }
93072   }
93073
93074   return rc;
93075 }
93076
93077 /*
93078 ** This function invokes either the xRollback or xCommit method
93079 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
93080 ** called is identified by the second argument, "offset", which is
93081 ** the offset of the method to call in the sqlite3_module structure.
93082 **
93083 ** The array is cleared after invoking the callbacks. 
93084 */
93085 static void callFinaliser(sqlite3 *db, int offset){
93086   int i;
93087   if( db->aVTrans ){
93088     for(i=0; i<db->nVTrans; i++){
93089       VTable *pVTab = db->aVTrans[i];
93090       sqlite3_vtab *p = pVTab->pVtab;
93091       if( p ){
93092         int (*x)(sqlite3_vtab *);
93093         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
93094         if( x ) x(p);
93095       }
93096       sqlite3VtabUnlock(pVTab);
93097     }
93098     sqlite3DbFree(db, db->aVTrans);
93099     db->nVTrans = 0;
93100     db->aVTrans = 0;
93101   }
93102 }
93103
93104 /*
93105 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
93106 ** array. Return the error code for the first error that occurs, or
93107 ** SQLITE_OK if all xSync operations are successful.
93108 **
93109 ** Set *pzErrmsg to point to a buffer that should be released using 
93110 ** sqlite3DbFree() containing an error message, if one is available.
93111 */
93112 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
93113   int i;
93114   int rc = SQLITE_OK;
93115   VTable **aVTrans = db->aVTrans;
93116
93117   db->aVTrans = 0;
93118   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
93119     int (*x)(sqlite3_vtab *);
93120     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
93121     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
93122       rc = x(pVtab);
93123       sqlite3DbFree(db, *pzErrmsg);
93124       *pzErrmsg = pVtab->zErrMsg;
93125       pVtab->zErrMsg = 0;
93126     }
93127   }
93128   db->aVTrans = aVTrans;
93129   return rc;
93130 }
93131
93132 /*
93133 ** Invoke the xRollback method of all virtual tables in the 
93134 ** sqlite3.aVTrans array. Then clear the array itself.
93135 */
93136 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
93137   callFinaliser(db, offsetof(sqlite3_module,xRollback));
93138   return SQLITE_OK;
93139 }
93140
93141 /*
93142 ** Invoke the xCommit method of all virtual tables in the 
93143 ** sqlite3.aVTrans array. Then clear the array itself.
93144 */
93145 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
93146   callFinaliser(db, offsetof(sqlite3_module,xCommit));
93147   return SQLITE_OK;
93148 }
93149
93150 /*
93151 ** If the virtual table pVtab supports the transaction interface
93152 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
93153 ** not currently open, invoke the xBegin method now.
93154 **
93155 ** If the xBegin call is successful, place the sqlite3_vtab pointer
93156 ** in the sqlite3.aVTrans array.
93157 */
93158 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
93159   int rc = SQLITE_OK;
93160   const sqlite3_module *pModule;
93161
93162   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
93163   ** than zero, then this function is being called from within a
93164   ** virtual module xSync() callback. It is illegal to write to 
93165   ** virtual module tables in this case, so return SQLITE_LOCKED.
93166   */
93167   if( sqlite3VtabInSync(db) ){
93168     return SQLITE_LOCKED;
93169   }
93170   if( !pVTab ){
93171     return SQLITE_OK;
93172   } 
93173   pModule = pVTab->pVtab->pModule;
93174
93175   if( pModule->xBegin ){
93176     int i;
93177
93178
93179     /* If pVtab is already in the aVTrans array, return early */
93180     for(i=0; i<db->nVTrans; i++){
93181       if( db->aVTrans[i]==pVTab ){
93182         return SQLITE_OK;
93183       }
93184     }
93185
93186     /* Invoke the xBegin method */
93187     rc = pModule->xBegin(pVTab->pVtab);
93188     if( rc==SQLITE_OK ){
93189       rc = addToVTrans(db, pVTab);
93190     }
93191   }
93192   return rc;
93193 }
93194
93195 /*
93196 ** The first parameter (pDef) is a function implementation.  The
93197 ** second parameter (pExpr) is the first argument to this function.
93198 ** If pExpr is a column in a virtual table, then let the virtual
93199 ** table implementation have an opportunity to overload the function.
93200 **
93201 ** This routine is used to allow virtual table implementations to
93202 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
93203 **
93204 ** Return either the pDef argument (indicating no change) or a 
93205 ** new FuncDef structure that is marked as ephemeral using the
93206 ** SQLITE_FUNC_EPHEM flag.
93207 */
93208 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
93209   sqlite3 *db,    /* Database connection for reporting malloc problems */
93210   FuncDef *pDef,  /* Function to possibly overload */
93211   int nArg,       /* Number of arguments to the function */
93212   Expr *pExpr     /* First argument to the function */
93213 ){
93214   Table *pTab;
93215   sqlite3_vtab *pVtab;
93216   sqlite3_module *pMod;
93217   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
93218   void *pArg = 0;
93219   FuncDef *pNew;
93220   int rc = 0;
93221   char *zLowerName;
93222   unsigned char *z;
93223
93224
93225   /* Check to see the left operand is a column in a virtual table */
93226   if( NEVER(pExpr==0) ) return pDef;
93227   if( pExpr->op!=TK_COLUMN ) return pDef;
93228   pTab = pExpr->pTab;
93229   if( NEVER(pTab==0) ) return pDef;
93230   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
93231   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
93232   assert( pVtab!=0 );
93233   assert( pVtab->pModule!=0 );
93234   pMod = (sqlite3_module *)pVtab->pModule;
93235   if( pMod->xFindFunction==0 ) return pDef;
93236  
93237   /* Call the xFindFunction method on the virtual table implementation
93238   ** to see if the implementation wants to overload this function 
93239   */
93240   zLowerName = sqlite3DbStrDup(db, pDef->zName);
93241   if( zLowerName ){
93242     for(z=(unsigned char*)zLowerName; *z; z++){
93243       *z = sqlite3UpperToLower[*z];
93244     }
93245     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
93246     sqlite3DbFree(db, zLowerName);
93247   }
93248   if( rc==0 ){
93249     return pDef;
93250   }
93251
93252   /* Create a new ephemeral function definition for the overloaded
93253   ** function */
93254   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
93255                              + sqlite3Strlen30(pDef->zName) + 1);
93256   if( pNew==0 ){
93257     return pDef;
93258   }
93259   *pNew = *pDef;
93260   pNew->zName = (char *)&pNew[1];
93261   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
93262   pNew->xFunc = xFunc;
93263   pNew->pUserData = pArg;
93264   pNew->flags |= SQLITE_FUNC_EPHEM;
93265   return pNew;
93266 }
93267
93268 /*
93269 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
93270 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
93271 ** array if it is missing.  If pTab is already in the array, this routine
93272 ** is a no-op.
93273 */
93274 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
93275   Parse *pToplevel = sqlite3ParseToplevel(pParse);
93276   int i, n;
93277   Table **apVtabLock;
93278
93279   assert( IsVirtual(pTab) );
93280   for(i=0; i<pToplevel->nVtabLock; i++){
93281     if( pTab==pToplevel->apVtabLock[i] ) return;
93282   }
93283   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
93284   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
93285   if( apVtabLock ){
93286     pToplevel->apVtabLock = apVtabLock;
93287     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
93288   }else{
93289     pToplevel->db->mallocFailed = 1;
93290   }
93291 }
93292
93293 #endif /* SQLITE_OMIT_VIRTUALTABLE */
93294
93295 /************** End of vtab.c ************************************************/
93296 /************** Begin file where.c *******************************************/
93297 /*
93298 ** 2001 September 15
93299 **
93300 ** The author disclaims copyright to this source code.  In place of
93301 ** a legal notice, here is a blessing:
93302 **
93303 **    May you do good and not evil.
93304 **    May you find forgiveness for yourself and forgive others.
93305 **    May you share freely, never taking more than you give.
93306 **
93307 *************************************************************************
93308 ** This module contains C code that generates VDBE code used to process
93309 ** the WHERE clause of SQL statements.  This module is responsible for
93310 ** generating the code that loops through a table looking for applicable
93311 ** rows.  Indices are selected and used to speed the search when doing
93312 ** so is applicable.  Because this module is responsible for selecting
93313 ** indices, you might also think of this module as the "query optimizer".
93314 */
93315
93316 /*
93317 ** Trace output macros
93318 */
93319 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
93320 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
93321 #endif
93322 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
93323 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
93324 #else
93325 # define WHERETRACE(X)
93326 #endif
93327
93328 /* Forward reference
93329 */
93330 typedef struct WhereClause WhereClause;
93331 typedef struct WhereMaskSet WhereMaskSet;
93332 typedef struct WhereOrInfo WhereOrInfo;
93333 typedef struct WhereAndInfo WhereAndInfo;
93334 typedef struct WhereCost WhereCost;
93335
93336 /*
93337 ** The query generator uses an array of instances of this structure to
93338 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
93339 ** clause subexpression is separated from the others by AND operators,
93340 ** usually, or sometimes subexpressions separated by OR.
93341 **
93342 ** All WhereTerms are collected into a single WhereClause structure.  
93343 ** The following identity holds:
93344 **
93345 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
93346 **
93347 ** When a term is of the form:
93348 **
93349 **              X <op> <expr>
93350 **
93351 ** where X is a column name and <op> is one of certain operators,
93352 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
93353 ** cursor number and column number for X.  WhereTerm.eOperator records
93354 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
93355 ** use of a bitmask encoding for the operator allows us to search
93356 ** quickly for terms that match any of several different operators.
93357 **
93358 ** A WhereTerm might also be two or more subterms connected by OR:
93359 **
93360 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
93361 **
93362 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
93363 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
93364 ** is collected about the
93365 **
93366 ** If a term in the WHERE clause does not match either of the two previous
93367 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
93368 ** to the original subexpression content and wtFlags is set up appropriately
93369 ** but no other fields in the WhereTerm object are meaningful.
93370 **
93371 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
93372 ** but they do so indirectly.  A single WhereMaskSet structure translates
93373 ** cursor number into bits and the translated bit is stored in the prereq
93374 ** fields.  The translation is used in order to maximize the number of
93375 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
93376 ** spread out over the non-negative integers.  For example, the cursor
93377 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
93378 ** translates these sparse cursor numbers into consecutive integers
93379 ** beginning with 0 in order to make the best possible use of the available
93380 ** bits in the Bitmask.  So, in the example above, the cursor numbers
93381 ** would be mapped into integers 0 through 7.
93382 **
93383 ** The number of terms in a join is limited by the number of bits
93384 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
93385 ** is only able to process joins with 64 or fewer tables.
93386 */
93387 typedef struct WhereTerm WhereTerm;
93388 struct WhereTerm {
93389   Expr *pExpr;            /* Pointer to the subexpression that is this term */
93390   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
93391   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
93392   union {
93393     int leftColumn;         /* Column number of X in "X <op> <expr>" */
93394     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
93395     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
93396   } u;
93397   u16 eOperator;          /* A WO_xx value describing <op> */
93398   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
93399   u8 nChild;              /* Number of children that must disable us */
93400   WhereClause *pWC;       /* The clause this term is part of */
93401   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
93402   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
93403 };
93404
93405 /*
93406 ** Allowed values of WhereTerm.wtFlags
93407 */
93408 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
93409 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
93410 #define TERM_CODED      0x04   /* This term is already coded */
93411 #define TERM_COPIED     0x08   /* Has a child */
93412 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
93413 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
93414 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
93415
93416 /*
93417 ** An instance of the following structure holds all information about a
93418 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
93419 */
93420 struct WhereClause {
93421   Parse *pParse;           /* The parser context */
93422   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
93423   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
93424   u8 op;                   /* Split operator.  TK_AND or TK_OR */
93425   int nTerm;               /* Number of terms */
93426   int nSlot;               /* Number of entries in a[] */
93427   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
93428 #if defined(SQLITE_SMALL_STACK)
93429   WhereTerm aStatic[1];    /* Initial static space for a[] */
93430 #else
93431   WhereTerm aStatic[8];    /* Initial static space for a[] */
93432 #endif
93433 };
93434
93435 /*
93436 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
93437 ** a dynamically allocated instance of the following structure.
93438 */
93439 struct WhereOrInfo {
93440   WhereClause wc;          /* Decomposition into subterms */
93441   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
93442 };
93443
93444 /*
93445 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
93446 ** a dynamically allocated instance of the following structure.
93447 */
93448 struct WhereAndInfo {
93449   WhereClause wc;          /* The subexpression broken out */
93450 };
93451
93452 /*
93453 ** An instance of the following structure keeps track of a mapping
93454 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
93455 **
93456 ** The VDBE cursor numbers are small integers contained in 
93457 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
93458 ** clause, the cursor numbers might not begin with 0 and they might
93459 ** contain gaps in the numbering sequence.  But we want to make maximum
93460 ** use of the bits in our bitmasks.  This structure provides a mapping
93461 ** from the sparse cursor numbers into consecutive integers beginning
93462 ** with 0.
93463 **
93464 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
93465 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
93466 **
93467 ** For example, if the WHERE clause expression used these VDBE
93468 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
93469 ** would map those cursor numbers into bits 0 through 5.
93470 **
93471 ** Note that the mapping is not necessarily ordered.  In the example
93472 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
93473 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
93474 ** does not really matter.  What is important is that sparse cursor
93475 ** numbers all get mapped into bit numbers that begin with 0 and contain
93476 ** no gaps.
93477 */
93478 struct WhereMaskSet {
93479   int n;                        /* Number of assigned cursor values */
93480   int ix[BMS];                  /* Cursor assigned to each bit */
93481 };
93482
93483 /*
93484 ** A WhereCost object records a lookup strategy and the estimated
93485 ** cost of pursuing that strategy.
93486 */
93487 struct WhereCost {
93488   WherePlan plan;    /* The lookup strategy */
93489   double rCost;      /* Overall cost of pursuing this search strategy */
93490   double nRow;       /* Estimated number of output rows */
93491   Bitmask used;      /* Bitmask of cursors used by this plan */
93492 };
93493
93494 /*
93495 ** Bitmasks for the operators that indices are able to exploit.  An
93496 ** OR-ed combination of these values can be used when searching for
93497 ** terms in the where clause.
93498 */
93499 #define WO_IN     0x001
93500 #define WO_EQ     0x002
93501 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
93502 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
93503 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
93504 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
93505 #define WO_MATCH  0x040
93506 #define WO_ISNULL 0x080
93507 #define WO_OR     0x100       /* Two or more OR-connected terms */
93508 #define WO_AND    0x200       /* Two or more AND-connected terms */
93509
93510 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
93511 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
93512
93513 /*
93514 ** Value for wsFlags returned by bestIndex() and stored in
93515 ** WhereLevel.wsFlags.  These flags determine which search
93516 ** strategies are appropriate.
93517 **
93518 ** The least significant 12 bits is reserved as a mask for WO_ values above.
93519 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
93520 ** But if the table is the right table of a left join, WhereLevel.wsFlags
93521 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
93522 ** the "op" parameter to findTerm when we are resolving equality constraints.
93523 ** ISNULL constraints will then not be used on the right table of a left
93524 ** join.  Tickets #2177 and #2189.
93525 */
93526 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
93527 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
93528 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
93529 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
93530 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
93531 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
93532 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
93533 #define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
93534 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
93535 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
93536 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
93537 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
93538 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
93539 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
93540 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
93541 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
93542 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
93543 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
93544
93545 /*
93546 ** Initialize a preallocated WhereClause structure.
93547 */
93548 static void whereClauseInit(
93549   WhereClause *pWC,        /* The WhereClause to be initialized */
93550   Parse *pParse,           /* The parsing context */
93551   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
93552 ){
93553   pWC->pParse = pParse;
93554   pWC->pMaskSet = pMaskSet;
93555   pWC->nTerm = 0;
93556   pWC->nSlot = ArraySize(pWC->aStatic);
93557   pWC->a = pWC->aStatic;
93558   pWC->vmask = 0;
93559 }
93560
93561 /* Forward reference */
93562 static void whereClauseClear(WhereClause*);
93563
93564 /*
93565 ** Deallocate all memory associated with a WhereOrInfo object.
93566 */
93567 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
93568   whereClauseClear(&p->wc);
93569   sqlite3DbFree(db, p);
93570 }
93571
93572 /*
93573 ** Deallocate all memory associated with a WhereAndInfo object.
93574 */
93575 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
93576   whereClauseClear(&p->wc);
93577   sqlite3DbFree(db, p);
93578 }
93579
93580 /*
93581 ** Deallocate a WhereClause structure.  The WhereClause structure
93582 ** itself is not freed.  This routine is the inverse of whereClauseInit().
93583 */
93584 static void whereClauseClear(WhereClause *pWC){
93585   int i;
93586   WhereTerm *a;
93587   sqlite3 *db = pWC->pParse->db;
93588   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
93589     if( a->wtFlags & TERM_DYNAMIC ){
93590       sqlite3ExprDelete(db, a->pExpr);
93591     }
93592     if( a->wtFlags & TERM_ORINFO ){
93593       whereOrInfoDelete(db, a->u.pOrInfo);
93594     }else if( a->wtFlags & TERM_ANDINFO ){
93595       whereAndInfoDelete(db, a->u.pAndInfo);
93596     }
93597   }
93598   if( pWC->a!=pWC->aStatic ){
93599     sqlite3DbFree(db, pWC->a);
93600   }
93601 }
93602
93603 /*
93604 ** Add a single new WhereTerm entry to the WhereClause object pWC.
93605 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
93606 ** The index in pWC->a[] of the new WhereTerm is returned on success.
93607 ** 0 is returned if the new WhereTerm could not be added due to a memory
93608 ** allocation error.  The memory allocation failure will be recorded in
93609 ** the db->mallocFailed flag so that higher-level functions can detect it.
93610 **
93611 ** This routine will increase the size of the pWC->a[] array as necessary.
93612 **
93613 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
93614 ** for freeing the expression p is assumed by the WhereClause object pWC.
93615 ** This is true even if this routine fails to allocate a new WhereTerm.
93616 **
93617 ** WARNING:  This routine might reallocate the space used to store
93618 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
93619 ** calling this routine.  Such pointers may be reinitialized by referencing
93620 ** the pWC->a[] array.
93621 */
93622 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
93623   WhereTerm *pTerm;
93624   int idx;
93625   if( pWC->nTerm>=pWC->nSlot ){
93626     WhereTerm *pOld = pWC->a;
93627     sqlite3 *db = pWC->pParse->db;
93628     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
93629     if( pWC->a==0 ){
93630       if( wtFlags & TERM_DYNAMIC ){
93631         sqlite3ExprDelete(db, p);
93632       }
93633       pWC->a = pOld;
93634       return 0;
93635     }
93636     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
93637     if( pOld!=pWC->aStatic ){
93638       sqlite3DbFree(db, pOld);
93639     }
93640     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
93641   }
93642   pTerm = &pWC->a[idx = pWC->nTerm++];
93643   pTerm->pExpr = p;
93644   pTerm->wtFlags = wtFlags;
93645   pTerm->pWC = pWC;
93646   pTerm->iParent = -1;
93647   return idx;
93648 }
93649
93650 /*
93651 ** This routine identifies subexpressions in the WHERE clause where
93652 ** each subexpression is separated by the AND operator or some other
93653 ** operator specified in the op parameter.  The WhereClause structure
93654 ** is filled with pointers to subexpressions.  For example:
93655 **
93656 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
93657 **           \________/     \_______________/     \________________/
93658 **            slot[0]            slot[1]               slot[2]
93659 **
93660 ** The original WHERE clause in pExpr is unaltered.  All this routine
93661 ** does is make slot[] entries point to substructure within pExpr.
93662 **
93663 ** In the previous sentence and in the diagram, "slot[]" refers to
93664 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
93665 ** all terms of the WHERE clause.
93666 */
93667 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
93668   pWC->op = (u8)op;
93669   if( pExpr==0 ) return;
93670   if( pExpr->op!=op ){
93671     whereClauseInsert(pWC, pExpr, 0);
93672   }else{
93673     whereSplit(pWC, pExpr->pLeft, op);
93674     whereSplit(pWC, pExpr->pRight, op);
93675   }
93676 }
93677
93678 /*
93679 ** Initialize an expression mask set (a WhereMaskSet object)
93680 */
93681 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
93682
93683 /*
93684 ** Return the bitmask for the given cursor number.  Return 0 if
93685 ** iCursor is not in the set.
93686 */
93687 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
93688   int i;
93689   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
93690   for(i=0; i<pMaskSet->n; i++){
93691     if( pMaskSet->ix[i]==iCursor ){
93692       return ((Bitmask)1)<<i;
93693     }
93694   }
93695   return 0;
93696 }
93697
93698 /*
93699 ** Create a new mask for cursor iCursor.
93700 **
93701 ** There is one cursor per table in the FROM clause.  The number of
93702 ** tables in the FROM clause is limited by a test early in the
93703 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
93704 ** array will never overflow.
93705 */
93706 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
93707   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
93708   pMaskSet->ix[pMaskSet->n++] = iCursor;
93709 }
93710
93711 /*
93712 ** This routine walks (recursively) an expression tree and generates
93713 ** a bitmask indicating which tables are used in that expression
93714 ** tree.
93715 **
93716 ** In order for this routine to work, the calling function must have
93717 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
93718 ** the header comment on that routine for additional information.
93719 ** The sqlite3ResolveExprNames() routines looks for column names and
93720 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
93721 ** the VDBE cursor number of the table.  This routine just has to
93722 ** translate the cursor numbers into bitmask values and OR all
93723 ** the bitmasks together.
93724 */
93725 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
93726 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
93727 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
93728   Bitmask mask = 0;
93729   if( p==0 ) return 0;
93730   if( p->op==TK_COLUMN ){
93731     mask = getMask(pMaskSet, p->iTable);
93732     return mask;
93733   }
93734   mask = exprTableUsage(pMaskSet, p->pRight);
93735   mask |= exprTableUsage(pMaskSet, p->pLeft);
93736   if( ExprHasProperty(p, EP_xIsSelect) ){
93737     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
93738   }else{
93739     mask |= exprListTableUsage(pMaskSet, p->x.pList);
93740   }
93741   return mask;
93742 }
93743 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
93744   int i;
93745   Bitmask mask = 0;
93746   if( pList ){
93747     for(i=0; i<pList->nExpr; i++){
93748       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
93749     }
93750   }
93751   return mask;
93752 }
93753 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
93754   Bitmask mask = 0;
93755   while( pS ){
93756     mask |= exprListTableUsage(pMaskSet, pS->pEList);
93757     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
93758     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
93759     mask |= exprTableUsage(pMaskSet, pS->pWhere);
93760     mask |= exprTableUsage(pMaskSet, pS->pHaving);
93761     pS = pS->pPrior;
93762   }
93763   return mask;
93764 }
93765
93766 /*
93767 ** Return TRUE if the given operator is one of the operators that is
93768 ** allowed for an indexable WHERE clause term.  The allowed operators are
93769 ** "=", "<", ">", "<=", ">=", and "IN".
93770 */
93771 static int allowedOp(int op){
93772   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
93773   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
93774   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
93775   assert( TK_GE==TK_EQ+4 );
93776   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
93777 }
93778
93779 /*
93780 ** Swap two objects of type TYPE.
93781 */
93782 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
93783
93784 /*
93785 ** Commute a comparison operator.  Expressions of the form "X op Y"
93786 ** are converted into "Y op X".
93787 **
93788 ** If a collation sequence is associated with either the left or right
93789 ** side of the comparison, it remains associated with the same side after
93790 ** the commutation. So "Y collate NOCASE op X" becomes 
93791 ** "X collate NOCASE op Y". This is because any collation sequence on
93792 ** the left hand side of a comparison overrides any collation sequence 
93793 ** attached to the right. For the same reason the EP_ExpCollate flag
93794 ** is not commuted.
93795 */
93796 static void exprCommute(Parse *pParse, Expr *pExpr){
93797   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
93798   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
93799   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
93800   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
93801   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
93802   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
93803   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
93804   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
93805   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
93806   if( pExpr->op>=TK_GT ){
93807     assert( TK_LT==TK_GT+2 );
93808     assert( TK_GE==TK_LE+2 );
93809     assert( TK_GT>TK_EQ );
93810     assert( TK_GT<TK_LE );
93811     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
93812     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
93813   }
93814 }
93815
93816 /*
93817 ** Translate from TK_xx operator to WO_xx bitmask.
93818 */
93819 static u16 operatorMask(int op){
93820   u16 c;
93821   assert( allowedOp(op) );
93822   if( op==TK_IN ){
93823     c = WO_IN;
93824   }else if( op==TK_ISNULL ){
93825     c = WO_ISNULL;
93826   }else{
93827     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
93828     c = (u16)(WO_EQ<<(op-TK_EQ));
93829   }
93830   assert( op!=TK_ISNULL || c==WO_ISNULL );
93831   assert( op!=TK_IN || c==WO_IN );
93832   assert( op!=TK_EQ || c==WO_EQ );
93833   assert( op!=TK_LT || c==WO_LT );
93834   assert( op!=TK_LE || c==WO_LE );
93835   assert( op!=TK_GT || c==WO_GT );
93836   assert( op!=TK_GE || c==WO_GE );
93837   return c;
93838 }
93839
93840 /*
93841 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
93842 ** where X is a reference to the iColumn of table iCur and <op> is one of
93843 ** the WO_xx operator codes specified by the op parameter.
93844 ** Return a pointer to the term.  Return 0 if not found.
93845 */
93846 static WhereTerm *findTerm(
93847   WhereClause *pWC,     /* The WHERE clause to be searched */
93848   int iCur,             /* Cursor number of LHS */
93849   int iColumn,          /* Column number of LHS */
93850   Bitmask notReady,     /* RHS must not overlap with this mask */
93851   u32 op,               /* Mask of WO_xx values describing operator */
93852   Index *pIdx           /* Must be compatible with this index, if not NULL */
93853 ){
93854   WhereTerm *pTerm;
93855   int k;
93856   assert( iCur>=0 );
93857   op &= WO_ALL;
93858   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
93859     if( pTerm->leftCursor==iCur
93860        && (pTerm->prereqRight & notReady)==0
93861        && pTerm->u.leftColumn==iColumn
93862        && (pTerm->eOperator & op)!=0
93863     ){
93864       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
93865         Expr *pX = pTerm->pExpr;
93866         CollSeq *pColl;
93867         char idxaff;
93868         int j;
93869         Parse *pParse = pWC->pParse;
93870
93871         idxaff = pIdx->pTable->aCol[iColumn].affinity;
93872         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
93873
93874         /* Figure out the collation sequence required from an index for
93875         ** it to be useful for optimising expression pX. Store this
93876         ** value in variable pColl.
93877         */
93878         assert(pX->pLeft);
93879         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
93880         assert(pColl || pParse->nErr);
93881
93882         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
93883           if( NEVER(j>=pIdx->nColumn) ) return 0;
93884         }
93885         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
93886       }
93887       return pTerm;
93888     }
93889   }
93890   return 0;
93891 }
93892
93893 /* Forward reference */
93894 static void exprAnalyze(SrcList*, WhereClause*, int);
93895
93896 /*
93897 ** Call exprAnalyze on all terms in a WHERE clause.  
93898 **
93899 **
93900 */
93901 static void exprAnalyzeAll(
93902   SrcList *pTabList,       /* the FROM clause */
93903   WhereClause *pWC         /* the WHERE clause to be analyzed */
93904 ){
93905   int i;
93906   for(i=pWC->nTerm-1; i>=0; i--){
93907     exprAnalyze(pTabList, pWC, i);
93908   }
93909 }
93910
93911 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
93912 /*
93913 ** Check to see if the given expression is a LIKE or GLOB operator that
93914 ** can be optimized using inequality constraints.  Return TRUE if it is
93915 ** so and false if not.
93916 **
93917 ** In order for the operator to be optimizible, the RHS must be a string
93918 ** literal that does not begin with a wildcard.  
93919 */
93920 static int isLikeOrGlob(
93921   Parse *pParse,    /* Parsing and code generating context */
93922   Expr *pExpr,      /* Test this expression */
93923   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
93924   int *pisComplete, /* True if the only wildcard is % in the last character */
93925   int *pnoCase      /* True if uppercase is equivalent to lowercase */
93926 ){
93927   const char *z = 0;         /* String on RHS of LIKE operator */
93928   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
93929   ExprList *pList;           /* List of operands to the LIKE operator */
93930   int c;                     /* One character in z[] */
93931   int cnt;                   /* Number of non-wildcard prefix characters */
93932   char wc[3];                /* Wildcard characters */
93933   CollSeq *pColl;            /* Collating sequence for LHS */
93934   sqlite3 *db = pParse->db;  /* Database connection */
93935   sqlite3_value *pVal = 0;
93936   int op;                    /* Opcode of pRight */
93937
93938   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
93939     return 0;
93940   }
93941 #ifdef SQLITE_EBCDIC
93942   if( *pnoCase ) return 0;
93943 #endif
93944   pList = pExpr->x.pList;
93945   pLeft = pList->a[1].pExpr;
93946   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
93947     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
93948     ** be the name of an indexed column with TEXT affinity. */
93949     return 0;
93950   }
93951   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
93952   pColl = sqlite3ExprCollSeq(pParse, pLeft);
93953   if( pColl==0 ) return 0;  /* Happens when LHS has an undefined collation */
93954   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
93955       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
93956     /* IMP: R-09003-32046 For the GLOB operator, the column must use the
93957     ** default BINARY collating sequence.
93958     ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
93959     ** is enabled then the column must use the default BINARY collating
93960     ** sequence, or if case_sensitive_like mode is disabled then the column
93961     ** must use the built-in NOCASE collating sequence.
93962     */
93963     return 0;
93964   }
93965
93966   pRight = pList->a[0].pExpr;
93967   op = pRight->op;
93968   if( op==TK_REGISTER ){
93969     op = pRight->op2;
93970   }
93971   if( op==TK_VARIABLE ){
93972     Vdbe *pReprepare = pParse->pReprepare;
93973     pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
93974     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
93975       z = (char *)sqlite3_value_text(pVal);
93976     }
93977     sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
93978     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
93979   }else if( op==TK_STRING ){
93980     z = pRight->u.zToken;
93981   }
93982   if( z ){
93983     cnt = 0;
93984     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
93985       cnt++;
93986     }
93987     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
93988       Expr *pPrefix;
93989       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
93990       pPrefix = sqlite3Expr(db, TK_STRING, z);
93991       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
93992       *ppPrefix = pPrefix;
93993       if( op==TK_VARIABLE ){
93994         Vdbe *v = pParse->pVdbe;
93995         sqlite3VdbeSetVarmask(v, pRight->iColumn);
93996         if( *pisComplete && pRight->u.zToken[1] ){
93997           /* If the rhs of the LIKE expression is a variable, and the current
93998           ** value of the variable means there is no need to invoke the LIKE
93999           ** function, then no OP_Variable will be added to the program.
94000           ** This causes problems for the sqlite3_bind_parameter_name()
94001           ** API. To workaround them, add a dummy OP_Variable here.
94002           */ 
94003           int r1 = sqlite3GetTempReg(pParse);
94004           sqlite3ExprCodeTarget(pParse, pRight, r1);
94005           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
94006           sqlite3ReleaseTempReg(pParse, r1);
94007         }
94008       }
94009     }else{
94010       z = 0;
94011     }
94012   }
94013
94014   sqlite3ValueFree(pVal);
94015   return (z!=0);
94016 }
94017 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
94018
94019
94020 #ifndef SQLITE_OMIT_VIRTUALTABLE
94021 /*
94022 ** Check to see if the given expression is of the form
94023 **
94024 **         column MATCH expr
94025 **
94026 ** If it is then return TRUE.  If not, return FALSE.
94027 */
94028 static int isMatchOfColumn(
94029   Expr *pExpr      /* Test this expression */
94030 ){
94031   ExprList *pList;
94032
94033   if( pExpr->op!=TK_FUNCTION ){
94034     return 0;
94035   }
94036   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
94037     return 0;
94038   }
94039   pList = pExpr->x.pList;
94040   if( pList->nExpr!=2 ){
94041     return 0;
94042   }
94043   if( pList->a[1].pExpr->op != TK_COLUMN ){
94044     return 0;
94045   }
94046   return 1;
94047 }
94048 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94049
94050 /*
94051 ** If the pBase expression originated in the ON or USING clause of
94052 ** a join, then transfer the appropriate markings over to derived.
94053 */
94054 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
94055   pDerived->flags |= pBase->flags & EP_FromJoin;
94056   pDerived->iRightJoinTable = pBase->iRightJoinTable;
94057 }
94058
94059 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94060 /*
94061 ** Analyze a term that consists of two or more OR-connected
94062 ** subterms.  So in:
94063 **
94064 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
94065 **                          ^^^^^^^^^^^^^^^^^^^^
94066 **
94067 ** This routine analyzes terms such as the middle term in the above example.
94068 ** A WhereOrTerm object is computed and attached to the term under
94069 ** analysis, regardless of the outcome of the analysis.  Hence:
94070 **
94071 **     WhereTerm.wtFlags   |=  TERM_ORINFO
94072 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
94073 **
94074 ** The term being analyzed must have two or more of OR-connected subterms.
94075 ** A single subterm might be a set of AND-connected sub-subterms.
94076 ** Examples of terms under analysis:
94077 **
94078 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
94079 **     (B)     x=expr1 OR expr2=x OR x=expr3
94080 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
94081 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
94082 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
94083 **
94084 ** CASE 1:
94085 **
94086 ** If all subterms are of the form T.C=expr for some single column of C
94087 ** a single table T (as shown in example B above) then create a new virtual
94088 ** term that is an equivalent IN expression.  In other words, if the term
94089 ** being analyzed is:
94090 **
94091 **      x = expr1  OR  expr2 = x  OR  x = expr3
94092 **
94093 ** then create a new virtual term like this:
94094 **
94095 **      x IN (expr1,expr2,expr3)
94096 **
94097 ** CASE 2:
94098 **
94099 ** If all subterms are indexable by a single table T, then set
94100 **
94101 **     WhereTerm.eOperator              =  WO_OR
94102 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
94103 **
94104 ** A subterm is "indexable" if it is of the form
94105 ** "T.C <op> <expr>" where C is any column of table T and 
94106 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
94107 ** A subterm is also indexable if it is an AND of two or more
94108 ** subsubterms at least one of which is indexable.  Indexable AND 
94109 ** subterms have their eOperator set to WO_AND and they have
94110 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
94111 **
94112 ** From another point of view, "indexable" means that the subterm could
94113 ** potentially be used with an index if an appropriate index exists.
94114 ** This analysis does not consider whether or not the index exists; that
94115 ** is something the bestIndex() routine will determine.  This analysis
94116 ** only looks at whether subterms appropriate for indexing exist.
94117 **
94118 ** All examples A through E above all satisfy case 2.  But if a term
94119 ** also statisfies case 1 (such as B) we know that the optimizer will
94120 ** always prefer case 1, so in that case we pretend that case 2 is not
94121 ** satisfied.
94122 **
94123 ** It might be the case that multiple tables are indexable.  For example,
94124 ** (E) above is indexable on tables P, Q, and R.
94125 **
94126 ** Terms that satisfy case 2 are candidates for lookup by using
94127 ** separate indices to find rowids for each subterm and composing
94128 ** the union of all rowids using a RowSet object.  This is similar
94129 ** to "bitmap indices" in other database engines.
94130 **
94131 ** OTHERWISE:
94132 **
94133 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
94134 ** zero.  This term is not useful for search.
94135 */
94136 static void exprAnalyzeOrTerm(
94137   SrcList *pSrc,            /* the FROM clause */
94138   WhereClause *pWC,         /* the complete WHERE clause */
94139   int idxTerm               /* Index of the OR-term to be analyzed */
94140 ){
94141   Parse *pParse = pWC->pParse;            /* Parser context */
94142   sqlite3 *db = pParse->db;               /* Database connection */
94143   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
94144   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
94145   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
94146   int i;                                  /* Loop counters */
94147   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
94148   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
94149   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
94150   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
94151   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
94152
94153   /*
94154   ** Break the OR clause into its separate subterms.  The subterms are
94155   ** stored in a WhereClause structure containing within the WhereOrInfo
94156   ** object that is attached to the original OR clause term.
94157   */
94158   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
94159   assert( pExpr->op==TK_OR );
94160   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
94161   if( pOrInfo==0 ) return;
94162   pTerm->wtFlags |= TERM_ORINFO;
94163   pOrWc = &pOrInfo->wc;
94164   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
94165   whereSplit(pOrWc, pExpr, TK_OR);
94166   exprAnalyzeAll(pSrc, pOrWc);
94167   if( db->mallocFailed ) return;
94168   assert( pOrWc->nTerm>=2 );
94169
94170   /*
94171   ** Compute the set of tables that might satisfy cases 1 or 2.
94172   */
94173   indexable = ~(Bitmask)0;
94174   chngToIN = ~(pWC->vmask);
94175   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
94176     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
94177       WhereAndInfo *pAndInfo;
94178       assert( pOrTerm->eOperator==0 );
94179       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
94180       chngToIN = 0;
94181       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
94182       if( pAndInfo ){
94183         WhereClause *pAndWC;
94184         WhereTerm *pAndTerm;
94185         int j;
94186         Bitmask b = 0;
94187         pOrTerm->u.pAndInfo = pAndInfo;
94188         pOrTerm->wtFlags |= TERM_ANDINFO;
94189         pOrTerm->eOperator = WO_AND;
94190         pAndWC = &pAndInfo->wc;
94191         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
94192         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
94193         exprAnalyzeAll(pSrc, pAndWC);
94194         testcase( db->mallocFailed );
94195         if( !db->mallocFailed ){
94196           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
94197             assert( pAndTerm->pExpr );
94198             if( allowedOp(pAndTerm->pExpr->op) ){
94199               b |= getMask(pMaskSet, pAndTerm->leftCursor);
94200             }
94201           }
94202         }
94203         indexable &= b;
94204       }
94205     }else if( pOrTerm->wtFlags & TERM_COPIED ){
94206       /* Skip this term for now.  We revisit it when we process the
94207       ** corresponding TERM_VIRTUAL term */
94208     }else{
94209       Bitmask b;
94210       b = getMask(pMaskSet, pOrTerm->leftCursor);
94211       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
94212         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
94213         b |= getMask(pMaskSet, pOther->leftCursor);
94214       }
94215       indexable &= b;
94216       if( pOrTerm->eOperator!=WO_EQ ){
94217         chngToIN = 0;
94218       }else{
94219         chngToIN &= b;
94220       }
94221     }
94222   }
94223
94224   /*
94225   ** Record the set of tables that satisfy case 2.  The set might be
94226   ** empty.
94227   */
94228   pOrInfo->indexable = indexable;
94229   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
94230
94231   /*
94232   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
94233   ** we have to do some additional checking to see if case 1 really
94234   ** is satisfied.
94235   **
94236   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
94237   ** that there is no possibility of transforming the OR clause into an
94238   ** IN operator because one or more terms in the OR clause contain
94239   ** something other than == on a column in the single table.  The 1-bit
94240   ** case means that every term of the OR clause is of the form
94241   ** "table.column=expr" for some single table.  The one bit that is set
94242   ** will correspond to the common table.  We still need to check to make
94243   ** sure the same column is used on all terms.  The 2-bit case is when
94244   ** the all terms are of the form "table1.column=table2.column".  It
94245   ** might be possible to form an IN operator with either table1.column
94246   ** or table2.column as the LHS if either is common to every term of
94247   ** the OR clause.
94248   **
94249   ** Note that terms of the form "table.column1=table.column2" (the
94250   ** same table on both sizes of the ==) cannot be optimized.
94251   */
94252   if( chngToIN ){
94253     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
94254     int iColumn = -1;         /* Column index on lhs of IN operator */
94255     int iCursor = -1;         /* Table cursor common to all terms */
94256     int j = 0;                /* Loop counter */
94257
94258     /* Search for a table and column that appears on one side or the
94259     ** other of the == operator in every subterm.  That table and column
94260     ** will be recorded in iCursor and iColumn.  There might not be any
94261     ** such table and column.  Set okToChngToIN if an appropriate table
94262     ** and column is found but leave okToChngToIN false if not found.
94263     */
94264     for(j=0; j<2 && !okToChngToIN; j++){
94265       pOrTerm = pOrWc->a;
94266       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
94267         assert( pOrTerm->eOperator==WO_EQ );
94268         pOrTerm->wtFlags &= ~TERM_OR_OK;
94269         if( pOrTerm->leftCursor==iCursor ){
94270           /* This is the 2-bit case and we are on the second iteration and
94271           ** current term is from the first iteration.  So skip this term. */
94272           assert( j==1 );
94273           continue;
94274         }
94275         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
94276           /* This term must be of the form t1.a==t2.b where t2 is in the
94277           ** chngToIN set but t1 is not.  This term will be either preceeded
94278           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
94279           ** and use its inversion. */
94280           testcase( pOrTerm->wtFlags & TERM_COPIED );
94281           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
94282           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
94283           continue;
94284         }
94285         iColumn = pOrTerm->u.leftColumn;
94286         iCursor = pOrTerm->leftCursor;
94287         break;
94288       }
94289       if( i<0 ){
94290         /* No candidate table+column was found.  This can only occur
94291         ** on the second iteration */
94292         assert( j==1 );
94293         assert( (chngToIN&(chngToIN-1))==0 );
94294         assert( chngToIN==getMask(pMaskSet, iCursor) );
94295         break;
94296       }
94297       testcase( j==1 );
94298
94299       /* We have found a candidate table and column.  Check to see if that
94300       ** table and column is common to every term in the OR clause */
94301       okToChngToIN = 1;
94302       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
94303         assert( pOrTerm->eOperator==WO_EQ );
94304         if( pOrTerm->leftCursor!=iCursor ){
94305           pOrTerm->wtFlags &= ~TERM_OR_OK;
94306         }else if( pOrTerm->u.leftColumn!=iColumn ){
94307           okToChngToIN = 0;
94308         }else{
94309           int affLeft, affRight;
94310           /* If the right-hand side is also a column, then the affinities
94311           ** of both right and left sides must be such that no type
94312           ** conversions are required on the right.  (Ticket #2249)
94313           */
94314           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
94315           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
94316           if( affRight!=0 && affRight!=affLeft ){
94317             okToChngToIN = 0;
94318           }else{
94319             pOrTerm->wtFlags |= TERM_OR_OK;
94320           }
94321         }
94322       }
94323     }
94324
94325     /* At this point, okToChngToIN is true if original pTerm satisfies
94326     ** case 1.  In that case, construct a new virtual term that is 
94327     ** pTerm converted into an IN operator.
94328     */
94329     if( okToChngToIN ){
94330       Expr *pDup;            /* A transient duplicate expression */
94331       ExprList *pList = 0;   /* The RHS of the IN operator */
94332       Expr *pLeft = 0;       /* The LHS of the IN operator */
94333       Expr *pNew;            /* The complete IN operator */
94334
94335       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
94336         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
94337         assert( pOrTerm->eOperator==WO_EQ );
94338         assert( pOrTerm->leftCursor==iCursor );
94339         assert( pOrTerm->u.leftColumn==iColumn );
94340         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
94341         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
94342         pLeft = pOrTerm->pExpr->pLeft;
94343       }
94344       assert( pLeft!=0 );
94345       pDup = sqlite3ExprDup(db, pLeft, 0);
94346       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
94347       if( pNew ){
94348         int idxNew;
94349         transferJoinMarkings(pNew, pExpr);
94350         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
94351         pNew->x.pList = pList;
94352         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
94353         testcase( idxNew==0 );
94354         exprAnalyze(pSrc, pWC, idxNew);
94355         pTerm = &pWC->a[idxTerm];
94356         pWC->a[idxNew].iParent = idxTerm;
94357         pTerm->nChild = 1;
94358       }else{
94359         sqlite3ExprListDelete(db, pList);
94360       }
94361       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
94362     }
94363   }
94364 }
94365 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
94366
94367
94368 /*
94369 ** The input to this routine is an WhereTerm structure with only the
94370 ** "pExpr" field filled in.  The job of this routine is to analyze the
94371 ** subexpression and populate all the other fields of the WhereTerm
94372 ** structure.
94373 **
94374 ** If the expression is of the form "<expr> <op> X" it gets commuted
94375 ** to the standard form of "X <op> <expr>".
94376 **
94377 ** If the expression is of the form "X <op> Y" where both X and Y are
94378 ** columns, then the original expression is unchanged and a new virtual
94379 ** term of the form "Y <op> X" is added to the WHERE clause and
94380 ** analyzed separately.  The original term is marked with TERM_COPIED
94381 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
94382 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
94383 ** is a commuted copy of a prior term.)  The original term has nChild=1
94384 ** and the copy has idxParent set to the index of the original term.
94385 */
94386 static void exprAnalyze(
94387   SrcList *pSrc,            /* the FROM clause */
94388   WhereClause *pWC,         /* the WHERE clause */
94389   int idxTerm               /* Index of the term to be analyzed */
94390 ){
94391   WhereTerm *pTerm;                /* The term to be analyzed */
94392   WhereMaskSet *pMaskSet;          /* Set of table index masks */
94393   Expr *pExpr;                     /* The expression to be analyzed */
94394   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
94395   Bitmask prereqAll;               /* Prerequesites of pExpr */
94396   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
94397   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
94398   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
94399   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
94400   int op;                          /* Top-level operator.  pExpr->op */
94401   Parse *pParse = pWC->pParse;     /* Parsing context */
94402   sqlite3 *db = pParse->db;        /* Database connection */
94403
94404   if( db->mallocFailed ){
94405     return;
94406   }
94407   pTerm = &pWC->a[idxTerm];
94408   pMaskSet = pWC->pMaskSet;
94409   pExpr = pTerm->pExpr;
94410   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
94411   op = pExpr->op;
94412   if( op==TK_IN ){
94413     assert( pExpr->pRight==0 );
94414     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94415       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
94416     }else{
94417       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
94418     }
94419   }else if( op==TK_ISNULL ){
94420     pTerm->prereqRight = 0;
94421   }else{
94422     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
94423   }
94424   prereqAll = exprTableUsage(pMaskSet, pExpr);
94425   if( ExprHasProperty(pExpr, EP_FromJoin) ){
94426     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
94427     prereqAll |= x;
94428     extraRight = x-1;  /* ON clause terms may not be used with an index
94429                        ** on left table of a LEFT JOIN.  Ticket #3015 */
94430   }
94431   pTerm->prereqAll = prereqAll;
94432   pTerm->leftCursor = -1;
94433   pTerm->iParent = -1;
94434   pTerm->eOperator = 0;
94435   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
94436     Expr *pLeft = pExpr->pLeft;
94437     Expr *pRight = pExpr->pRight;
94438     if( pLeft->op==TK_COLUMN ){
94439       pTerm->leftCursor = pLeft->iTable;
94440       pTerm->u.leftColumn = pLeft->iColumn;
94441       pTerm->eOperator = operatorMask(op);
94442     }
94443     if( pRight && pRight->op==TK_COLUMN ){
94444       WhereTerm *pNew;
94445       Expr *pDup;
94446       if( pTerm->leftCursor>=0 ){
94447         int idxNew;
94448         pDup = sqlite3ExprDup(db, pExpr, 0);
94449         if( db->mallocFailed ){
94450           sqlite3ExprDelete(db, pDup);
94451           return;
94452         }
94453         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
94454         if( idxNew==0 ) return;
94455         pNew = &pWC->a[idxNew];
94456         pNew->iParent = idxTerm;
94457         pTerm = &pWC->a[idxTerm];
94458         pTerm->nChild = 1;
94459         pTerm->wtFlags |= TERM_COPIED;
94460       }else{
94461         pDup = pExpr;
94462         pNew = pTerm;
94463       }
94464       exprCommute(pParse, pDup);
94465       pLeft = pDup->pLeft;
94466       pNew->leftCursor = pLeft->iTable;
94467       pNew->u.leftColumn = pLeft->iColumn;
94468       testcase( (prereqLeft | extraRight) != prereqLeft );
94469       pNew->prereqRight = prereqLeft | extraRight;
94470       pNew->prereqAll = prereqAll;
94471       pNew->eOperator = operatorMask(pDup->op);
94472     }
94473   }
94474
94475 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
94476   /* If a term is the BETWEEN operator, create two new virtual terms
94477   ** that define the range that the BETWEEN implements.  For example:
94478   **
94479   **      a BETWEEN b AND c
94480   **
94481   ** is converted into:
94482   **
94483   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
94484   **
94485   ** The two new terms are added onto the end of the WhereClause object.
94486   ** The new terms are "dynamic" and are children of the original BETWEEN
94487   ** term.  That means that if the BETWEEN term is coded, the children are
94488   ** skipped.  Or, if the children are satisfied by an index, the original
94489   ** BETWEEN term is skipped.
94490   */
94491   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
94492     ExprList *pList = pExpr->x.pList;
94493     int i;
94494     static const u8 ops[] = {TK_GE, TK_LE};
94495     assert( pList!=0 );
94496     assert( pList->nExpr==2 );
94497     for(i=0; i<2; i++){
94498       Expr *pNewExpr;
94499       int idxNew;
94500       pNewExpr = sqlite3PExpr(pParse, ops[i], 
94501                              sqlite3ExprDup(db, pExpr->pLeft, 0),
94502                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
94503       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94504       testcase( idxNew==0 );
94505       exprAnalyze(pSrc, pWC, idxNew);
94506       pTerm = &pWC->a[idxTerm];
94507       pWC->a[idxNew].iParent = idxTerm;
94508     }
94509     pTerm->nChild = 2;
94510   }
94511 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
94512
94513 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94514   /* Analyze a term that is composed of two or more subterms connected by
94515   ** an OR operator.
94516   */
94517   else if( pExpr->op==TK_OR ){
94518     assert( pWC->op==TK_AND );
94519     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
94520     pTerm = &pWC->a[idxTerm];
94521   }
94522 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94523
94524 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
94525   /* Add constraints to reduce the search space on a LIKE or GLOB
94526   ** operator.
94527   **
94528   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
94529   **
94530   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
94531   **
94532   ** The last character of the prefix "abc" is incremented to form the
94533   ** termination condition "abd".
94534   */
94535   if( pWC->op==TK_AND 
94536    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
94537   ){
94538     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
94539     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
94540     Expr *pNewExpr1;
94541     Expr *pNewExpr2;
94542     int idxNew1;
94543     int idxNew2;
94544
94545     pLeft = pExpr->x.pList->a[1].pExpr;
94546     pStr2 = sqlite3ExprDup(db, pStr1, 0);
94547     if( !db->mallocFailed ){
94548       u8 c, *pC;       /* Last character before the first wildcard */
94549       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
94550       c = *pC;
94551       if( noCase ){
94552         /* The point is to increment the last character before the first
94553         ** wildcard.  But if we increment '@', that will push it into the
94554         ** alphabetic range where case conversions will mess up the 
94555         ** inequality.  To avoid this, make sure to also run the full
94556         ** LIKE on all candidate expressions by clearing the isComplete flag
94557         */
94558         if( c=='A'-1 ) isComplete = 0;
94559
94560         c = sqlite3UpperToLower[c];
94561       }
94562       *pC = c + 1;
94563     }
94564     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
94565     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
94566     testcase( idxNew1==0 );
94567     exprAnalyze(pSrc, pWC, idxNew1);
94568     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
94569     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
94570     testcase( idxNew2==0 );
94571     exprAnalyze(pSrc, pWC, idxNew2);
94572     pTerm = &pWC->a[idxTerm];
94573     if( isComplete ){
94574       pWC->a[idxNew1].iParent = idxTerm;
94575       pWC->a[idxNew2].iParent = idxTerm;
94576       pTerm->nChild = 2;
94577     }
94578   }
94579 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
94580
94581 #ifndef SQLITE_OMIT_VIRTUALTABLE
94582   /* Add a WO_MATCH auxiliary term to the constraint set if the
94583   ** current expression is of the form:  column MATCH expr.
94584   ** This information is used by the xBestIndex methods of
94585   ** virtual tables.  The native query optimizer does not attempt
94586   ** to do anything with MATCH functions.
94587   */
94588   if( isMatchOfColumn(pExpr) ){
94589     int idxNew;
94590     Expr *pRight, *pLeft;
94591     WhereTerm *pNewTerm;
94592     Bitmask prereqColumn, prereqExpr;
94593
94594     pRight = pExpr->x.pList->a[0].pExpr;
94595     pLeft = pExpr->x.pList->a[1].pExpr;
94596     prereqExpr = exprTableUsage(pMaskSet, pRight);
94597     prereqColumn = exprTableUsage(pMaskSet, pLeft);
94598     if( (prereqExpr & prereqColumn)==0 ){
94599       Expr *pNewExpr;
94600       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
94601                               0, sqlite3ExprDup(db, pRight, 0), 0);
94602       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94603       testcase( idxNew==0 );
94604       pNewTerm = &pWC->a[idxNew];
94605       pNewTerm->prereqRight = prereqExpr;
94606       pNewTerm->leftCursor = pLeft->iTable;
94607       pNewTerm->u.leftColumn = pLeft->iColumn;
94608       pNewTerm->eOperator = WO_MATCH;
94609       pNewTerm->iParent = idxTerm;
94610       pTerm = &pWC->a[idxTerm];
94611       pTerm->nChild = 1;
94612       pTerm->wtFlags |= TERM_COPIED;
94613       pNewTerm->prereqAll = pTerm->prereqAll;
94614     }
94615   }
94616 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94617
94618   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
94619   ** an index for tables to the left of the join.
94620   */
94621   pTerm->prereqRight |= extraRight;
94622 }
94623
94624 /*
94625 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
94626 ** a reference to any table other than the iBase table.
94627 */
94628 static int referencesOtherTables(
94629   ExprList *pList,          /* Search expressions in ths list */
94630   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
94631   int iFirst,               /* Be searching with the iFirst-th expression */
94632   int iBase                 /* Ignore references to this table */
94633 ){
94634   Bitmask allowed = ~getMask(pMaskSet, iBase);
94635   while( iFirst<pList->nExpr ){
94636     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
94637       return 1;
94638     }
94639   }
94640   return 0;
94641 }
94642
94643
94644 /*
94645 ** This routine decides if pIdx can be used to satisfy the ORDER BY
94646 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
94647 ** ORDER BY clause, this routine returns 0.
94648 **
94649 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
94650 ** left-most table in the FROM clause of that same SELECT statement and
94651 ** the table has a cursor number of "base".  pIdx is an index on pTab.
94652 **
94653 ** nEqCol is the number of columns of pIdx that are used as equality
94654 ** constraints.  Any of these columns may be missing from the ORDER BY
94655 ** clause and the match can still be a success.
94656 **
94657 ** All terms of the ORDER BY that match against the index must be either
94658 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
94659 ** index do not need to satisfy this constraint.)  The *pbRev value is
94660 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
94661 ** the ORDER BY clause is all ASC.
94662 */
94663 static int isSortingIndex(
94664   Parse *pParse,          /* Parsing context */
94665   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
94666   Index *pIdx,            /* The index we are testing */
94667   int base,               /* Cursor number for the table to be sorted */
94668   ExprList *pOrderBy,     /* The ORDER BY clause */
94669   int nEqCol,             /* Number of index columns with == constraints */
94670   int *pbRev              /* Set to 1 if ORDER BY is DESC */
94671 ){
94672   int i, j;                       /* Loop counters */
94673   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
94674   int nTerm;                      /* Number of ORDER BY terms */
94675   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
94676   sqlite3 *db = pParse->db;
94677
94678   assert( pOrderBy!=0 );
94679   nTerm = pOrderBy->nExpr;
94680   assert( nTerm>0 );
94681
94682   /* Argument pIdx must either point to a 'real' named index structure, 
94683   ** or an index structure allocated on the stack by bestBtreeIndex() to
94684   ** represent the rowid index that is part of every table.  */
94685   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
94686
94687   /* Match terms of the ORDER BY clause against columns of
94688   ** the index.
94689   **
94690   ** Note that indices have pIdx->nColumn regular columns plus
94691   ** one additional column containing the rowid.  The rowid column
94692   ** of the index is also allowed to match against the ORDER BY
94693   ** clause.
94694   */
94695   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
94696     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
94697     CollSeq *pColl;    /* The collating sequence of pExpr */
94698     int termSortOrder; /* Sort order for this term */
94699     int iColumn;       /* The i-th column of the index.  -1 for rowid */
94700     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
94701     const char *zColl; /* Name of the collating sequence for i-th index term */
94702
94703     pExpr = pTerm->pExpr;
94704     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
94705       /* Can not use an index sort on anything that is not a column in the
94706       ** left-most table of the FROM clause */
94707       break;
94708     }
94709     pColl = sqlite3ExprCollSeq(pParse, pExpr);
94710     if( !pColl ){
94711       pColl = db->pDfltColl;
94712     }
94713     if( pIdx->zName && i<pIdx->nColumn ){
94714       iColumn = pIdx->aiColumn[i];
94715       if( iColumn==pIdx->pTable->iPKey ){
94716         iColumn = -1;
94717       }
94718       iSortOrder = pIdx->aSortOrder[i];
94719       zColl = pIdx->azColl[i];
94720     }else{
94721       iColumn = -1;
94722       iSortOrder = 0;
94723       zColl = pColl->zName;
94724     }
94725     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
94726       /* Term j of the ORDER BY clause does not match column i of the index */
94727       if( i<nEqCol ){
94728         /* If an index column that is constrained by == fails to match an
94729         ** ORDER BY term, that is OK.  Just ignore that column of the index
94730         */
94731         continue;
94732       }else if( i==pIdx->nColumn ){
94733         /* Index column i is the rowid.  All other terms match. */
94734         break;
94735       }else{
94736         /* If an index column fails to match and is not constrained by ==
94737         ** then the index cannot satisfy the ORDER BY constraint.
94738         */
94739         return 0;
94740       }
94741     }
94742     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
94743     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
94744     assert( iSortOrder==0 || iSortOrder==1 );
94745     termSortOrder = iSortOrder ^ pTerm->sortOrder;
94746     if( i>nEqCol ){
94747       if( termSortOrder!=sortOrder ){
94748         /* Indices can only be used if all ORDER BY terms past the
94749         ** equality constraints are all either DESC or ASC. */
94750         return 0;
94751       }
94752     }else{
94753       sortOrder = termSortOrder;
94754     }
94755     j++;
94756     pTerm++;
94757     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94758       /* If the indexed column is the primary key and everything matches
94759       ** so far and none of the ORDER BY terms to the right reference other
94760       ** tables in the join, then we are assured that the index can be used 
94761       ** to sort because the primary key is unique and so none of the other
94762       ** columns will make any difference
94763       */
94764       j = nTerm;
94765     }
94766   }
94767
94768   *pbRev = sortOrder!=0;
94769   if( j>=nTerm ){
94770     /* All terms of the ORDER BY clause are covered by this index so
94771     ** this index can be used for sorting. */
94772     return 1;
94773   }
94774   if( pIdx->onError!=OE_None && i==pIdx->nColumn
94775       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94776     /* All terms of this index match some prefix of the ORDER BY clause
94777     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
94778     ** clause reference other tables in a join.  If this is all true then
94779     ** the order by clause is superfluous. */
94780     return 1;
94781   }
94782   return 0;
94783 }
94784
94785 /*
94786 ** Prepare a crude estimate of the logarithm of the input value.
94787 ** The results need not be exact.  This is only used for estimating
94788 ** the total cost of performing operations with O(logN) or O(NlogN)
94789 ** complexity.  Because N is just a guess, it is no great tragedy if
94790 ** logN is a little off.
94791 */
94792 static double estLog(double N){
94793   double logN = 1;
94794   double x = 10;
94795   while( N>x ){
94796     logN += 1;
94797     x *= 10;
94798   }
94799   return logN;
94800 }
94801
94802 /*
94803 ** Two routines for printing the content of an sqlite3_index_info
94804 ** structure.  Used for testing and debugging only.  If neither
94805 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
94806 ** are no-ops.
94807 */
94808 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
94809 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
94810   int i;
94811   if( !sqlite3WhereTrace ) return;
94812   for(i=0; i<p->nConstraint; i++){
94813     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
94814        i,
94815        p->aConstraint[i].iColumn,
94816        p->aConstraint[i].iTermOffset,
94817        p->aConstraint[i].op,
94818        p->aConstraint[i].usable);
94819   }
94820   for(i=0; i<p->nOrderBy; i++){
94821     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
94822        i,
94823        p->aOrderBy[i].iColumn,
94824        p->aOrderBy[i].desc);
94825   }
94826 }
94827 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
94828   int i;
94829   if( !sqlite3WhereTrace ) return;
94830   for(i=0; i<p->nConstraint; i++){
94831     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
94832        i,
94833        p->aConstraintUsage[i].argvIndex,
94834        p->aConstraintUsage[i].omit);
94835   }
94836   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
94837   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
94838   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
94839   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
94840 }
94841 #else
94842 #define TRACE_IDX_INPUTS(A)
94843 #define TRACE_IDX_OUTPUTS(A)
94844 #endif
94845
94846 /* 
94847 ** Required because bestIndex() is called by bestOrClauseIndex() 
94848 */
94849 static void bestIndex(
94850     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
94851
94852 /*
94853 ** This routine attempts to find an scanning strategy that can be used 
94854 ** to optimize an 'OR' expression that is part of a WHERE clause. 
94855 **
94856 ** The table associated with FROM clause term pSrc may be either a
94857 ** regular B-Tree table or a virtual table.
94858 */
94859 static void bestOrClauseIndex(
94860   Parse *pParse,              /* The parsing context */
94861   WhereClause *pWC,           /* The WHERE clause */
94862   struct SrcList_item *pSrc,  /* The FROM clause term to search */
94863   Bitmask notReady,           /* Mask of cursors that are not available */
94864   ExprList *pOrderBy,         /* The ORDER BY clause */
94865   WhereCost *pCost            /* Lowest cost query plan */
94866 ){
94867 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
94868   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
94869   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
94870   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
94871   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
94872
94873   /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
94874   if( pSrc->notIndexed ){
94875     return;
94876   }
94877
94878   /* Search the WHERE clause terms for a usable WO_OR term. */
94879   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94880     if( pTerm->eOperator==WO_OR 
94881      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
94882      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
94883     ){
94884       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
94885       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
94886       WhereTerm *pOrTerm;
94887       int flags = WHERE_MULTI_OR;
94888       double rTotal = 0;
94889       double nRow = 0;
94890       Bitmask used = 0;
94891
94892       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
94893         WhereCost sTermCost;
94894         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
94895           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
94896         ));
94897         if( pOrTerm->eOperator==WO_AND ){
94898           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
94899           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
94900         }else if( pOrTerm->leftCursor==iCur ){
94901           WhereClause tempWC;
94902           tempWC.pParse = pWC->pParse;
94903           tempWC.pMaskSet = pWC->pMaskSet;
94904           tempWC.op = TK_AND;
94905           tempWC.a = pOrTerm;
94906           tempWC.nTerm = 1;
94907           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
94908         }else{
94909           continue;
94910         }
94911         rTotal += sTermCost.rCost;
94912         nRow += sTermCost.nRow;
94913         used |= sTermCost.used;
94914         if( rTotal>=pCost->rCost ) break;
94915       }
94916
94917       /* If there is an ORDER BY clause, increase the scan cost to account 
94918       ** for the cost of the sort. */
94919       if( pOrderBy!=0 ){
94920         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
94921                     rTotal, rTotal+nRow*estLog(nRow)));
94922         rTotal += nRow*estLog(nRow);
94923       }
94924
94925       /* If the cost of scanning using this OR term for optimization is
94926       ** less than the current cost stored in pCost, replace the contents
94927       ** of pCost. */
94928       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
94929       if( rTotal<pCost->rCost ){
94930         pCost->rCost = rTotal;
94931         pCost->nRow = nRow;
94932         pCost->used = used;
94933         pCost->plan.wsFlags = flags;
94934         pCost->plan.u.pTerm = pTerm;
94935       }
94936     }
94937   }
94938 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94939 }
94940
94941 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94942 /*
94943 ** Return TRUE if the WHERE clause term pTerm is of a form where it
94944 ** could be used with an index to access pSrc, assuming an appropriate
94945 ** index existed.
94946 */
94947 static int termCanDriveIndex(
94948   WhereTerm *pTerm,              /* WHERE clause term to check */
94949   struct SrcList_item *pSrc,     /* Table we are trying to access */
94950   Bitmask notReady               /* Tables in outer loops of the join */
94951 ){
94952   char aff;
94953   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
94954   if( pTerm->eOperator!=WO_EQ ) return 0;
94955   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
94956   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
94957   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
94958   return 1;
94959 }
94960 #endif
94961
94962 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94963 /*
94964 ** If the query plan for pSrc specified in pCost is a full table scan
94965 ** and indexing is allows (if there is no NOT INDEXED clause) and it
94966 ** possible to construct a transient index that would perform better
94967 ** than a full table scan even when the cost of constructing the index
94968 ** is taken into account, then alter the query plan to use the
94969 ** transient index.
94970 */
94971 static void bestAutomaticIndex(
94972   Parse *pParse,              /* The parsing context */
94973   WhereClause *pWC,           /* The WHERE clause */
94974   struct SrcList_item *pSrc,  /* The FROM clause term to search */
94975   Bitmask notReady,           /* Mask of cursors that are not available */
94976   WhereCost *pCost            /* Lowest cost query plan */
94977 ){
94978   double nTableRow;           /* Rows in the input table */
94979   double logN;                /* log(nTableRow) */
94980   double costTempIdx;         /* per-query cost of the transient index */
94981   WhereTerm *pTerm;           /* A single term of the WHERE clause */
94982   WhereTerm *pWCEnd;          /* End of pWC->a[] */
94983   Table *pTable;              /* Table tht might be indexed */
94984
94985   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
94986     /* Automatic indices are disabled at run-time */
94987     return;
94988   }
94989   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
94990     /* We already have some kind of index in use for this query. */
94991     return;
94992   }
94993   if( pSrc->notIndexed ){
94994     /* The NOT INDEXED clause appears in the SQL. */
94995     return;
94996   }
94997
94998   assert( pParse->nQueryLoop >= (double)1 );
94999   pTable = pSrc->pTab;
95000   nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
95001   logN = estLog(nTableRow);
95002   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
95003   if( costTempIdx>=pCost->rCost ){
95004     /* The cost of creating the transient table would be greater than
95005     ** doing the full table scan */
95006     return;
95007   }
95008
95009   /* Search for any equality comparison term */
95010   pWCEnd = &pWC->a[pWC->nTerm];
95011   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95012     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95013       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
95014                     pCost->rCost, costTempIdx));
95015       pCost->rCost = costTempIdx;
95016       pCost->nRow = logN + 1;
95017       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
95018       pCost->used = pTerm->prereqRight;
95019       break;
95020     }
95021   }
95022 }
95023 #else
95024 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
95025 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95026
95027
95028 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95029 /*
95030 ** Generate code to construct the Index object for an automatic index
95031 ** and to set up the WhereLevel object pLevel so that the code generator
95032 ** makes use of the automatic index.
95033 */
95034 static void constructAutomaticIndex(
95035   Parse *pParse,              /* The parsing context */
95036   WhereClause *pWC,           /* The WHERE clause */
95037   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
95038   Bitmask notReady,           /* Mask of cursors that are not available */
95039   WhereLevel *pLevel          /* Write new index here */
95040 ){
95041   int nColumn;                /* Number of columns in the constructed index */
95042   WhereTerm *pTerm;           /* A single term of the WHERE clause */
95043   WhereTerm *pWCEnd;          /* End of pWC->a[] */
95044   int nByte;                  /* Byte of memory needed for pIdx */
95045   Index *pIdx;                /* Object describing the transient index */
95046   Vdbe *v;                    /* Prepared statement under construction */
95047   int regIsInit;              /* Register set by initialization */
95048   int addrInit;               /* Address of the initialization bypass jump */
95049   Table *pTable;              /* The table being indexed */
95050   KeyInfo *pKeyinfo;          /* Key information for the index */   
95051   int addrTop;                /* Top of the index fill loop */
95052   int regRecord;              /* Register holding an index record */
95053   int n;                      /* Column counter */
95054   int i;                      /* Loop counter */
95055   int mxBitCol;               /* Maximum column in pSrc->colUsed */
95056   CollSeq *pColl;             /* Collating sequence to on a column */
95057   Bitmask idxCols;            /* Bitmap of columns used for indexing */
95058   Bitmask extraCols;          /* Bitmap of additional columns */
95059
95060   /* Generate code to skip over the creation and initialization of the
95061   ** transient index on 2nd and subsequent iterations of the loop. */
95062   v = pParse->pVdbe;
95063   assert( v!=0 );
95064   regIsInit = ++pParse->nMem;
95065   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
95066   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
95067
95068   /* Count the number of columns that will be added to the index
95069   ** and used to match WHERE clause constraints */
95070   nColumn = 0;
95071   pTable = pSrc->pTab;
95072   pWCEnd = &pWC->a[pWC->nTerm];
95073   idxCols = 0;
95074   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95075     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95076       int iCol = pTerm->u.leftColumn;
95077       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95078       testcase( iCol==BMS );
95079       testcase( iCol==BMS-1 );
95080       if( (idxCols & cMask)==0 ){
95081         nColumn++;
95082         idxCols |= cMask;
95083       }
95084     }
95085   }
95086   assert( nColumn>0 );
95087   pLevel->plan.nEq = nColumn;
95088
95089   /* Count the number of additional columns needed to create a
95090   ** covering index.  A "covering index" is an index that contains all
95091   ** columns that are needed by the query.  With a covering index, the
95092   ** original table never needs to be accessed.  Automatic indices must
95093   ** be a covering index because the index will not be updated if the
95094   ** original table changes and the index and table cannot both be used
95095   ** if they go out of sync.
95096   */
95097   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
95098   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
95099   testcase( pTable->nCol==BMS-1 );
95100   testcase( pTable->nCol==BMS-2 );
95101   for(i=0; i<mxBitCol; i++){
95102     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
95103   }
95104   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
95105     nColumn += pTable->nCol - BMS + 1;
95106   }
95107   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
95108
95109   /* Construct the Index object to describe this index */
95110   nByte = sizeof(Index);
95111   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
95112   nByte += nColumn*sizeof(char*);   /* Index.azColl */
95113   nByte += nColumn;                 /* Index.aSortOrder */
95114   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
95115   if( pIdx==0 ) return;
95116   pLevel->plan.u.pIdx = pIdx;
95117   pIdx->azColl = (char**)&pIdx[1];
95118   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
95119   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
95120   pIdx->zName = "auto-index";
95121   pIdx->nColumn = nColumn;
95122   pIdx->pTable = pTable;
95123   n = 0;
95124   idxCols = 0;
95125   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95126     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95127       int iCol = pTerm->u.leftColumn;
95128       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95129       if( (idxCols & cMask)==0 ){
95130         Expr *pX = pTerm->pExpr;
95131         idxCols |= cMask;
95132         pIdx->aiColumn[n] = pTerm->u.leftColumn;
95133         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
95134         pIdx->azColl[n] = pColl->zName;
95135         n++;
95136       }
95137     }
95138   }
95139   assert( (u32)n==pLevel->plan.nEq );
95140
95141   /* Add additional columns needed to make the automatic index into
95142   ** a covering index */
95143   for(i=0; i<mxBitCol; i++){
95144     if( extraCols & (((Bitmask)1)<<i) ){
95145       pIdx->aiColumn[n] = i;
95146       pIdx->azColl[n] = "BINARY";
95147       n++;
95148     }
95149   }
95150   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
95151     for(i=BMS-1; i<pTable->nCol; i++){
95152       pIdx->aiColumn[n] = i;
95153       pIdx->azColl[n] = "BINARY";
95154       n++;
95155     }
95156   }
95157   assert( n==nColumn );
95158
95159   /* Create the automatic index */
95160   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
95161   assert( pLevel->iIdxCur>=0 );
95162   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
95163                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
95164   VdbeComment((v, "for %s", pTable->zName));
95165
95166   /* Fill the automatic index with content */
95167   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
95168   regRecord = sqlite3GetTempReg(pParse);
95169   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
95170   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
95171   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
95172   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
95173   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
95174   sqlite3VdbeJumpHere(v, addrTop);
95175   sqlite3ReleaseTempReg(pParse, regRecord);
95176   
95177   /* Jump here when skipping the initialization */
95178   sqlite3VdbeJumpHere(v, addrInit);
95179 }
95180 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95181
95182 #ifndef SQLITE_OMIT_VIRTUALTABLE
95183 /*
95184 ** Allocate and populate an sqlite3_index_info structure. It is the 
95185 ** responsibility of the caller to eventually release the structure
95186 ** by passing the pointer returned by this function to sqlite3_free().
95187 */
95188 static sqlite3_index_info *allocateIndexInfo(
95189   Parse *pParse, 
95190   WhereClause *pWC,
95191   struct SrcList_item *pSrc,
95192   ExprList *pOrderBy
95193 ){
95194   int i, j;
95195   int nTerm;
95196   struct sqlite3_index_constraint *pIdxCons;
95197   struct sqlite3_index_orderby *pIdxOrderBy;
95198   struct sqlite3_index_constraint_usage *pUsage;
95199   WhereTerm *pTerm;
95200   int nOrderBy;
95201   sqlite3_index_info *pIdxInfo;
95202
95203   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
95204
95205   /* Count the number of possible WHERE clause constraints referring
95206   ** to this virtual table */
95207   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
95208     if( pTerm->leftCursor != pSrc->iCursor ) continue;
95209     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
95210     testcase( pTerm->eOperator==WO_IN );
95211     testcase( pTerm->eOperator==WO_ISNULL );
95212     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
95213     nTerm++;
95214   }
95215
95216   /* If the ORDER BY clause contains only columns in the current 
95217   ** virtual table then allocate space for the aOrderBy part of
95218   ** the sqlite3_index_info structure.
95219   */
95220   nOrderBy = 0;
95221   if( pOrderBy ){
95222     for(i=0; i<pOrderBy->nExpr; i++){
95223       Expr *pExpr = pOrderBy->a[i].pExpr;
95224       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
95225     }
95226     if( i==pOrderBy->nExpr ){
95227       nOrderBy = pOrderBy->nExpr;
95228     }
95229   }
95230
95231   /* Allocate the sqlite3_index_info structure
95232   */
95233   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
95234                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
95235                            + sizeof(*pIdxOrderBy)*nOrderBy );
95236   if( pIdxInfo==0 ){
95237     sqlite3ErrorMsg(pParse, "out of memory");
95238     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
95239     return 0;
95240   }
95241
95242   /* Initialize the structure.  The sqlite3_index_info structure contains
95243   ** many fields that are declared "const" to prevent xBestIndex from
95244   ** changing them.  We have to do some funky casting in order to
95245   ** initialize those fields.
95246   */
95247   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
95248   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
95249   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
95250   *(int*)&pIdxInfo->nConstraint = nTerm;
95251   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
95252   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
95253   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
95254   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
95255                                                                    pUsage;
95256
95257   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
95258     if( pTerm->leftCursor != pSrc->iCursor ) continue;
95259     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
95260     testcase( pTerm->eOperator==WO_IN );
95261     testcase( pTerm->eOperator==WO_ISNULL );
95262     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
95263     pIdxCons[j].iColumn = pTerm->u.leftColumn;
95264     pIdxCons[j].iTermOffset = i;
95265     pIdxCons[j].op = (u8)pTerm->eOperator;
95266     /* The direct assignment in the previous line is possible only because
95267     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
95268     ** following asserts verify this fact. */
95269     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
95270     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
95271     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
95272     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
95273     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
95274     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
95275     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
95276     j++;
95277   }
95278   for(i=0; i<nOrderBy; i++){
95279     Expr *pExpr = pOrderBy->a[i].pExpr;
95280     pIdxOrderBy[i].iColumn = pExpr->iColumn;
95281     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
95282   }
95283
95284   return pIdxInfo;
95285 }
95286
95287 /*
95288 ** The table object reference passed as the second argument to this function
95289 ** must represent a virtual table. This function invokes the xBestIndex()
95290 ** method of the virtual table with the sqlite3_index_info pointer passed
95291 ** as the argument.
95292 **
95293 ** If an error occurs, pParse is populated with an error message and a
95294 ** non-zero value is returned. Otherwise, 0 is returned and the output
95295 ** part of the sqlite3_index_info structure is left populated.
95296 **
95297 ** Whether or not an error is returned, it is the responsibility of the
95298 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
95299 ** that this is required.
95300 */
95301 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
95302   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
95303   int i;
95304   int rc;
95305
95306   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
95307   TRACE_IDX_INPUTS(p);
95308   rc = pVtab->pModule->xBestIndex(pVtab, p);
95309   TRACE_IDX_OUTPUTS(p);
95310
95311   if( rc!=SQLITE_OK ){
95312     if( rc==SQLITE_NOMEM ){
95313       pParse->db->mallocFailed = 1;
95314     }else if( !pVtab->zErrMsg ){
95315       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
95316     }else{
95317       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
95318     }
95319   }
95320   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
95321   pVtab->zErrMsg = 0;
95322
95323   for(i=0; i<p->nConstraint; i++){
95324     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
95325       sqlite3ErrorMsg(pParse, 
95326           "table %s: xBestIndex returned an invalid plan", pTab->zName);
95327     }
95328   }
95329
95330   return pParse->nErr;
95331 }
95332
95333
95334 /*
95335 ** Compute the best index for a virtual table.
95336 **
95337 ** The best index is computed by the xBestIndex method of the virtual
95338 ** table module.  This routine is really just a wrapper that sets up
95339 ** the sqlite3_index_info structure that is used to communicate with
95340 ** xBestIndex.
95341 **
95342 ** In a join, this routine might be called multiple times for the
95343 ** same virtual table.  The sqlite3_index_info structure is created
95344 ** and initialized on the first invocation and reused on all subsequent
95345 ** invocations.  The sqlite3_index_info structure is also used when
95346 ** code is generated to access the virtual table.  The whereInfoDelete() 
95347 ** routine takes care of freeing the sqlite3_index_info structure after
95348 ** everybody has finished with it.
95349 */
95350 static void bestVirtualIndex(
95351   Parse *pParse,                  /* The parsing context */
95352   WhereClause *pWC,               /* The WHERE clause */
95353   struct SrcList_item *pSrc,      /* The FROM clause term to search */
95354   Bitmask notReady,               /* Mask of cursors that are not available */
95355   ExprList *pOrderBy,             /* The order by clause */
95356   WhereCost *pCost,               /* Lowest cost query plan */
95357   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
95358 ){
95359   Table *pTab = pSrc->pTab;
95360   sqlite3_index_info *pIdxInfo;
95361   struct sqlite3_index_constraint *pIdxCons;
95362   struct sqlite3_index_constraint_usage *pUsage;
95363   WhereTerm *pTerm;
95364   int i, j;
95365   int nOrderBy;
95366   double rCost;
95367
95368   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
95369   ** malloc in allocateIndexInfo() fails and this function returns leaving
95370   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
95371   */
95372   memset(pCost, 0, sizeof(*pCost));
95373   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
95374
95375   /* If the sqlite3_index_info structure has not been previously
95376   ** allocated and initialized, then allocate and initialize it now.
95377   */
95378   pIdxInfo = *ppIdxInfo;
95379   if( pIdxInfo==0 ){
95380     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
95381   }
95382   if( pIdxInfo==0 ){
95383     return;
95384   }
95385
95386   /* At this point, the sqlite3_index_info structure that pIdxInfo points
95387   ** to will have been initialized, either during the current invocation or
95388   ** during some prior invocation.  Now we just have to customize the
95389   ** details of pIdxInfo for the current invocation and pass it to
95390   ** xBestIndex.
95391   */
95392
95393   /* The module name must be defined. Also, by this point there must
95394   ** be a pointer to an sqlite3_vtab structure. Otherwise
95395   ** sqlite3ViewGetColumnNames() would have picked up the error. 
95396   */
95397   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
95398   assert( sqlite3GetVTable(pParse->db, pTab) );
95399
95400   /* Set the aConstraint[].usable fields and initialize all 
95401   ** output variables to zero.
95402   **
95403   ** aConstraint[].usable is true for constraints where the right-hand
95404   ** side contains only references to tables to the left of the current
95405   ** table.  In other words, if the constraint is of the form:
95406   **
95407   **           column = expr
95408   **
95409   ** and we are evaluating a join, then the constraint on column is 
95410   ** only valid if all tables referenced in expr occur to the left
95411   ** of the table containing column.
95412   **
95413   ** The aConstraints[] array contains entries for all constraints
95414   ** on the current table.  That way we only have to compute it once
95415   ** even though we might try to pick the best index multiple times.
95416   ** For each attempt at picking an index, the order of tables in the
95417   ** join might be different so we have to recompute the usable flag
95418   ** each time.
95419   */
95420   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95421   pUsage = pIdxInfo->aConstraintUsage;
95422   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
95423     j = pIdxCons->iTermOffset;
95424     pTerm = &pWC->a[j];
95425     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
95426   }
95427   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
95428   if( pIdxInfo->needToFreeIdxStr ){
95429     sqlite3_free(pIdxInfo->idxStr);
95430   }
95431   pIdxInfo->idxStr = 0;
95432   pIdxInfo->idxNum = 0;
95433   pIdxInfo->needToFreeIdxStr = 0;
95434   pIdxInfo->orderByConsumed = 0;
95435   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
95436   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
95437   nOrderBy = pIdxInfo->nOrderBy;
95438   if( !pOrderBy ){
95439     pIdxInfo->nOrderBy = 0;
95440   }
95441
95442   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
95443     return;
95444   }
95445
95446   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95447   for(i=0; i<pIdxInfo->nConstraint; i++){
95448     if( pUsage[i].argvIndex>0 ){
95449       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
95450     }
95451   }
95452
95453   /* If there is an ORDER BY clause, and the selected virtual table index
95454   ** does not satisfy it, increase the cost of the scan accordingly. This
95455   ** matches the processing for non-virtual tables in bestBtreeIndex().
95456   */
95457   rCost = pIdxInfo->estimatedCost;
95458   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
95459     rCost += estLog(rCost)*rCost;
95460   }
95461
95462   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
95463   ** inital value of lowestCost in this loop. If it is, then the
95464   ** (cost<lowestCost) test below will never be true.
95465   ** 
95466   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
95467   ** is defined.
95468   */
95469   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
95470     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
95471   }else{
95472     pCost->rCost = rCost;
95473   }
95474   pCost->plan.u.pVtabIdx = pIdxInfo;
95475   if( pIdxInfo->orderByConsumed ){
95476     pCost->plan.wsFlags |= WHERE_ORDERBY;
95477   }
95478   pCost->plan.nEq = 0;
95479   pIdxInfo->nOrderBy = nOrderBy;
95480
95481   /* Try to find a more efficient access pattern by using multiple indexes
95482   ** to optimize an OR expression within the WHERE clause. 
95483   */
95484   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
95485 }
95486 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95487
95488 /*
95489 ** Argument pIdx is a pointer to an index structure that has an array of
95490 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
95491 ** stored in Index.aSample. The domain of values stored in said column
95492 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
95493 ** Region 0 contains all values smaller than the first sample value. Region
95494 ** 1 contains values larger than or equal to the value of the first sample,
95495 ** but smaller than the value of the second. And so on.
95496 **
95497 ** If successful, this function determines which of the regions value 
95498 ** pVal lies in, sets *piRegion to the region index (a value between 0
95499 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
95500 ** Or, if an OOM occurs while converting text values between encodings,
95501 ** SQLITE_NOMEM is returned and *piRegion is undefined.
95502 */
95503 #ifdef SQLITE_ENABLE_STAT2
95504 static int whereRangeRegion(
95505   Parse *pParse,              /* Database connection */
95506   Index *pIdx,                /* Index to consider domain of */
95507   sqlite3_value *pVal,        /* Value to consider */
95508   int *piRegion               /* OUT: Region of domain in which value lies */
95509 ){
95510   if( ALWAYS(pVal) ){
95511     IndexSample *aSample = pIdx->aSample;
95512     int i = 0;
95513     int eType = sqlite3_value_type(pVal);
95514
95515     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
95516       double r = sqlite3_value_double(pVal);
95517       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95518         if( aSample[i].eType==SQLITE_NULL ) continue;
95519         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
95520       }
95521     }else{ 
95522       sqlite3 *db = pParse->db;
95523       CollSeq *pColl;
95524       const u8 *z;
95525       int n;
95526
95527       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
95528       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
95529
95530       if( eType==SQLITE_BLOB ){
95531         z = (const u8 *)sqlite3_value_blob(pVal);
95532         pColl = db->pDfltColl;
95533         assert( pColl->enc==SQLITE_UTF8 );
95534       }else{
95535         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
95536         if( pColl==0 ){
95537           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
95538                           *pIdx->azColl);
95539           return SQLITE_ERROR;
95540         }
95541         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
95542         if( !z ){
95543           return SQLITE_NOMEM;
95544         }
95545         assert( z && pColl && pColl->xCmp );
95546       }
95547       n = sqlite3ValueBytes(pVal, pColl->enc);
95548
95549       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95550         int r;
95551         int eSampletype = aSample[i].eType;
95552         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
95553         if( (eSampletype!=eType) ) break;
95554 #ifndef SQLITE_OMIT_UTF16
95555         if( pColl->enc!=SQLITE_UTF8 ){
95556           int nSample;
95557           char *zSample = sqlite3Utf8to16(
95558               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
95559           );
95560           if( !zSample ){
95561             assert( db->mallocFailed );
95562             return SQLITE_NOMEM;
95563           }
95564           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
95565           sqlite3DbFree(db, zSample);
95566         }else
95567 #endif
95568         {
95569           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
95570         }
95571         if( r>0 ) break;
95572       }
95573     }
95574
95575     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
95576     *piRegion = i;
95577   }
95578   return SQLITE_OK;
95579 }
95580 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
95581
95582 /*
95583 ** If expression pExpr represents a literal value, set *pp to point to
95584 ** an sqlite3_value structure containing the same value, with affinity
95585 ** aff applied to it, before returning. It is the responsibility of the 
95586 ** caller to eventually release this structure by passing it to 
95587 ** sqlite3ValueFree().
95588 **
95589 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
95590 ** is an SQL variable that currently has a non-NULL value bound to it,
95591 ** create an sqlite3_value structure containing this value, again with
95592 ** affinity aff applied to it, instead.
95593 **
95594 ** If neither of the above apply, set *pp to NULL.
95595 **
95596 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
95597 */
95598 #ifdef SQLITE_ENABLE_STAT2
95599 static int valueFromExpr(
95600   Parse *pParse, 
95601   Expr *pExpr, 
95602   u8 aff, 
95603   sqlite3_value **pp
95604 ){
95605   /* The evalConstExpr() function will have already converted any TK_VARIABLE
95606   ** expression involved in an comparison into a TK_REGISTER. */
95607   assert( pExpr->op!=TK_VARIABLE );
95608   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
95609     int iVar = pExpr->iColumn;
95610     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
95611     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
95612     return SQLITE_OK;
95613   }
95614   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
95615 }
95616 #endif
95617
95618 /*
95619 ** This function is used to estimate the number of rows that will be visited
95620 ** by scanning an index for a range of values. The range may have an upper
95621 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
95622 ** and lower bounds are represented by pLower and pUpper respectively. For
95623 ** example, assuming that index p is on t1(a):
95624 **
95625 **   ... FROM t1 WHERE a > ? AND a < ? ...
95626 **                    |_____|   |_____|
95627 **                       |         |
95628 **                     pLower    pUpper
95629 **
95630 ** If either of the upper or lower bound is not present, then NULL is passed in
95631 ** place of the corresponding WhereTerm.
95632 **
95633 ** The nEq parameter is passed the index of the index column subject to the
95634 ** range constraint. Or, equivalently, the number of equality constraints
95635 ** optimized by the proposed index scan. For example, assuming index p is
95636 ** on t1(a, b), and the SQL query is:
95637 **
95638 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
95639 **
95640 ** then nEq should be passed the value 1 (as the range restricted column,
95641 ** b, is the second left-most column of the index). Or, if the query is:
95642 **
95643 **   ... FROM t1 WHERE a > ? AND a < ? ...
95644 **
95645 ** then nEq should be passed 0.
95646 **
95647 ** The returned value is an integer between 1 and 100, inclusive. A return
95648 ** value of 1 indicates that the proposed range scan is expected to visit
95649 ** approximately 1/100th (1%) of the rows selected by the nEq equality
95650 ** constraints (if any). A return value of 100 indicates that it is expected
95651 ** that the range scan will visit every row (100%) selected by the equality
95652 ** constraints.
95653 **
95654 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
95655 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
95656 ** results in a return of 33 and a range constraint (x>? AND x<?) results
95657 ** in a return of 11.
95658 */
95659 static int whereRangeScanEst(
95660   Parse *pParse,       /* Parsing & code generating context */
95661   Index *p,            /* The index containing the range-compared column; "x" */
95662   int nEq,             /* index into p->aCol[] of the range-compared column */
95663   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
95664   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
95665   int *piEst           /* OUT: Return value */
95666 ){
95667   int rc = SQLITE_OK;
95668
95669 #ifdef SQLITE_ENABLE_STAT2
95670
95671   if( nEq==0 && p->aSample ){
95672     sqlite3_value *pLowerVal = 0;
95673     sqlite3_value *pUpperVal = 0;
95674     int iEst;
95675     int iLower = 0;
95676     int iUpper = SQLITE_INDEX_SAMPLES;
95677     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
95678
95679     if( pLower ){
95680       Expr *pExpr = pLower->pExpr->pRight;
95681       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
95682     }
95683     if( rc==SQLITE_OK && pUpper ){
95684       Expr *pExpr = pUpper->pExpr->pRight;
95685       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
95686     }
95687
95688     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
95689       sqlite3ValueFree(pLowerVal);
95690       sqlite3ValueFree(pUpperVal);
95691       goto range_est_fallback;
95692     }else if( pLowerVal==0 ){
95693       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95694       if( pLower ) iLower = iUpper/2;
95695     }else if( pUpperVal==0 ){
95696       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95697       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
95698     }else{
95699       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95700       if( rc==SQLITE_OK ){
95701         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95702       }
95703     }
95704
95705     iEst = iUpper - iLower;
95706     testcase( iEst==SQLITE_INDEX_SAMPLES );
95707     assert( iEst<=SQLITE_INDEX_SAMPLES );
95708     if( iEst<1 ){
95709       iEst = 1;
95710     }
95711
95712     sqlite3ValueFree(pLowerVal);
95713     sqlite3ValueFree(pUpperVal);
95714     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
95715     return rc;
95716   }
95717 range_est_fallback:
95718 #else
95719   UNUSED_PARAMETER(pParse);
95720   UNUSED_PARAMETER(p);
95721   UNUSED_PARAMETER(nEq);
95722 #endif
95723   assert( pLower || pUpper );
95724   if( pLower && pUpper ){
95725     *piEst = 11;
95726   }else{
95727     *piEst = 33;
95728   }
95729   return rc;
95730 }
95731
95732
95733 /*
95734 ** Find the query plan for accessing a particular table.  Write the
95735 ** best query plan and its cost into the WhereCost object supplied as the
95736 ** last parameter.
95737 **
95738 ** The lowest cost plan wins.  The cost is an estimate of the amount of
95739 ** CPU and disk I/O need to process the request using the selected plan.
95740 ** Factors that influence cost include:
95741 **
95742 **    *  The estimated number of rows that will be retrieved.  (The
95743 **       fewer the better.)
95744 **
95745 **    *  Whether or not sorting must occur.
95746 **
95747 **    *  Whether or not there must be separate lookups in the
95748 **       index and in the main table.
95749 **
95750 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
95751 ** the SQL statement, then this function only considers plans using the 
95752 ** named index. If no such plan is found, then the returned cost is
95753 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
95754 ** then the cost is calculated in the usual way.
95755 **
95756 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
95757 ** in the SELECT statement, then no indexes are considered. However, the 
95758 ** selected plan may still take advantage of the tables built-in rowid
95759 ** index.
95760 */
95761 static void bestBtreeIndex(
95762   Parse *pParse,              /* The parsing context */
95763   WhereClause *pWC,           /* The WHERE clause */
95764   struct SrcList_item *pSrc,  /* The FROM clause term to search */
95765   Bitmask notReady,           /* Mask of cursors that are not available */
95766   ExprList *pOrderBy,         /* The ORDER BY clause */
95767   WhereCost *pCost            /* Lowest cost query plan */
95768 ){
95769   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
95770   Index *pProbe;              /* An index we are evaluating */
95771   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
95772   int eqTermMask;             /* Current mask of valid equality operators */
95773   int idxEqTermMask;          /* Index mask of valid equality operators */
95774   Index sPk;                  /* A fake index object for the primary key */
95775   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
95776   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
95777   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
95778
95779   /* Initialize the cost to a worst-case value */
95780   memset(pCost, 0, sizeof(*pCost));
95781   pCost->rCost = SQLITE_BIG_DBL;
95782
95783   /* If the pSrc table is the right table of a LEFT JOIN then we may not
95784   ** use an index to satisfy IS NULL constraints on that table.  This is
95785   ** because columns might end up being NULL if the table does not match -
95786   ** a circumstance which the index cannot help us discover.  Ticket #2177.
95787   */
95788   if( pSrc->jointype & JT_LEFT ){
95789     idxEqTermMask = WO_EQ|WO_IN;
95790   }else{
95791     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
95792   }
95793
95794   if( pSrc->pIndex ){
95795     /* An INDEXED BY clause specifies a particular index to use */
95796     pIdx = pProbe = pSrc->pIndex;
95797     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
95798     eqTermMask = idxEqTermMask;
95799   }else{
95800     /* There is no INDEXED BY clause.  Create a fake Index object to
95801     ** represent the primary key */
95802     Index *pFirst;                /* Any other index on the table */
95803     memset(&sPk, 0, sizeof(Index));
95804     sPk.nColumn = 1;
95805     sPk.aiColumn = &aiColumnPk;
95806     sPk.aiRowEst = aiRowEstPk;
95807     aiRowEstPk[1] = 1;
95808     sPk.onError = OE_Replace;
95809     sPk.pTable = pSrc->pTab;
95810     pFirst = pSrc->pTab->pIndex;
95811     if( pSrc->notIndexed==0 ){
95812       sPk.pNext = pFirst;
95813     }
95814     /* The aiRowEstPk[0] is an estimate of the total number of rows in the
95815     ** table.  Get this information from the ANALYZE information if it is
95816     ** available.  If not available, assume the table 1 million rows in size.
95817     */
95818     if( pFirst ){
95819       assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
95820       aiRowEstPk[0] = pFirst->aiRowEst[0];
95821     }else{
95822       aiRowEstPk[0] = 1000000;
95823     }
95824     pProbe = &sPk;
95825     wsFlagMask = ~(
95826         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
95827     );
95828     eqTermMask = WO_EQ|WO_IN;
95829     pIdx = 0;
95830   }
95831
95832   /* Loop over all indices looking for the best one to use
95833   */
95834   for(; pProbe; pIdx=pProbe=pProbe->pNext){
95835     const unsigned int * const aiRowEst = pProbe->aiRowEst;
95836     double cost;                /* Cost of using pProbe */
95837     double nRow;                /* Estimated number of rows in result set */
95838     int rev;                    /* True to scan in reverse order */
95839     int wsFlags = 0;
95840     Bitmask used = 0;
95841
95842     /* The following variables are populated based on the properties of
95843     ** scan being evaluated. They are then used to determine the expected
95844     ** cost and number of rows returned.
95845     **
95846     **  nEq: 
95847     **    Number of equality terms that can be implemented using the index.
95848     **
95849     **  nInMul:  
95850     **    The "in-multiplier". This is an estimate of how many seek operations 
95851     **    SQLite must perform on the index in question. For example, if the 
95852     **    WHERE clause is:
95853     **
95854     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
95855     **
95856     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
95857     **    set to 9. Given the same schema and either of the following WHERE 
95858     **    clauses:
95859     **
95860     **      WHERE a =  1
95861     **      WHERE a >= 2
95862     **
95863     **    nInMul is set to 1.
95864     **
95865     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
95866     **    the sub-select is assumed to return 25 rows for the purposes of 
95867     **    determining nInMul.
95868     **
95869     **  bInEst:  
95870     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
95871     **    in determining the value of nInMul.
95872     **
95873     **  estBound:
95874     **    An estimate on the amount of the table that must be searched.  A
95875     **    value of 100 means the entire table is searched.  Range constraints
95876     **    might reduce this to a value less than 100 to indicate that only
95877     **    a fraction of the table needs searching.  In the absence of
95878     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
95879     **    space to 1/3rd its original size.  So an x>? constraint reduces
95880     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
95881     **
95882     **  bSort:   
95883     **    Boolean. True if there is an ORDER BY clause that will require an 
95884     **    external sort (i.e. scanning the index being evaluated will not 
95885     **    correctly order records).
95886     **
95887     **  bLookup: 
95888     **    Boolean. True if for each index entry visited a lookup on the 
95889     **    corresponding table b-tree is required. This is always false 
95890     **    for the rowid index. For other indexes, it is true unless all the 
95891     **    columns of the table used by the SELECT statement are present in 
95892     **    the index (such an index is sometimes described as a covering index).
95893     **    For example, given the index on (a, b), the second of the following 
95894     **    two queries requires table b-tree lookups, but the first does not.
95895     **
95896     **             SELECT a, b    FROM tbl WHERE a = 1;
95897     **             SELECT a, b, c FROM tbl WHERE a = 1;
95898     */
95899     int nEq;
95900     int bInEst = 0;
95901     int nInMul = 1;
95902     int estBound = 100;
95903     int nBound = 0;             /* Number of range constraints seen */
95904     int bSort = 0;
95905     int bLookup = 0;
95906     WhereTerm *pTerm;           /* A single term of the WHERE clause */
95907
95908     /* Determine the values of nEq and nInMul */
95909     for(nEq=0; nEq<pProbe->nColumn; nEq++){
95910       int j = pProbe->aiColumn[nEq];
95911       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
95912       if( pTerm==0 ) break;
95913       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
95914       if( pTerm->eOperator & WO_IN ){
95915         Expr *pExpr = pTerm->pExpr;
95916         wsFlags |= WHERE_COLUMN_IN;
95917         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95918           nInMul *= 25;
95919           bInEst = 1;
95920         }else if( ALWAYS(pExpr->x.pList) ){
95921           nInMul *= pExpr->x.pList->nExpr + 1;
95922         }
95923       }else if( pTerm->eOperator & WO_ISNULL ){
95924         wsFlags |= WHERE_COLUMN_NULL;
95925       }
95926       used |= pTerm->prereqRight;
95927     }
95928
95929     /* Determine the value of estBound. */
95930     if( nEq<pProbe->nColumn ){
95931       int j = pProbe->aiColumn[nEq];
95932       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
95933         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
95934         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
95935         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
95936         if( pTop ){
95937           nBound = 1;
95938           wsFlags |= WHERE_TOP_LIMIT;
95939           used |= pTop->prereqRight;
95940         }
95941         if( pBtm ){
95942           nBound++;
95943           wsFlags |= WHERE_BTM_LIMIT;
95944           used |= pBtm->prereqRight;
95945         }
95946         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
95947       }
95948     }else if( pProbe->onError!=OE_None ){
95949       testcase( wsFlags & WHERE_COLUMN_IN );
95950       testcase( wsFlags & WHERE_COLUMN_NULL );
95951       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
95952         wsFlags |= WHERE_UNIQUE;
95953       }
95954     }
95955
95956     /* If there is an ORDER BY clause and the index being considered will
95957     ** naturally scan rows in the required order, set the appropriate flags
95958     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
95959     ** will scan rows in a different order, set the bSort variable.  */
95960     if( pOrderBy ){
95961       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
95962         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
95963       ){
95964         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
95965         wsFlags |= (rev ? WHERE_REVERSE : 0);
95966       }else{
95967         bSort = 1;
95968       }
95969     }
95970
95971     /* If currently calculating the cost of using an index (not the IPK
95972     ** index), determine if all required column data may be obtained without 
95973     ** using the main table (i.e. if the index is a covering
95974     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
95975     ** wsFlags. Otherwise, set the bLookup variable to true.  */
95976     if( pIdx && wsFlags ){
95977       Bitmask m = pSrc->colUsed;
95978       int j;
95979       for(j=0; j<pIdx->nColumn; j++){
95980         int x = pIdx->aiColumn[j];
95981         if( x<BMS-1 ){
95982           m &= ~(((Bitmask)1)<<x);
95983         }
95984       }
95985       if( m==0 ){
95986         wsFlags |= WHERE_IDX_ONLY;
95987       }else{
95988         bLookup = 1;
95989       }
95990     }
95991
95992     /*
95993     ** Estimate the number of rows of output.  For an IN operator,
95994     ** do not let the estimate exceed half the rows in the table.
95995     */
95996     nRow = (double)(aiRowEst[nEq] * nInMul);
95997     if( bInEst && nRow*2>aiRowEst[0] ){
95998       nRow = aiRowEst[0]/2;
95999       nInMul = (int)(nRow / aiRowEst[nEq]);
96000     }
96001
96002     /* Assume constant cost to access a row and logarithmic cost to
96003     ** do a binary search.  Hence, the initial cost is the number of output
96004     ** rows plus log2(table-size) times the number of binary searches.
96005     */
96006     cost = nRow + nInMul*estLog(aiRowEst[0]);
96007
96008     /* Adjust the number of rows and the cost downward to reflect rows
96009     ** that are excluded by range constraints.
96010     */
96011     nRow = (nRow * (double)estBound) / (double)100;
96012     cost = (cost * (double)estBound) / (double)100;
96013
96014     /* Add in the estimated cost of sorting the result
96015     */
96016     if( bSort ){
96017       cost += cost*estLog(cost);
96018     }
96019
96020     /* If all information can be taken directly from the index, we avoid
96021     ** doing table lookups.  This reduces the cost by half.  (Not really -
96022     ** this needs to be fixed.)
96023     */
96024     if( pIdx && bLookup==0 ){
96025       cost /= (double)2;
96026     }
96027     /**** Cost of using this index has now been computed ****/
96028
96029     /* If there are additional constraints on this table that cannot
96030     ** be used with the current index, but which might lower the number
96031     ** of output rows, adjust the nRow value accordingly.  This only 
96032     ** matters if the current index is the least costly, so do not bother
96033     ** with this step if we already know this index will not be chosen.
96034     ** Also, never reduce the output row count below 2 using this step.
96035     **
96036     ** Do not reduce the output row count if pSrc is the only table that
96037     ** is notReady; if notReady is a power of two.  This will be the case
96038     ** when the main sqlite3WhereBegin() loop is scanning for a table with
96039     ** and "optimal" index, and on such a scan the output row count
96040     ** reduction is not valid because it does not update the "pCost->used"
96041     ** bitmap.  The notReady bitmap will also be a power of two when we
96042     ** are scanning for the last table in a 64-way join.  We are willing
96043     ** to bypass this optimization in that corner case.
96044     */
96045     if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
96046       int k;                       /* Loop counter */
96047       int nSkipEq = nEq;           /* Number of == constraints to skip */
96048       int nSkipRange = nBound;     /* Number of < constraints to skip */
96049       Bitmask thisTab;             /* Bitmap for pSrc */
96050
96051       thisTab = getMask(pWC->pMaskSet, iCur);
96052       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
96053         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
96054         if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
96055         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
96056           if( nSkipEq ){
96057             /* Ignore the first nEq equality matches since the index
96058             ** has already accounted for these */
96059             nSkipEq--;
96060           }else{
96061             /* Assume each additional equality match reduces the result
96062             ** set size by a factor of 10 */
96063             nRow /= 10;
96064           }
96065         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
96066           if( nSkipRange ){
96067             /* Ignore the first nBound range constraints since the index
96068             ** has already accounted for these */
96069             nSkipRange--;
96070           }else{
96071             /* Assume each additional range constraint reduces the result
96072             ** set size by a factor of 3 */
96073             nRow /= 3;
96074           }
96075         }else{
96076           /* Any other expression lowers the output row count by half */
96077           nRow /= 2;
96078         }
96079       }
96080       if( nRow<2 ) nRow = 2;
96081     }
96082
96083
96084     WHERETRACE((
96085       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
96086       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
96087       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
96088       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
96089       notReady, nRow, cost, used
96090     ));
96091
96092     /* If this index is the best we have seen so far, then record this
96093     ** index and its cost in the pCost structure.
96094     */
96095     if( (!pIdx || wsFlags)
96096      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
96097     ){
96098       pCost->rCost = cost;
96099       pCost->nRow = nRow;
96100       pCost->used = used;
96101       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
96102       pCost->plan.nEq = nEq;
96103       pCost->plan.u.pIdx = pIdx;
96104     }
96105
96106     /* If there was an INDEXED BY clause, then only that one index is
96107     ** considered. */
96108     if( pSrc->pIndex ) break;
96109
96110     /* Reset masks for the next index in the loop */
96111     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
96112     eqTermMask = idxEqTermMask;
96113   }
96114
96115   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
96116   ** is set, then reverse the order that the index will be scanned
96117   ** in. This is used for application testing, to help find cases
96118   ** where application behaviour depends on the (undefined) order that
96119   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
96120   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
96121     pCost->plan.wsFlags |= WHERE_REVERSE;
96122   }
96123
96124   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
96125   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
96126   assert( pSrc->pIndex==0 
96127        || pCost->plan.u.pIdx==0 
96128        || pCost->plan.u.pIdx==pSrc->pIndex 
96129   );
96130
96131   WHERETRACE(("best index is: %s\n", 
96132     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
96133          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
96134   ));
96135   
96136   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
96137   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
96138   pCost->plan.wsFlags |= eqTermMask;
96139 }
96140
96141 /*
96142 ** Find the query plan for accessing table pSrc->pTab. Write the
96143 ** best query plan and its cost into the WhereCost object supplied 
96144 ** as the last parameter. This function may calculate the cost of
96145 ** both real and virtual table scans.
96146 */
96147 static void bestIndex(
96148   Parse *pParse,              /* The parsing context */
96149   WhereClause *pWC,           /* The WHERE clause */
96150   struct SrcList_item *pSrc,  /* The FROM clause term to search */
96151   Bitmask notReady,           /* Mask of cursors that are not available */
96152   ExprList *pOrderBy,         /* The ORDER BY clause */
96153   WhereCost *pCost            /* Lowest cost query plan */
96154 ){
96155 #ifndef SQLITE_OMIT_VIRTUALTABLE
96156   if( IsVirtual(pSrc->pTab) ){
96157     sqlite3_index_info *p = 0;
96158     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
96159     if( p->needToFreeIdxStr ){
96160       sqlite3_free(p->idxStr);
96161     }
96162     sqlite3DbFree(pParse->db, p);
96163   }else
96164 #endif
96165   {
96166     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
96167   }
96168 }
96169
96170 /*
96171 ** Disable a term in the WHERE clause.  Except, do not disable the term
96172 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
96173 ** or USING clause of that join.
96174 **
96175 ** Consider the term t2.z='ok' in the following queries:
96176 **
96177 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
96178 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
96179 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
96180 **
96181 ** The t2.z='ok' is disabled in the in (2) because it originates
96182 ** in the ON clause.  The term is disabled in (3) because it is not part
96183 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
96184 **
96185 ** Disabling a term causes that term to not be tested in the inner loop
96186 ** of the join.  Disabling is an optimization.  When terms are satisfied
96187 ** by indices, we disable them to prevent redundant tests in the inner
96188 ** loop.  We would get the correct results if nothing were ever disabled,
96189 ** but joins might run a little slower.  The trick is to disable as much
96190 ** as we can without disabling too much.  If we disabled in (1), we'd get
96191 ** the wrong answer.  See ticket #813.
96192 */
96193 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
96194   if( pTerm
96195       && (pTerm->wtFlags & TERM_CODED)==0
96196       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
96197   ){
96198     pTerm->wtFlags |= TERM_CODED;
96199     if( pTerm->iParent>=0 ){
96200       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
96201       if( (--pOther->nChild)==0 ){
96202         disableTerm(pLevel, pOther);
96203       }
96204     }
96205   }
96206 }
96207
96208 /*
96209 ** Code an OP_Affinity opcode to apply the column affinity string zAff
96210 ** to the n registers starting at base. 
96211 **
96212 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
96213 ** beginning and end of zAff are ignored.  If all entries in zAff are
96214 ** SQLITE_AFF_NONE, then no code gets generated.
96215 **
96216 ** This routine makes its own copy of zAff so that the caller is free
96217 ** to modify zAff after this routine returns.
96218 */
96219 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
96220   Vdbe *v = pParse->pVdbe;
96221   if( zAff==0 ){
96222     assert( pParse->db->mallocFailed );
96223     return;
96224   }
96225   assert( v!=0 );
96226
96227   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
96228   ** and end of the affinity string.
96229   */
96230   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
96231     n--;
96232     base++;
96233     zAff++;
96234   }
96235   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
96236     n--;
96237   }
96238
96239   /* Code the OP_Affinity opcode if there is anything left to do. */
96240   if( n>0 ){
96241     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
96242     sqlite3VdbeChangeP4(v, -1, zAff, n);
96243     sqlite3ExprCacheAffinityChange(pParse, base, n);
96244   }
96245 }
96246
96247
96248 /*
96249 ** Generate code for a single equality term of the WHERE clause.  An equality
96250 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
96251 ** coded.
96252 **
96253 ** The current value for the constraint is left in register iReg.
96254 **
96255 ** For a constraint of the form X=expr, the expression is evaluated and its
96256 ** result is left on the stack.  For constraints of the form X IN (...)
96257 ** this routine sets up a loop that will iterate over all values of X.
96258 */
96259 static int codeEqualityTerm(
96260   Parse *pParse,      /* The parsing context */
96261   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
96262   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
96263   int iTarget         /* Attempt to leave results in this register */
96264 ){
96265   Expr *pX = pTerm->pExpr;
96266   Vdbe *v = pParse->pVdbe;
96267   int iReg;                  /* Register holding results */
96268
96269   assert( iTarget>0 );
96270   if( pX->op==TK_EQ ){
96271     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
96272   }else if( pX->op==TK_ISNULL ){
96273     iReg = iTarget;
96274     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
96275 #ifndef SQLITE_OMIT_SUBQUERY
96276   }else{
96277     int eType;
96278     int iTab;
96279     struct InLoop *pIn;
96280
96281     assert( pX->op==TK_IN );
96282     iReg = iTarget;
96283     eType = sqlite3FindInIndex(pParse, pX, 0);
96284     iTab = pX->iTable;
96285     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
96286     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
96287     if( pLevel->u.in.nIn==0 ){
96288       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
96289     }
96290     pLevel->u.in.nIn++;
96291     pLevel->u.in.aInLoop =
96292        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
96293                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
96294     pIn = pLevel->u.in.aInLoop;
96295     if( pIn ){
96296       pIn += pLevel->u.in.nIn - 1;
96297       pIn->iCur = iTab;
96298       if( eType==IN_INDEX_ROWID ){
96299         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
96300       }else{
96301         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
96302       }
96303       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
96304     }else{
96305       pLevel->u.in.nIn = 0;
96306     }
96307 #endif
96308   }
96309   disableTerm(pLevel, pTerm);
96310   return iReg;
96311 }
96312
96313 /*
96314 ** Generate code that will evaluate all == and IN constraints for an
96315 ** index.
96316 **
96317 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
96318 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
96319 ** The index has as many as three equality constraints, but in this
96320 ** example, the third "c" value is an inequality.  So only two 
96321 ** constraints are coded.  This routine will generate code to evaluate
96322 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
96323 ** in consecutive registers and the index of the first register is returned.
96324 **
96325 ** In the example above nEq==2.  But this subroutine works for any value
96326 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
96327 ** The only thing it does is allocate the pLevel->iMem memory cell and
96328 ** compute the affinity string.
96329 **
96330 ** This routine always allocates at least one memory cell and returns
96331 ** the index of that memory cell. The code that
96332 ** calls this routine will use that memory cell to store the termination
96333 ** key value of the loop.  If one or more IN operators appear, then
96334 ** this routine allocates an additional nEq memory cells for internal
96335 ** use.
96336 **
96337 ** Before returning, *pzAff is set to point to a buffer containing a
96338 ** copy of the column affinity string of the index allocated using
96339 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
96340 ** with equality constraints that use NONE affinity are set to
96341 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
96342 **
96343 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
96344 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
96345 **
96346 ** In the example above, the index on t1(a) has TEXT affinity. But since
96347 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
96348 ** no conversion should be attempted before using a t2.b value as part of
96349 ** a key to search the index. Hence the first byte in the returned affinity
96350 ** string in this example would be set to SQLITE_AFF_NONE.
96351 */
96352 static int codeAllEqualityTerms(
96353   Parse *pParse,        /* Parsing context */
96354   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
96355   WhereClause *pWC,     /* The WHERE clause */
96356   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
96357   int nExtraReg,        /* Number of extra registers to allocate */
96358   char **pzAff          /* OUT: Set to point to affinity string */
96359 ){
96360   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
96361   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
96362   Index *pIdx;                  /* The index being used for this loop */
96363   int iCur = pLevel->iTabCur;   /* The cursor of the table */
96364   WhereTerm *pTerm;             /* A single constraint term */
96365   int j;                        /* Loop counter */
96366   int regBase;                  /* Base register */
96367   int nReg;                     /* Number of registers to allocate */
96368   char *zAff;                   /* Affinity string to return */
96369
96370   /* This module is only called on query plans that use an index. */
96371   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
96372   pIdx = pLevel->plan.u.pIdx;
96373
96374   /* Figure out how many memory cells we will need then allocate them.
96375   */
96376   regBase = pParse->nMem + 1;
96377   nReg = pLevel->plan.nEq + nExtraReg;
96378   pParse->nMem += nReg;
96379
96380   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
96381   if( !zAff ){
96382     pParse->db->mallocFailed = 1;
96383   }
96384
96385   /* Evaluate the equality constraints
96386   */
96387   assert( pIdx->nColumn>=nEq );
96388   for(j=0; j<nEq; j++){
96389     int r1;
96390     int k = pIdx->aiColumn[j];
96391     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
96392     if( NEVER(pTerm==0) ) break;
96393     /* The following true for indices with redundant columns. 
96394     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
96395     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
96396     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
96397     if( r1!=regBase+j ){
96398       if( nReg==1 ){
96399         sqlite3ReleaseTempReg(pParse, regBase);
96400         regBase = r1;
96401       }else{
96402         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
96403       }
96404     }
96405     testcase( pTerm->eOperator & WO_ISNULL );
96406     testcase( pTerm->eOperator & WO_IN );
96407     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
96408       Expr *pRight = pTerm->pExpr->pRight;
96409       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
96410       if( zAff ){
96411         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
96412           zAff[j] = SQLITE_AFF_NONE;
96413         }
96414         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
96415           zAff[j] = SQLITE_AFF_NONE;
96416         }
96417       }
96418     }
96419   }
96420   *pzAff = zAff;
96421   return regBase;
96422 }
96423
96424 /*
96425 ** Generate code for the start of the iLevel-th loop in the WHERE clause
96426 ** implementation described by pWInfo.
96427 */
96428 static Bitmask codeOneLoopStart(
96429   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
96430   int iLevel,          /* Which level of pWInfo->a[] should be coded */
96431   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
96432   Bitmask notReady     /* Which tables are currently available */
96433 ){
96434   int j, k;            /* Loop counters */
96435   int iCur;            /* The VDBE cursor for the table */
96436   int addrNxt;         /* Where to jump to continue with the next IN case */
96437   int omitTable;       /* True if we use the index only */
96438   int bRev;            /* True if we need to scan in reverse order */
96439   WhereLevel *pLevel;  /* The where level to be coded */
96440   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
96441   WhereTerm *pTerm;               /* A WHERE clause term */
96442   Parse *pParse;                  /* Parsing context */
96443   Vdbe *v;                        /* The prepared stmt under constructions */
96444   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
96445   int addrBrk;                    /* Jump here to break out of the loop */
96446   int addrCont;                   /* Jump here to continue with next cycle */
96447   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
96448   int iReleaseReg = 0;      /* Temp register to free before returning */
96449
96450   pParse = pWInfo->pParse;
96451   v = pParse->pVdbe;
96452   pWC = pWInfo->pWC;
96453   pLevel = &pWInfo->a[iLevel];
96454   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
96455   iCur = pTabItem->iCursor;
96456   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
96457   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
96458            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
96459
96460   /* Create labels for the "break" and "continue" instructions
96461   ** for the current loop.  Jump to addrBrk to break out of a loop.
96462   ** Jump to cont to go immediately to the next iteration of the
96463   ** loop.
96464   **
96465   ** When there is an IN operator, we also have a "addrNxt" label that
96466   ** means to continue with the next IN value combination.  When
96467   ** there are no IN operators in the constraints, the "addrNxt" label
96468   ** is the same as "addrBrk".
96469   */
96470   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
96471   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
96472
96473   /* If this is the right table of a LEFT OUTER JOIN, allocate and
96474   ** initialize a memory cell that records if this table matches any
96475   ** row of the left table of the join.
96476   */
96477   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
96478     pLevel->iLeftJoin = ++pParse->nMem;
96479     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
96480     VdbeComment((v, "init LEFT JOIN no-match flag"));
96481   }
96482
96483 #ifndef SQLITE_OMIT_VIRTUALTABLE
96484   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
96485     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
96486     **          to access the data.
96487     */
96488     int iReg;   /* P3 Value for OP_VFilter */
96489     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
96490     int nConstraint = pVtabIdx->nConstraint;
96491     struct sqlite3_index_constraint_usage *aUsage =
96492                                                 pVtabIdx->aConstraintUsage;
96493     const struct sqlite3_index_constraint *aConstraint =
96494                                                 pVtabIdx->aConstraint;
96495
96496     sqlite3ExprCachePush(pParse);
96497     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
96498     for(j=1; j<=nConstraint; j++){
96499       for(k=0; k<nConstraint; k++){
96500         if( aUsage[k].argvIndex==j ){
96501           int iTerm = aConstraint[k].iTermOffset;
96502           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
96503           break;
96504         }
96505       }
96506       if( k==nConstraint ) break;
96507     }
96508     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
96509     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
96510     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
96511                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
96512     pVtabIdx->needToFreeIdxStr = 0;
96513     for(j=0; j<nConstraint; j++){
96514       if( aUsage[j].omit ){
96515         int iTerm = aConstraint[j].iTermOffset;
96516         disableTerm(pLevel, &pWC->a[iTerm]);
96517       }
96518     }
96519     pLevel->op = OP_VNext;
96520     pLevel->p1 = iCur;
96521     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96522     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
96523     sqlite3ExprCachePop(pParse, 1);
96524   }else
96525 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96526
96527   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
96528     /* Case 1:  We can directly reference a single row using an
96529     **          equality comparison against the ROWID field.  Or
96530     **          we reference multiple rows using a "rowid IN (...)"
96531     **          construct.
96532     */
96533     iReleaseReg = sqlite3GetTempReg(pParse);
96534     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
96535     assert( pTerm!=0 );
96536     assert( pTerm->pExpr!=0 );
96537     assert( pTerm->leftCursor==iCur );
96538     assert( omitTable==0 );
96539     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
96540     addrNxt = pLevel->addrNxt;
96541     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
96542     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
96543     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96544     VdbeComment((v, "pk"));
96545     pLevel->op = OP_Noop;
96546   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
96547     /* Case 2:  We have an inequality comparison against the ROWID field.
96548     */
96549     int testOp = OP_Noop;
96550     int start;
96551     int memEndValue = 0;
96552     WhereTerm *pStart, *pEnd;
96553
96554     assert( omitTable==0 );
96555     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
96556     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
96557     if( bRev ){
96558       pTerm = pStart;
96559       pStart = pEnd;
96560       pEnd = pTerm;
96561     }
96562     if( pStart ){
96563       Expr *pX;             /* The expression that defines the start bound */
96564       int r1, rTemp;        /* Registers for holding the start boundary */
96565
96566       /* The following constant maps TK_xx codes into corresponding 
96567       ** seek opcodes.  It depends on a particular ordering of TK_xx
96568       */
96569       const u8 aMoveOp[] = {
96570            /* TK_GT */  OP_SeekGt,
96571            /* TK_LE */  OP_SeekLe,
96572            /* TK_LT */  OP_SeekLt,
96573            /* TK_GE */  OP_SeekGe
96574       };
96575       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
96576       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
96577       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
96578
96579       pX = pStart->pExpr;
96580       assert( pX!=0 );
96581       assert( pStart->leftCursor==iCur );
96582       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
96583       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
96584       VdbeComment((v, "pk"));
96585       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
96586       sqlite3ReleaseTempReg(pParse, rTemp);
96587       disableTerm(pLevel, pStart);
96588     }else{
96589       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
96590     }
96591     if( pEnd ){
96592       Expr *pX;
96593       pX = pEnd->pExpr;
96594       assert( pX!=0 );
96595       assert( pEnd->leftCursor==iCur );
96596       memEndValue = ++pParse->nMem;
96597       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
96598       if( pX->op==TK_LT || pX->op==TK_GT ){
96599         testOp = bRev ? OP_Le : OP_Ge;
96600       }else{
96601         testOp = bRev ? OP_Lt : OP_Gt;
96602       }
96603       disableTerm(pLevel, pEnd);
96604     }
96605     start = sqlite3VdbeCurrentAddr(v);
96606     pLevel->op = bRev ? OP_Prev : OP_Next;
96607     pLevel->p1 = iCur;
96608     pLevel->p2 = start;
96609     if( pStart==0 && pEnd==0 ){
96610       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
96611     }else{
96612       assert( pLevel->p5==0 );
96613     }
96614     if( testOp!=OP_Noop ){
96615       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96616       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
96617       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96618       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
96619       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
96620     }
96621   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
96622     /* Case 3: A scan using an index.
96623     **
96624     **         The WHERE clause may contain zero or more equality 
96625     **         terms ("==" or "IN" operators) that refer to the N
96626     **         left-most columns of the index. It may also contain
96627     **         inequality constraints (>, <, >= or <=) on the indexed
96628     **         column that immediately follows the N equalities. Only 
96629     **         the right-most column can be an inequality - the rest must
96630     **         use the "==" and "IN" operators. For example, if the 
96631     **         index is on (x,y,z), then the following clauses are all 
96632     **         optimized:
96633     **
96634     **            x=5
96635     **            x=5 AND y=10
96636     **            x=5 AND y<10
96637     **            x=5 AND y>5 AND y<10
96638     **            x=5 AND y=5 AND z<=10
96639     **
96640     **         The z<10 term of the following cannot be used, only
96641     **         the x=5 term:
96642     **
96643     **            x=5 AND z<10
96644     **
96645     **         N may be zero if there are inequality constraints.
96646     **         If there are no inequality constraints, then N is at
96647     **         least one.
96648     **
96649     **         This case is also used when there are no WHERE clause
96650     **         constraints but an index is selected anyway, in order
96651     **         to force the output order to conform to an ORDER BY.
96652     */  
96653     int aStartOp[] = {
96654       0,
96655       0,
96656       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
96657       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
96658       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
96659       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
96660       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
96661       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
96662     };
96663     int aEndOp[] = {
96664       OP_Noop,             /* 0: (!end_constraints) */
96665       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
96666       OP_IdxLT             /* 2: (end_constraints && bRev) */
96667     };
96668     int nEq = pLevel->plan.nEq;
96669     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
96670     int regBase;                 /* Base register holding constraint values */
96671     int r1;                      /* Temp register */
96672     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
96673     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
96674     int startEq;                 /* True if range start uses ==, >= or <= */
96675     int endEq;                   /* True if range end uses ==, >= or <= */
96676     int start_constraints;       /* Start of range is constrained */
96677     int nConstraint;             /* Number of constraint terms */
96678     Index *pIdx;         /* The index we will be using */
96679     int iIdxCur;         /* The VDBE cursor for the index */
96680     int nExtraReg = 0;   /* Number of extra registers needed */
96681     int op;              /* Instruction opcode */
96682     char *zStartAff;             /* Affinity for start of range constraint */
96683     char *zEndAff;               /* Affinity for end of range constraint */
96684
96685     pIdx = pLevel->plan.u.pIdx;
96686     iIdxCur = pLevel->iIdxCur;
96687     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
96688
96689     /* If this loop satisfies a sort order (pOrderBy) request that 
96690     ** was passed to this function to implement a "SELECT min(x) ..." 
96691     ** query, then the caller will only allow the loop to run for
96692     ** a single iteration. This means that the first row returned
96693     ** should not have a NULL value stored in 'x'. If column 'x' is
96694     ** the first one after the nEq equality constraints in the index,
96695     ** this requires some special handling.
96696     */
96697     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
96698      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
96699      && (pIdx->nColumn>nEq)
96700     ){
96701       /* assert( pOrderBy->nExpr==1 ); */
96702       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
96703       isMinQuery = 1;
96704       nExtraReg = 1;
96705     }
96706
96707     /* Find any inequality constraint terms for the start and end 
96708     ** of the range. 
96709     */
96710     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
96711       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
96712       nExtraReg = 1;
96713     }
96714     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
96715       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
96716       nExtraReg = 1;
96717     }
96718
96719     /* Generate code to evaluate all constraint terms using == or IN
96720     ** and store the values of those terms in an array of registers
96721     ** starting at regBase.
96722     */
96723     regBase = codeAllEqualityTerms(
96724         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
96725     );
96726     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
96727     addrNxt = pLevel->addrNxt;
96728
96729     /* If we are doing a reverse order scan on an ascending index, or
96730     ** a forward order scan on a descending index, interchange the 
96731     ** start and end terms (pRangeStart and pRangeEnd).
96732     */
96733     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
96734       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
96735     }
96736
96737     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
96738     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
96739     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
96740     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
96741     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
96742     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
96743     start_constraints = pRangeStart || nEq>0;
96744
96745     /* Seek the index cursor to the start of the range. */
96746     nConstraint = nEq;
96747     if( pRangeStart ){
96748       Expr *pRight = pRangeStart->pExpr->pRight;
96749       sqlite3ExprCode(pParse, pRight, regBase+nEq);
96750       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96751       if( zStartAff ){
96752         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
96753           /* Since the comparison is to be performed with no conversions
96754           ** applied to the operands, set the affinity to apply to pRight to 
96755           ** SQLITE_AFF_NONE.  */
96756           zStartAff[nEq] = SQLITE_AFF_NONE;
96757         }
96758         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
96759           zStartAff[nEq] = SQLITE_AFF_NONE;
96760         }
96761       }  
96762       nConstraint++;
96763     }else if( isMinQuery ){
96764       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
96765       nConstraint++;
96766       startEq = 0;
96767       start_constraints = 1;
96768     }
96769     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
96770     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
96771     assert( op!=0 );
96772     testcase( op==OP_Rewind );
96773     testcase( op==OP_Last );
96774     testcase( op==OP_SeekGt );
96775     testcase( op==OP_SeekGe );
96776     testcase( op==OP_SeekLe );
96777     testcase( op==OP_SeekLt );
96778     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96779
96780     /* Load the value for the inequality constraint at the end of the
96781     ** range (if any).
96782     */
96783     nConstraint = nEq;
96784     if( pRangeEnd ){
96785       Expr *pRight = pRangeEnd->pExpr->pRight;
96786       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
96787       sqlite3ExprCode(pParse, pRight, regBase+nEq);
96788       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96789       if( zEndAff ){
96790         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
96791           /* Since the comparison is to be performed with no conversions
96792           ** applied to the operands, set the affinity to apply to pRight to 
96793           ** SQLITE_AFF_NONE.  */
96794           zEndAff[nEq] = SQLITE_AFF_NONE;
96795         }
96796         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
96797           zEndAff[nEq] = SQLITE_AFF_NONE;
96798         }
96799       }  
96800       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
96801       nConstraint++;
96802     }
96803     sqlite3DbFree(pParse->db, zStartAff);
96804     sqlite3DbFree(pParse->db, zEndAff);
96805
96806     /* Top of the loop body */
96807     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96808
96809     /* Check if the index cursor is past the end of the range. */
96810     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
96811     testcase( op==OP_Noop );
96812     testcase( op==OP_IdxGE );
96813     testcase( op==OP_IdxLT );
96814     if( op!=OP_Noop ){
96815       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96816       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
96817     }
96818
96819     /* If there are inequality constraints, check that the value
96820     ** of the table column that the inequality contrains is not NULL.
96821     ** If it is, jump to the next iteration of the loop.
96822     */
96823     r1 = sqlite3GetTempReg(pParse);
96824     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
96825     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
96826     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
96827       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
96828       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
96829     }
96830     sqlite3ReleaseTempReg(pParse, r1);
96831
96832     /* Seek the table cursor, if required */
96833     disableTerm(pLevel, pRangeStart);
96834     disableTerm(pLevel, pRangeEnd);
96835     if( !omitTable ){
96836       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96837       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
96838       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96839       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
96840     }
96841
96842     /* Record the instruction used to terminate the loop. Disable 
96843     ** WHERE clause terms made redundant by the index range scan.
96844     */
96845     pLevel->op = bRev ? OP_Prev : OP_Next;
96846     pLevel->p1 = iIdxCur;
96847   }else
96848
96849 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
96850   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
96851     /* Case 4:  Two or more separately indexed terms connected by OR
96852     **
96853     ** Example:
96854     **
96855     **   CREATE TABLE t1(a,b,c,d);
96856     **   CREATE INDEX i1 ON t1(a);
96857     **   CREATE INDEX i2 ON t1(b);
96858     **   CREATE INDEX i3 ON t1(c);
96859     **
96860     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
96861     **
96862     ** In the example, there are three indexed terms connected by OR.
96863     ** The top of the loop looks like this:
96864     **
96865     **          Null       1                # Zero the rowset in reg 1
96866     **
96867     ** Then, for each indexed term, the following. The arguments to
96868     ** RowSetTest are such that the rowid of the current row is inserted
96869     ** into the RowSet. If it is already present, control skips the
96870     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
96871     **
96872     **        sqlite3WhereBegin(<term>)
96873     **          RowSetTest                  # Insert rowid into rowset
96874     **          Gosub      2 A
96875     **        sqlite3WhereEnd()
96876     **
96877     ** Following the above, code to terminate the loop. Label A, the target
96878     ** of the Gosub above, jumps to the instruction right after the Goto.
96879     **
96880     **          Null       1                # Zero the rowset in reg 1
96881     **          Goto       B                # The loop is finished.
96882     **
96883     **       A: <loop body>                 # Return data, whatever.
96884     **
96885     **          Return     2                # Jump back to the Gosub
96886     **
96887     **       B: <after the loop>
96888     **
96889     */
96890     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
96891     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
96892     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
96893
96894     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
96895     int regRowset = 0;                        /* Register for RowSet object */
96896     int regRowid = 0;                         /* Register holding rowid */
96897     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
96898     int iRetInit;                             /* Address of regReturn init */
96899     int untestedTerms = 0;             /* Some terms not completely tested */
96900     int ii;
96901    
96902     pTerm = pLevel->plan.u.pTerm;
96903     assert( pTerm!=0 );
96904     assert( pTerm->eOperator==WO_OR );
96905     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
96906     pOrWc = &pTerm->u.pOrInfo->wc;
96907     pFinal = &pOrWc->a[pOrWc->nTerm-1];
96908     pLevel->op = OP_Return;
96909     pLevel->p1 = regReturn;
96910
96911     /* Set up a new SrcList ni pOrTab containing the table being scanned
96912     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
96913     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
96914     */
96915     if( pWInfo->nLevel>1 ){
96916       int nNotReady;                 /* The number of notReady tables */
96917       struct SrcList_item *origSrc;     /* Original list of tables */
96918       nNotReady = pWInfo->nLevel - iLevel - 1;
96919       pOrTab = sqlite3StackAllocRaw(pParse->db,
96920                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
96921       if( pOrTab==0 ) return notReady;
96922       pOrTab->nAlloc = (i16)(nNotReady + 1);
96923       pOrTab->nSrc = pOrTab->nAlloc;
96924       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
96925       origSrc = pWInfo->pTabList->a;
96926       for(k=1; k<=nNotReady; k++){
96927         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
96928       }
96929     }else{
96930       pOrTab = pWInfo->pTabList;
96931     }
96932
96933     /* Initialize the rowset register to contain NULL. An SQL NULL is 
96934     ** equivalent to an empty rowset.
96935     **
96936     ** Also initialize regReturn to contain the address of the instruction 
96937     ** immediately following the OP_Return at the bottom of the loop. This
96938     ** is required in a few obscure LEFT JOIN cases where control jumps
96939     ** over the top of the loop into the body of it. In this case the 
96940     ** correct response for the end-of-loop code (the OP_Return) is to 
96941     ** fall through to the next instruction, just as an OP_Next does if
96942     ** called on an uninitialized cursor.
96943     */
96944     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96945       regRowset = ++pParse->nMem;
96946       regRowid = ++pParse->nMem;
96947       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
96948     }
96949     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
96950
96951     for(ii=0; ii<pOrWc->nTerm; ii++){
96952       WhereTerm *pOrTerm = &pOrWc->a[ii];
96953       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
96954         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
96955         /* Loop through table entries that match term pOrTerm. */
96956         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
96957                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
96958                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
96959         if( pSubWInfo ){
96960           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96961             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
96962             int r;
96963             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
96964                                          regRowid);
96965             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
96966                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
96967           }
96968           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
96969
96970           /* The pSubWInfo->untestedTerms flag means that this OR term
96971           ** contained one or more AND term from a notReady table.  The
96972           ** terms from the notReady table could not be tested and will
96973           ** need to be tested later.
96974           */
96975           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
96976
96977           /* Finish the loop through table entries that match term pOrTerm. */
96978           sqlite3WhereEnd(pSubWInfo);
96979         }
96980       }
96981     }
96982     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
96983     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
96984     sqlite3VdbeResolveLabel(v, iLoopBody);
96985
96986     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
96987     if( !untestedTerms ) disableTerm(pLevel, pTerm);
96988   }else
96989 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96990
96991   {
96992     /* Case 5:  There is no usable index.  We must do a complete
96993     **          scan of the entire table.
96994     */
96995     static const u8 aStep[] = { OP_Next, OP_Prev };
96996     static const u8 aStart[] = { OP_Rewind, OP_Last };
96997     assert( bRev==0 || bRev==1 );
96998     assert( omitTable==0 );
96999     pLevel->op = aStep[bRev];
97000     pLevel->p1 = iCur;
97001     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
97002     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
97003   }
97004   notReady &= ~getMask(pWC->pMaskSet, iCur);
97005
97006   /* Insert code to test every subexpression that can be completely
97007   ** computed using the current set of tables.
97008   */
97009   k = 0;
97010   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
97011     Expr *pE;
97012     testcase( pTerm->wtFlags & TERM_VIRTUAL );
97013     testcase( pTerm->wtFlags & TERM_CODED );
97014     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97015     if( (pTerm->prereqAll & notReady)!=0 ){
97016       testcase( pWInfo->untestedTerms==0
97017                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
97018       pWInfo->untestedTerms = 1;
97019       continue;
97020     }
97021     pE = pTerm->pExpr;
97022     assert( pE!=0 );
97023     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
97024       continue;
97025     }
97026     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
97027     k = 1;
97028     pTerm->wtFlags |= TERM_CODED;
97029   }
97030
97031   /* For a LEFT OUTER JOIN, generate code that will record the fact that
97032   ** at least one row of the right table has matched the left table.  
97033   */
97034   if( pLevel->iLeftJoin ){
97035     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
97036     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
97037     VdbeComment((v, "record LEFT JOIN hit"));
97038     sqlite3ExprCacheClear(pParse);
97039     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
97040       testcase( pTerm->wtFlags & TERM_VIRTUAL );
97041       testcase( pTerm->wtFlags & TERM_CODED );
97042       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97043       if( (pTerm->prereqAll & notReady)!=0 ){
97044         assert( pWInfo->untestedTerms );
97045         continue;
97046       }
97047       assert( pTerm->pExpr );
97048       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
97049       pTerm->wtFlags |= TERM_CODED;
97050     }
97051   }
97052   sqlite3ReleaseTempReg(pParse, iReleaseReg);
97053
97054   return notReady;
97055 }
97056
97057 #if defined(SQLITE_TEST)
97058 /*
97059 ** The following variable holds a text description of query plan generated
97060 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
97061 ** overwrites the previous.  This information is used for testing and
97062 ** analysis only.
97063 */
97064 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
97065 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
97066
97067 #endif /* SQLITE_TEST */
97068
97069
97070 /*
97071 ** Free a WhereInfo structure
97072 */
97073 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
97074   if( ALWAYS(pWInfo) ){
97075     int i;
97076     for(i=0; i<pWInfo->nLevel; i++){
97077       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
97078       if( pInfo ){
97079         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
97080         if( pInfo->needToFreeIdxStr ){
97081           sqlite3_free(pInfo->idxStr);
97082         }
97083         sqlite3DbFree(db, pInfo);
97084       }
97085       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
97086         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
97087         if( pIdx ){
97088           sqlite3DbFree(db, pIdx->zColAff);
97089           sqlite3DbFree(db, pIdx);
97090         }
97091       }
97092     }
97093     whereClauseClear(pWInfo->pWC);
97094     sqlite3DbFree(db, pWInfo);
97095   }
97096 }
97097
97098
97099 /*
97100 ** Generate the beginning of the loop used for WHERE clause processing.
97101 ** The return value is a pointer to an opaque structure that contains
97102 ** information needed to terminate the loop.  Later, the calling routine
97103 ** should invoke sqlite3WhereEnd() with the return value of this function
97104 ** in order to complete the WHERE clause processing.
97105 **
97106 ** If an error occurs, this routine returns NULL.
97107 **
97108 ** The basic idea is to do a nested loop, one loop for each table in
97109 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
97110 ** same as a SELECT with only a single table in the FROM clause.)  For
97111 ** example, if the SQL is this:
97112 **
97113 **       SELECT * FROM t1, t2, t3 WHERE ...;
97114 **
97115 ** Then the code generated is conceptually like the following:
97116 **
97117 **      foreach row1 in t1 do       \    Code generated
97118 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
97119 **          foreach row3 in t3 do   /
97120 **            ...
97121 **          end                     \    Code generated
97122 **        end                        |-- by sqlite3WhereEnd()
97123 **      end                         /
97124 **
97125 ** Note that the loops might not be nested in the order in which they
97126 ** appear in the FROM clause if a different order is better able to make
97127 ** use of indices.  Note also that when the IN operator appears in
97128 ** the WHERE clause, it might result in additional nested loops for
97129 ** scanning through all values on the right-hand side of the IN.
97130 **
97131 ** There are Btree cursors associated with each table.  t1 uses cursor
97132 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
97133 ** And so forth.  This routine generates code to open those VDBE cursors
97134 ** and sqlite3WhereEnd() generates the code to close them.
97135 **
97136 ** The code that sqlite3WhereBegin() generates leaves the cursors named
97137 ** in pTabList pointing at their appropriate entries.  The [...] code
97138 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
97139 ** data from the various tables of the loop.
97140 **
97141 ** If the WHERE clause is empty, the foreach loops must each scan their
97142 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
97143 ** the tables have indices and there are terms in the WHERE clause that
97144 ** refer to those indices, a complete table scan can be avoided and the
97145 ** code will run much faster.  Most of the work of this routine is checking
97146 ** to see if there are indices that can be used to speed up the loop.
97147 **
97148 ** Terms of the WHERE clause are also used to limit which rows actually
97149 ** make it to the "..." in the middle of the loop.  After each "foreach",
97150 ** terms of the WHERE clause that use only terms in that loop and outer
97151 ** loops are evaluated and if false a jump is made around all subsequent
97152 ** inner loops (or around the "..." if the test occurs within the inner-
97153 ** most loop)
97154 **
97155 ** OUTER JOINS
97156 **
97157 ** An outer join of tables t1 and t2 is conceptally coded as follows:
97158 **
97159 **    foreach row1 in t1 do
97160 **      flag = 0
97161 **      foreach row2 in t2 do
97162 **        start:
97163 **          ...
97164 **          flag = 1
97165 **      end
97166 **      if flag==0 then
97167 **        move the row2 cursor to a null row
97168 **        goto start
97169 **      fi
97170 **    end
97171 **
97172 ** ORDER BY CLAUSE PROCESSING
97173 **
97174 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
97175 ** if there is one.  If there is no ORDER BY clause or if this routine
97176 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
97177 **
97178 ** If an index can be used so that the natural output order of the table
97179 ** scan is correct for the ORDER BY clause, then that index is used and
97180 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
97181 ** unnecessary sort of the result set if an index appropriate for the
97182 ** ORDER BY clause already exists.
97183 **
97184 ** If the where clause loops cannot be arranged to provide the correct
97185 ** output order, then the *ppOrderBy is unchanged.
97186 */
97187 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
97188   Parse *pParse,        /* The parser context */
97189   SrcList *pTabList,    /* A list of all tables to be scanned */
97190   Expr *pWhere,         /* The WHERE clause */
97191   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
97192   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
97193 ){
97194   int i;                     /* Loop counter */
97195   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
97196   int nTabList;              /* Number of elements in pTabList */
97197   WhereInfo *pWInfo;         /* Will become the return value of this function */
97198   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
97199   Bitmask notReady;          /* Cursors that are not yet positioned */
97200   WhereMaskSet *pMaskSet;    /* The expression mask set */
97201   WhereClause *pWC;               /* Decomposition of the WHERE clause */
97202   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
97203   WhereLevel *pLevel;             /* A single level in the pWInfo list */
97204   int iFrom;                      /* First unused FROM clause element */
97205   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
97206   sqlite3 *db;               /* Database connection */
97207
97208   /* The number of tables in the FROM clause is limited by the number of
97209   ** bits in a Bitmask 
97210   */
97211   testcase( pTabList->nSrc==BMS );
97212   if( pTabList->nSrc>BMS ){
97213     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
97214     return 0;
97215   }
97216
97217   /* This function normally generates a nested loop for all tables in 
97218   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
97219   ** only generate code for the first table in pTabList and assume that
97220   ** any cursors associated with subsequent tables are uninitialized.
97221   */
97222   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
97223
97224   /* Allocate and initialize the WhereInfo structure that will become the
97225   ** return value. A single allocation is used to store the WhereInfo
97226   ** struct, the contents of WhereInfo.a[], the WhereClause structure
97227   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
97228   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
97229   ** some architectures. Hence the ROUND8() below.
97230   */
97231   db = pParse->db;
97232   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
97233   pWInfo = sqlite3DbMallocZero(db, 
97234       nByteWInfo + 
97235       sizeof(WhereClause) +
97236       sizeof(WhereMaskSet)
97237   );
97238   if( db->mallocFailed ){
97239     sqlite3DbFree(db, pWInfo);
97240     pWInfo = 0;
97241     goto whereBeginError;
97242   }
97243   pWInfo->nLevel = nTabList;
97244   pWInfo->pParse = pParse;
97245   pWInfo->pTabList = pTabList;
97246   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
97247   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
97248   pWInfo->wctrlFlags = wctrlFlags;
97249   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
97250   pMaskSet = (WhereMaskSet*)&pWC[1];
97251
97252   /* Split the WHERE clause into separate subexpressions where each
97253   ** subexpression is separated by an AND operator.
97254   */
97255   initMaskSet(pMaskSet);
97256   whereClauseInit(pWC, pParse, pMaskSet);
97257   sqlite3ExprCodeConstants(pParse, pWhere);
97258   whereSplit(pWC, pWhere, TK_AND);
97259     
97260   /* Special case: a WHERE clause that is constant.  Evaluate the
97261   ** expression and either jump over all of the code or fall thru.
97262   */
97263   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
97264     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
97265     pWhere = 0;
97266   }
97267
97268   /* Assign a bit from the bitmask to every term in the FROM clause.
97269   **
97270   ** When assigning bitmask values to FROM clause cursors, it must be
97271   ** the case that if X is the bitmask for the N-th FROM clause term then
97272   ** the bitmask for all FROM clause terms to the left of the N-th term
97273   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
97274   ** its Expr.iRightJoinTable value to find the bitmask of the right table
97275   ** of the join.  Subtracting one from the right table bitmask gives a
97276   ** bitmask for all tables to the left of the join.  Knowing the bitmask
97277   ** for all tables to the left of a left join is important.  Ticket #3015.
97278   **
97279   ** Configure the WhereClause.vmask variable so that bits that correspond
97280   ** to virtual table cursors are set. This is used to selectively disable 
97281   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
97282   ** with virtual tables.
97283   **
97284   ** Note that bitmasks are created for all pTabList->nSrc tables in
97285   ** pTabList, not just the first nTabList tables.  nTabList is normally
97286   ** equal to pTabList->nSrc but might be shortened to 1 if the
97287   ** WHERE_ONETABLE_ONLY flag is set.
97288   */
97289   assert( pWC->vmask==0 && pMaskSet->n==0 );
97290   for(i=0; i<pTabList->nSrc; i++){
97291     createMask(pMaskSet, pTabList->a[i].iCursor);
97292 #ifndef SQLITE_OMIT_VIRTUALTABLE
97293     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
97294       pWC->vmask |= ((Bitmask)1 << i);
97295     }
97296 #endif
97297   }
97298 #ifndef NDEBUG
97299   {
97300     Bitmask toTheLeft = 0;
97301     for(i=0; i<pTabList->nSrc; i++){
97302       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
97303       assert( (m-1)==toTheLeft );
97304       toTheLeft |= m;
97305     }
97306   }
97307 #endif
97308
97309   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
97310   ** add new virtual terms onto the end of the WHERE clause.  We do not
97311   ** want to analyze these virtual terms, so start analyzing at the end
97312   ** and work forward so that the added virtual terms are never processed.
97313   */
97314   exprAnalyzeAll(pTabList, pWC);
97315   if( db->mallocFailed ){
97316     goto whereBeginError;
97317   }
97318
97319   /* Chose the best index to use for each table in the FROM clause.
97320   **
97321   ** This loop fills in the following fields:
97322   **
97323   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
97324   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
97325   **   pWInfo->a[].nEq       The number of == and IN constraints
97326   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
97327   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
97328   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
97329   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
97330   **
97331   ** This loop also figures out the nesting order of tables in the FROM
97332   ** clause.
97333   */
97334   notReady = ~(Bitmask)0;
97335   pTabItem = pTabList->a;
97336   pLevel = pWInfo->a;
97337   andFlags = ~0;
97338   WHERETRACE(("*** Optimizer Start ***\n"));
97339   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
97340     WhereCost bestPlan;         /* Most efficient plan seen so far */
97341     Index *pIdx;                /* Index for FROM table at pTabItem */
97342     int j;                      /* For looping over FROM tables */
97343     int bestJ = -1;             /* The value of j */
97344     Bitmask m;                  /* Bitmask value for j or bestJ */
97345     int isOptimal;              /* Iterator for optimal/non-optimal search */
97346
97347     memset(&bestPlan, 0, sizeof(bestPlan));
97348     bestPlan.rCost = SQLITE_BIG_DBL;
97349
97350     /* Loop through the remaining entries in the FROM clause to find the
97351     ** next nested loop. The loop tests all FROM clause entries
97352     ** either once or twice. 
97353     **
97354     ** The first test is always performed if there are two or more entries
97355     ** remaining and never performed if there is only one FROM clause entry
97356     ** to choose from.  The first test looks for an "optimal" scan.  In
97357     ** this context an optimal scan is one that uses the same strategy
97358     ** for the given FROM clause entry as would be selected if the entry
97359     ** were used as the innermost nested loop.  In other words, a table
97360     ** is chosen such that the cost of running that table cannot be reduced
97361     ** by waiting for other tables to run first.  This "optimal" test works
97362     ** by first assuming that the FROM clause is on the inner loop and finding
97363     ** its query plan, then checking to see if that query plan uses any
97364     ** other FROM clause terms that are notReady.  If no notReady terms are
97365     ** used then the "optimal" query plan works.
97366     **
97367     ** The second loop iteration is only performed if no optimal scan
97368     ** strategies were found by the first loop. This 2nd iteration is used to
97369     ** search for the lowest cost scan overall.
97370     **
97371     ** Previous versions of SQLite performed only the second iteration -
97372     ** the next outermost loop was always that with the lowest overall
97373     ** cost. However, this meant that SQLite could select the wrong plan
97374     ** for scripts such as the following:
97375     **   
97376     **   CREATE TABLE t1(a, b); 
97377     **   CREATE TABLE t2(c, d);
97378     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
97379     **
97380     ** The best strategy is to iterate through table t1 first. However it
97381     ** is not possible to determine this with a simple greedy algorithm.
97382     ** However, since the cost of a linear scan through table t2 is the same 
97383     ** as the cost of a linear scan through table t1, a simple greedy 
97384     ** algorithm may choose to use t2 for the outer loop, which is a much
97385     ** costlier approach.
97386     */
97387     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
97388       Bitmask mask;  /* Mask of tables not yet ready */
97389       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
97390         int doNotReorder;    /* True if this table should not be reordered */
97391         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
97392         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
97393   
97394         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
97395         if( j!=iFrom && doNotReorder ) break;
97396         m = getMask(pMaskSet, pTabItem->iCursor);
97397         if( (m & notReady)==0 ){
97398           if( j==iFrom ) iFrom++;
97399           continue;
97400         }
97401         mask = (isOptimal ? m : notReady);
97402         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
97403   
97404         assert( pTabItem->pTab );
97405 #ifndef SQLITE_OMIT_VIRTUALTABLE
97406         if( IsVirtual(pTabItem->pTab) ){
97407           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
97408           bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
97409         }else 
97410 #endif
97411         {
97412           bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
97413         }
97414         assert( isOptimal || (sCost.used&notReady)==0 );
97415
97416         if( (sCost.used&notReady)==0
97417          && (bestJ<0 || sCost.rCost<bestPlan.rCost
97418              || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
97419         ){
97420           WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
97421                       sCost.rCost, sCost.nRow));
97422           bestPlan = sCost;
97423           bestJ = j;
97424         }
97425         if( doNotReorder ) break;
97426       }
97427     }
97428     assert( bestJ>=0 );
97429     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
97430     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
97431            pLevel-pWInfo->a));
97432     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
97433       *ppOrderBy = 0;
97434     }
97435     andFlags &= bestPlan.plan.wsFlags;
97436     pLevel->plan = bestPlan.plan;
97437     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
97438     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
97439     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
97440       pLevel->iIdxCur = pParse->nTab++;
97441     }else{
97442       pLevel->iIdxCur = -1;
97443     }
97444     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
97445     pLevel->iFrom = (u8)bestJ;
97446     if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
97447
97448     /* Check that if the table scanned by this loop iteration had an
97449     ** INDEXED BY clause attached to it, that the named index is being
97450     ** used for the scan. If not, then query compilation has failed.
97451     ** Return an error.
97452     */
97453     pIdx = pTabList->a[bestJ].pIndex;
97454     if( pIdx ){
97455       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
97456         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
97457         goto whereBeginError;
97458       }else{
97459         /* If an INDEXED BY clause is used, the bestIndex() function is
97460         ** guaranteed to find the index specified in the INDEXED BY clause
97461         ** if it find an index at all. */
97462         assert( bestPlan.plan.u.pIdx==pIdx );
97463       }
97464     }
97465   }
97466   WHERETRACE(("*** Optimizer Finished ***\n"));
97467   if( pParse->nErr || db->mallocFailed ){
97468     goto whereBeginError;
97469   }
97470
97471   /* If the total query only selects a single row, then the ORDER BY
97472   ** clause is irrelevant.
97473   */
97474   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
97475     *ppOrderBy = 0;
97476   }
97477
97478   /* If the caller is an UPDATE or DELETE statement that is requesting
97479   ** to use a one-pass algorithm, determine if this is appropriate.
97480   ** The one-pass algorithm only works if the WHERE clause constraints
97481   ** the statement to update a single row.
97482   */
97483   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
97484   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
97485     pWInfo->okOnePass = 1;
97486     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
97487   }
97488
97489   /* Open all tables in the pTabList and any indices selected for
97490   ** searching those tables.
97491   */
97492   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
97493   notReady = ~(Bitmask)0;
97494   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
97495     Table *pTab;     /* Table to open */
97496     int iDb;         /* Index of database containing table/index */
97497
97498 #ifndef SQLITE_OMIT_EXPLAIN
97499     if( pParse->explain==2 ){
97500       char *zMsg;
97501       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
97502       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
97503       if( pItem->zAlias ){
97504         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
97505       }
97506       if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97507         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
97508       }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97509         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
97510            zMsg, pLevel->plan.u.pIdx->zName);
97511       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
97512         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
97513       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97514         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
97515       }
97516 #ifndef SQLITE_OMIT_VIRTUALTABLE
97517       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97518         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
97519         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
97520                     pVtabIdx->idxNum, pVtabIdx->idxStr);
97521       }
97522 #endif
97523       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
97524         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
97525       }
97526       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
97527     }
97528 #endif /* SQLITE_OMIT_EXPLAIN */
97529     pTabItem = &pTabList->a[pLevel->iFrom];
97530     pTab = pTabItem->pTab;
97531     pLevel->iTabCur = pTabItem->iCursor;
97532     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97533     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
97534       /* Do nothing */
97535     }else
97536 #ifndef SQLITE_OMIT_VIRTUALTABLE
97537     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97538       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
97539       int iCur = pTabItem->iCursor;
97540       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
97541     }else
97542 #endif
97543     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97544          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
97545       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
97546       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
97547       testcase( pTab->nCol==BMS-1 );
97548       testcase( pTab->nCol==BMS );
97549       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
97550         Bitmask b = pTabItem->colUsed;
97551         int n = 0;
97552         for(; b; b=b>>1, n++){}
97553         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
97554                             SQLITE_INT_TO_PTR(n), P4_INT32);
97555         assert( n<=pTab->nCol );
97556       }
97557     }else{
97558       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97559     }
97560 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97561     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97562       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
97563     }else
97564 #endif
97565     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97566       Index *pIx = pLevel->plan.u.pIdx;
97567       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
97568       int iIdxCur = pLevel->iIdxCur;
97569       assert( pIx->pSchema==pTab->pSchema );
97570       assert( iIdxCur>=0 );
97571       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
97572                         (char*)pKey, P4_KEYINFO_HANDOFF);
97573       VdbeComment((v, "%s", pIx->zName));
97574     }
97575     sqlite3CodeVerifySchema(pParse, iDb);
97576     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
97577   }
97578   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
97579   if( db->mallocFailed ) goto whereBeginError;
97580
97581   /* Generate the code to do the search.  Each iteration of the for
97582   ** loop below generates code for a single nested loop of the VM
97583   ** program.
97584   */
97585   notReady = ~(Bitmask)0;
97586   for(i=0; i<nTabList; i++){
97587     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
97588     pWInfo->iContinue = pWInfo->a[i].addrCont;
97589   }
97590
97591 #ifdef SQLITE_TEST  /* For testing and debugging use only */
97592   /* Record in the query plan information about the current table
97593   ** and the index used to access it (if any).  If the table itself
97594   ** is not used, its name is just '{}'.  If no index is used
97595   ** the index is listed as "{}".  If the primary key is used the
97596   ** index name is '*'.
97597   */
97598   for(i=0; i<nTabList; i++){
97599     char *z;
97600     int n;
97601     pLevel = &pWInfo->a[i];
97602     pTabItem = &pTabList->a[pLevel->iFrom];
97603     z = pTabItem->zAlias;
97604     if( z==0 ) z = pTabItem->pTab->zName;
97605     n = sqlite3Strlen30(z);
97606     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
97607       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
97608         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
97609         nQPlan += 2;
97610       }else{
97611         memcpy(&sqlite3_query_plan[nQPlan], z, n);
97612         nQPlan += n;
97613       }
97614       sqlite3_query_plan[nQPlan++] = ' ';
97615     }
97616     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
97617     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
97618     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97619       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
97620       nQPlan += 2;
97621     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97622       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
97623       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
97624         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
97625         nQPlan += n;
97626         sqlite3_query_plan[nQPlan++] = ' ';
97627       }
97628     }else{
97629       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
97630       nQPlan += 3;
97631     }
97632   }
97633   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
97634     sqlite3_query_plan[--nQPlan] = 0;
97635   }
97636   sqlite3_query_plan[nQPlan] = 0;
97637   nQPlan = 0;
97638 #endif /* SQLITE_TEST // Testing and debugging use only */
97639
97640   /* Record the continuation address in the WhereInfo structure.  Then
97641   ** clean up and return.
97642   */
97643   return pWInfo;
97644
97645   /* Jump here if malloc fails */
97646 whereBeginError:
97647   if( pWInfo ){
97648     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97649     whereInfoFree(db, pWInfo);
97650   }
97651   return 0;
97652 }
97653
97654 /*
97655 ** Generate the end of the WHERE loop.  See comments on 
97656 ** sqlite3WhereBegin() for additional information.
97657 */
97658 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
97659   Parse *pParse = pWInfo->pParse;
97660   Vdbe *v = pParse->pVdbe;
97661   int i;
97662   WhereLevel *pLevel;
97663   SrcList *pTabList = pWInfo->pTabList;
97664   sqlite3 *db = pParse->db;
97665
97666   /* Generate loop termination code.
97667   */
97668   sqlite3ExprCacheClear(pParse);
97669   for(i=pWInfo->nLevel-1; i>=0; i--){
97670     pLevel = &pWInfo->a[i];
97671     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
97672     if( pLevel->op!=OP_Noop ){
97673       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
97674       sqlite3VdbeChangeP5(v, pLevel->p5);
97675     }
97676     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
97677       struct InLoop *pIn;
97678       int j;
97679       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
97680       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
97681         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
97682         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
97683         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
97684       }
97685       sqlite3DbFree(db, pLevel->u.in.aInLoop);
97686     }
97687     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
97688     if( pLevel->iLeftJoin ){
97689       int addr;
97690       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
97691       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97692            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
97693       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
97694         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
97695       }
97696       if( pLevel->iIdxCur>=0 ){
97697         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
97698       }
97699       if( pLevel->op==OP_Return ){
97700         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
97701       }else{
97702         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
97703       }
97704       sqlite3VdbeJumpHere(v, addr);
97705     }
97706   }
97707
97708   /* The "break" point is here, just past the end of the outer loop.
97709   ** Set it.
97710   */
97711   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
97712
97713   /* Close all of the cursors that were opened by sqlite3WhereBegin.
97714   */
97715   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
97716   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
97717     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
97718     Table *pTab = pTabItem->pTab;
97719     assert( pTab!=0 );
97720     if( (pTab->tabFlags & TF_Ephemeral)==0
97721      && pTab->pSelect==0
97722      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
97723     ){
97724       int ws = pLevel->plan.wsFlags;
97725       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
97726         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
97727       }
97728       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
97729         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
97730       }
97731     }
97732
97733     /* If this scan uses an index, make code substitutions to read data
97734     ** from the index in preference to the table. Sometimes, this means
97735     ** the table need never be read from. This is a performance boost,
97736     ** as the vdbe level waits until the table is read before actually
97737     ** seeking the table cursor to the record corresponding to the current
97738     ** position in the index.
97739     ** 
97740     ** Calls to the code generator in between sqlite3WhereBegin and
97741     ** sqlite3WhereEnd will have created code that references the table
97742     ** directly.  This loop scans all that code looking for opcodes
97743     ** that reference the table and converts them into opcodes that
97744     ** reference the index.
97745     */
97746     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
97747       int k, j, last;
97748       VdbeOp *pOp;
97749       Index *pIdx = pLevel->plan.u.pIdx;
97750
97751       assert( pIdx!=0 );
97752       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
97753       last = sqlite3VdbeCurrentAddr(v);
97754       for(k=pWInfo->iTop; k<last; k++, pOp++){
97755         if( pOp->p1!=pLevel->iTabCur ) continue;
97756         if( pOp->opcode==OP_Column ){
97757           for(j=0; j<pIdx->nColumn; j++){
97758             if( pOp->p2==pIdx->aiColumn[j] ){
97759               pOp->p2 = j;
97760               pOp->p1 = pLevel->iIdxCur;
97761               break;
97762             }
97763           }
97764           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97765                || j<pIdx->nColumn );
97766         }else if( pOp->opcode==OP_Rowid ){
97767           pOp->p1 = pLevel->iIdxCur;
97768           pOp->opcode = OP_IdxRowid;
97769         }
97770       }
97771     }
97772   }
97773
97774   /* Final cleanup
97775   */
97776   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97777   whereInfoFree(db, pWInfo);
97778   return;
97779 }
97780
97781 /************** End of where.c ***********************************************/
97782 /************** Begin file parse.c *******************************************/
97783 /* Driver template for the LEMON parser generator.
97784 ** The author disclaims copyright to this source code.
97785 **
97786 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
97787 ** The only modifications are the addition of a couple of NEVER()
97788 ** macros to disable tests that are needed in the case of a general
97789 ** LALR(1) grammar but which are always false in the
97790 ** specific grammar used by SQLite.
97791 */
97792 /* First off, code is included that follows the "include" declaration
97793 ** in the input grammar file. */
97794
97795
97796 /*
97797 ** Disable all error recovery processing in the parser push-down
97798 ** automaton.
97799 */
97800 #define YYNOERRORRECOVERY 1
97801
97802 /*
97803 ** Make yytestcase() the same as testcase()
97804 */
97805 #define yytestcase(X) testcase(X)
97806
97807 /*
97808 ** An instance of this structure holds information about the
97809 ** LIMIT clause of a SELECT statement.
97810 */
97811 struct LimitVal {
97812   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
97813   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
97814 };
97815
97816 /*
97817 ** An instance of this structure is used to store the LIKE,
97818 ** GLOB, NOT LIKE, and NOT GLOB operators.
97819 */
97820 struct LikeOp {
97821   Token eOperator;  /* "like" or "glob" or "regexp" */
97822   int not;         /* True if the NOT keyword is present */
97823 };
97824
97825 /*
97826 ** An instance of the following structure describes the event of a
97827 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
97828 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
97829 **
97830 **      UPDATE ON (a,b,c)
97831 **
97832 ** Then the "b" IdList records the list "a,b,c".
97833 */
97834 struct TrigEvent { int a; IdList * b; };
97835
97836 /*
97837 ** An instance of this structure holds the ATTACH key and the key type.
97838 */
97839 struct AttachKey { int type;  Token key; };
97840
97841
97842   /* This is a utility routine used to set the ExprSpan.zStart and
97843   ** ExprSpan.zEnd values of pOut so that the span covers the complete
97844   ** range of text beginning with pStart and going to the end of pEnd.
97845   */
97846   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
97847     pOut->zStart = pStart->z;
97848     pOut->zEnd = &pEnd->z[pEnd->n];
97849   }
97850
97851   /* Construct a new Expr object from a single identifier.  Use the
97852   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
97853   ** that created the expression.
97854   */
97855   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
97856     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
97857     pOut->zStart = pValue->z;
97858     pOut->zEnd = &pValue->z[pValue->n];
97859   }
97860
97861   /* This routine constructs a binary expression node out of two ExprSpan
97862   ** objects and uses the result to populate a new ExprSpan object.
97863   */
97864   static void spanBinaryExpr(
97865     ExprSpan *pOut,     /* Write the result here */
97866     Parse *pParse,      /* The parsing context.  Errors accumulate here */
97867     int op,             /* The binary operation */
97868     ExprSpan *pLeft,    /* The left operand */
97869     ExprSpan *pRight    /* The right operand */
97870   ){
97871     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
97872     pOut->zStart = pLeft->zStart;
97873     pOut->zEnd = pRight->zEnd;
97874   }
97875
97876   /* Construct an expression node for a unary postfix operator
97877   */
97878   static void spanUnaryPostfix(
97879     ExprSpan *pOut,        /* Write the new expression node here */
97880     Parse *pParse,         /* Parsing context to record errors */
97881     int op,                /* The operator */
97882     ExprSpan *pOperand,    /* The operand */
97883     Token *pPostOp         /* The operand token for setting the span */
97884   ){
97885     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97886     pOut->zStart = pOperand->zStart;
97887     pOut->zEnd = &pPostOp->z[pPostOp->n];
97888   }                           
97889
97890   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
97891   ** unary TK_ISNULL or TK_NOTNULL expression. */
97892   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
97893     sqlite3 *db = pParse->db;
97894     if( db->mallocFailed==0 && pY->op==TK_NULL ){
97895       pA->op = (u8)op;
97896       sqlite3ExprDelete(db, pA->pRight);
97897       pA->pRight = 0;
97898     }
97899   }
97900
97901   /* Construct an expression node for a unary prefix operator
97902   */
97903   static void spanUnaryPrefix(
97904     ExprSpan *pOut,        /* Write the new expression node here */
97905     Parse *pParse,         /* Parsing context to record errors */
97906     int op,                /* The operator */
97907     ExprSpan *pOperand,    /* The operand */
97908     Token *pPreOp         /* The operand token for setting the span */
97909   ){
97910     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97911     pOut->zStart = pPreOp->z;
97912     pOut->zEnd = pOperand->zEnd;
97913   }
97914 /* Next is all token values, in a form suitable for use by makeheaders.
97915 ** This section will be null unless lemon is run with the -m switch.
97916 */
97917 /* 
97918 ** These constants (all generated automatically by the parser generator)
97919 ** specify the various kinds of tokens (terminals) that the parser
97920 ** understands. 
97921 **
97922 ** Each symbol here is a terminal symbol in the grammar.
97923 */
97924 /* Make sure the INTERFACE macro is defined.
97925 */
97926 #ifndef INTERFACE
97927 # define INTERFACE 1
97928 #endif
97929 /* The next thing included is series of defines which control
97930 ** various aspects of the generated parser.
97931 **    YYCODETYPE         is the data type used for storing terminal
97932 **                       and nonterminal numbers.  "unsigned char" is
97933 **                       used if there are fewer than 250 terminals
97934 **                       and nonterminals.  "int" is used otherwise.
97935 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
97936 **                       to no legal terminal or nonterminal number.  This
97937 **                       number is used to fill in empty slots of the hash 
97938 **                       table.
97939 **    YYFALLBACK         If defined, this indicates that one or more tokens
97940 **                       have fall-back values which should be used if the
97941 **                       original value of the token will not parse.
97942 **    YYACTIONTYPE       is the data type used for storing terminal
97943 **                       and nonterminal numbers.  "unsigned char" is
97944 **                       used if there are fewer than 250 rules and
97945 **                       states combined.  "int" is used otherwise.
97946 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
97947 **                       directly to the parser from the tokenizer.
97948 **    YYMINORTYPE        is the data type used for all minor tokens.
97949 **                       This is typically a union of many types, one of
97950 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
97951 **                       for base tokens is called "yy0".
97952 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
97953 **                       zero the stack is dynamically sized using realloc()
97954 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
97955 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
97956 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
97957 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
97958 **    YYNSTATE           the combined number of states.
97959 **    YYNRULE            the number of rules in the grammar
97960 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
97961 **                       defined, then do no error processing.
97962 */
97963 #define YYCODETYPE unsigned char
97964 #define YYNOCODE 253
97965 #define YYACTIONTYPE unsigned short int
97966 #define YYWILDCARD 67
97967 #define sqlite3ParserTOKENTYPE Token
97968 typedef union {
97969   int yyinit;
97970   sqlite3ParserTOKENTYPE yy0;
97971   int yy4;
97972   struct TrigEvent yy90;
97973   ExprSpan yy118;
97974   TriggerStep* yy203;
97975   u8 yy210;
97976   struct {int value; int mask;} yy215;
97977   SrcList* yy259;
97978   struct LimitVal yy292;
97979   Expr* yy314;
97980   ExprList* yy322;
97981   struct LikeOp yy342;
97982   IdList* yy384;
97983   Select* yy387;
97984 } YYMINORTYPE;
97985 #ifndef YYSTACKDEPTH
97986 #define YYSTACKDEPTH 100
97987 #endif
97988 #define sqlite3ParserARG_SDECL Parse *pParse;
97989 #define sqlite3ParserARG_PDECL ,Parse *pParse
97990 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
97991 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
97992 #define YYNSTATE 630
97993 #define YYNRULE 329
97994 #define YYFALLBACK 1
97995 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
97996 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
97997 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
97998
97999 /* The yyzerominor constant is used to initialize instances of
98000 ** YYMINORTYPE objects to zero. */
98001 static const YYMINORTYPE yyzerominor = { 0 };
98002
98003 /* Define the yytestcase() macro to be a no-op if is not already defined
98004 ** otherwise.
98005 **
98006 ** Applications can choose to define yytestcase() in the %include section
98007 ** to a macro that can assist in verifying code coverage.  For production
98008 ** code the yytestcase() macro should be turned off.  But it is useful
98009 ** for testing.
98010 */
98011 #ifndef yytestcase
98012 # define yytestcase(X)
98013 #endif
98014
98015
98016 /* Next are the tables used to determine what action to take based on the
98017 ** current state and lookahead token.  These tables are used to implement
98018 ** functions that take a state number and lookahead value and return an
98019 ** action integer.  
98020 **
98021 ** Suppose the action integer is N.  Then the action is determined as
98022 ** follows
98023 **
98024 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
98025 **                                      token onto the stack and goto state N.
98026 **
98027 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
98028 **
98029 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
98030 **
98031 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
98032 **
98033 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
98034 **                                      slots in the yy_action[] table.
98035 **
98036 ** The action table is constructed as a single large table named yy_action[].
98037 ** Given state S and lookahead X, the action is computed as
98038 **
98039 **      yy_action[ yy_shift_ofst[S] + X ]
98040 **
98041 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
98042 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
98043 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
98044 ** and that yy_default[S] should be used instead.  
98045 **
98046 ** The formula above is for computing the action when the lookahead is
98047 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
98048 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
98049 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
98050 ** YY_SHIFT_USE_DFLT.
98051 **
98052 ** The following are the tables generated in this section:
98053 **
98054 **  yy_action[]        A single table containing all actions.
98055 **  yy_lookahead[]     A table containing the lookahead for each entry in
98056 **                     yy_action.  Used to detect hash collisions.
98057 **  yy_shift_ofst[]    For each state, the offset into yy_action for
98058 **                     shifting terminals.
98059 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
98060 **                     shifting non-terminals after a reduce.
98061 **  yy_default[]       Default action for each state.
98062 */
98063 #define YY_ACTTAB_COUNT (1557)
98064 static const YYACTIONTYPE yy_action[] = {
98065  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
98066  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
98067  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
98068  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
98069  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
98070  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98071  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
98072  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
98073  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98074  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
98075  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
98076  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
98077  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
98078  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
98079  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
98080  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
98081  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
98082  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
98083  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
98084  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
98085  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98086  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98087  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
98088  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
98089  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
98090  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
98091  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
98092  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
98093  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
98094  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
98095  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
98096  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
98097  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
98098  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
98099  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
98100  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
98101  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98102  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
98103  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
98104  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
98105  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
98106  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
98107  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98108  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
98109  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
98110  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
98111  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
98112  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
98113  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
98114  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
98115  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
98116  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
98117  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
98118  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
98119  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
98120  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
98121  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
98122  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98123  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98124  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
98125  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
98126  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
98127  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
98128  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
98129  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
98130  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
98131  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
98132  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
98133  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
98134  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
98135  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
98136  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
98137  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
98138  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98139  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
98140  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
98141  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
98142  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
98143  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
98144  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98145  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
98146  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
98147  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
98148  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
98149  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
98150  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
98151  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
98152  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
98153  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
98154  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
98155  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
98156  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
98157  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
98158  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
98159  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98160  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98161  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
98162  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
98163  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
98164  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
98165  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
98166  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
98167  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
98168  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
98169  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
98170  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
98171  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
98172  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
98173  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
98174  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
98175  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98176  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
98177  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
98178  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
98179  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
98180  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
98181  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
98182  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
98183  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
98184  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
98185  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
98186  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
98187  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
98188  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
98189  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
98190  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
98191  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
98192  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
98193  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
98194  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
98195  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
98196  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
98197  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
98198  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
98199  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
98200  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
98201  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
98202  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
98203  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
98204  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
98205  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
98206  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
98207  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
98208  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
98209  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
98210  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
98211  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
98212  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
98213  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
98214  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
98215  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
98216  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
98217  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
98218  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
98219  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
98220  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
98221 };
98222 static const YYCODETYPE yy_lookahead[] = {
98223  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
98224  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
98225  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
98226  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
98227  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
98228  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98229  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
98230  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
98231  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98232  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
98233  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
98234  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
98235  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
98236  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
98237  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
98238  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
98239  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
98240  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
98241  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
98242  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
98243  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98244  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98245  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
98246  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
98247  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
98248  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
98249  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
98250  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
98251  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
98252  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
98253  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
98254  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
98255  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
98256  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
98257  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
98258  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
98259  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98260  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
98261  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
98262  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
98263  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
98264  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
98265  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98266  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
98267  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
98268  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
98269  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
98270  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
98271  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
98272  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
98273  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
98274  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
98275  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
98276  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
98277  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
98278  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
98279  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
98280  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98281  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98282  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
98283  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
98284  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
98285  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
98286  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
98287  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
98288  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
98289  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
98290  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
98291  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
98292  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
98293  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
98294  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
98295  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
98296  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98297  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
98298  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
98299  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
98300  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
98301  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
98302  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98303  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
98304  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
98305  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
98306  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
98307  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
98308  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
98309  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
98310  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
98311  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
98312  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
98313  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
98314  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
98315  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
98316  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
98317  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98318  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98319  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
98320  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
98321  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
98322  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
98323  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
98324  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
98325  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
98326  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
98327  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
98328  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
98329  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
98330  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
98331  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
98332  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
98333  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98334  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
98335  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
98336  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
98337  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
98338  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
98339  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
98340  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
98341  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
98342  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
98343  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
98344  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
98345  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
98346  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
98347  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
98348  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
98349  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
98350  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
98351  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
98352  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
98353  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
98354  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
98355  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
98356  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
98357  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
98358  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
98359  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
98360  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
98361  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
98362  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
98363  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
98364  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
98365  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
98366  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
98367  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
98368  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
98369  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
98370  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
98371  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
98372  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
98373  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
98374  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
98375  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
98376  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
98377  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
98378  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
98379 };
98380 #define YY_SHIFT_USE_DFLT (-74)
98381 #define YY_SHIFT_COUNT (418)
98382 #define YY_SHIFT_MIN   (-73)
98383 #define YY_SHIFT_MAX   (1468)
98384 static const short yy_shift_ofst[] = {
98385  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
98386  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
98387  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98388  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98389  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
98390  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98391  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
98392  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
98393  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
98394  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
98395  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
98396  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98397  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
98398  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
98399  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
98400  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98401  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98402  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98403  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
98404  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
98405  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
98406  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
98407  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
98408  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
98409  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
98410  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
98411  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
98412  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
98413  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
98414  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
98415  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
98416  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
98417  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
98418  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
98419  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
98420  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
98421  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
98422  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
98423  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
98424  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
98425  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
98426  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
98427 };
98428 #define YY_REDUCE_USE_DFLT (-142)
98429 #define YY_REDUCE_COUNT (312)
98430 #define YY_REDUCE_MIN   (-141)
98431 #define YY_REDUCE_MAX   (1369)
98432 static const short yy_reduce_ofst[] = {
98433  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
98434  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
98435  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
98436  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
98437  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
98438  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
98439  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
98440  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98441  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98442  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98443  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
98444  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
98445  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
98446  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
98447  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
98448  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
98449  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
98450  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
98451  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
98452  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
98453  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
98454  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
98455  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
98456  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
98457  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
98458  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
98459  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
98460  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
98461  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
98462  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
98463  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
98464  /*   310 */  1031, 1023, 1030,
98465 };
98466 static const YYACTIONTYPE yy_default[] = {
98467  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
98468  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
98469  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98470  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98471  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98472  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98473  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
98474  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
98475  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
98476  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
98477  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
98478  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98479  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
98480  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
98481  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98482  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
98483  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98484  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98485  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
98486  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
98487  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
98488  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
98489  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
98490  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
98491  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
98492  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
98493  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
98494  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
98495  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
98496  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
98497  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
98498  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
98499  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98500  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
98501  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98502  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
98503  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
98504  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98505  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98506  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
98507  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
98508  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
98509  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
98510  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
98511  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
98512  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
98513  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
98514  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
98515  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
98516  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
98517  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
98518  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
98519  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
98520  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
98521  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
98522  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
98523  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
98524  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
98525  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
98526  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
98527  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
98528  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
98529  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
98530 };
98531
98532 /* The next table maps tokens into fallback tokens.  If a construct
98533 ** like the following:
98534 ** 
98535 **      %fallback ID X Y Z.
98536 **
98537 ** appears in the grammar, then ID becomes a fallback token for X, Y,
98538 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
98539 ** but it does not parse, the type of the token is changed to ID and
98540 ** the parse is retried before an error is thrown.
98541 */
98542 #ifdef YYFALLBACK
98543 static const YYCODETYPE yyFallback[] = {
98544     0,  /*          $ => nothing */
98545     0,  /*       SEMI => nothing */
98546    26,  /*    EXPLAIN => ID */
98547    26,  /*      QUERY => ID */
98548    26,  /*       PLAN => ID */
98549    26,  /*      BEGIN => ID */
98550     0,  /* TRANSACTION => nothing */
98551    26,  /*   DEFERRED => ID */
98552    26,  /*  IMMEDIATE => ID */
98553    26,  /*  EXCLUSIVE => ID */
98554     0,  /*     COMMIT => nothing */
98555    26,  /*        END => ID */
98556    26,  /*   ROLLBACK => ID */
98557    26,  /*  SAVEPOINT => ID */
98558    26,  /*    RELEASE => ID */
98559     0,  /*         TO => nothing */
98560     0,  /*      TABLE => nothing */
98561     0,  /*     CREATE => nothing */
98562    26,  /*         IF => ID */
98563     0,  /*        NOT => nothing */
98564     0,  /*     EXISTS => nothing */
98565    26,  /*       TEMP => ID */
98566     0,  /*         LP => nothing */
98567     0,  /*         RP => nothing */
98568     0,  /*         AS => nothing */
98569     0,  /*      COMMA => nothing */
98570     0,  /*         ID => nothing */
98571     0,  /*    INDEXED => nothing */
98572    26,  /*      ABORT => ID */
98573    26,  /*     ACTION => ID */
98574    26,  /*      AFTER => ID */
98575    26,  /*    ANALYZE => ID */
98576    26,  /*        ASC => ID */
98577    26,  /*     ATTACH => ID */
98578    26,  /*     BEFORE => ID */
98579    26,  /*         BY => ID */
98580    26,  /*    CASCADE => ID */
98581    26,  /*       CAST => ID */
98582    26,  /*   COLUMNKW => ID */
98583    26,  /*   CONFLICT => ID */
98584    26,  /*   DATABASE => ID */
98585    26,  /*       DESC => ID */
98586    26,  /*     DETACH => ID */
98587    26,  /*       EACH => ID */
98588    26,  /*       FAIL => ID */
98589    26,  /*        FOR => ID */
98590    26,  /*     IGNORE => ID */
98591    26,  /*  INITIALLY => ID */
98592    26,  /*    INSTEAD => ID */
98593    26,  /*    LIKE_KW => ID */
98594    26,  /*      MATCH => ID */
98595    26,  /*         NO => ID */
98596    26,  /*        KEY => ID */
98597    26,  /*         OF => ID */
98598    26,  /*     OFFSET => ID */
98599    26,  /*     PRAGMA => ID */
98600    26,  /*      RAISE => ID */
98601    26,  /*    REPLACE => ID */
98602    26,  /*   RESTRICT => ID */
98603    26,  /*        ROW => ID */
98604    26,  /*    TRIGGER => ID */
98605    26,  /*     VACUUM => ID */
98606    26,  /*       VIEW => ID */
98607    26,  /*    VIRTUAL => ID */
98608    26,  /*    REINDEX => ID */
98609    26,  /*     RENAME => ID */
98610    26,  /*   CTIME_KW => ID */
98611 };
98612 #endif /* YYFALLBACK */
98613
98614 /* The following structure represents a single element of the
98615 ** parser's stack.  Information stored includes:
98616 **
98617 **   +  The state number for the parser at this level of the stack.
98618 **
98619 **   +  The value of the token stored at this level of the stack.
98620 **      (In other words, the "major" token.)
98621 **
98622 **   +  The semantic value stored at this level of the stack.  This is
98623 **      the information used by the action routines in the grammar.
98624 **      It is sometimes called the "minor" token.
98625 */
98626 struct yyStackEntry {
98627   YYACTIONTYPE stateno;  /* The state-number */
98628   YYCODETYPE major;      /* The major token value.  This is the code
98629                          ** number for the token at this stack level */
98630   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
98631                          ** is the value of the token  */
98632 };
98633 typedef struct yyStackEntry yyStackEntry;
98634
98635 /* The state of the parser is completely contained in an instance of
98636 ** the following structure */
98637 struct yyParser {
98638   int yyidx;                    /* Index of top element in stack */
98639 #ifdef YYTRACKMAXSTACKDEPTH
98640   int yyidxMax;                 /* Maximum value of yyidx */
98641 #endif
98642   int yyerrcnt;                 /* Shifts left before out of the error */
98643   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
98644 #if YYSTACKDEPTH<=0
98645   int yystksz;                  /* Current side of the stack */
98646   yyStackEntry *yystack;        /* The parser's stack */
98647 #else
98648   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
98649 #endif
98650 };
98651 typedef struct yyParser yyParser;
98652
98653 #ifndef NDEBUG
98654 static FILE *yyTraceFILE = 0;
98655 static char *yyTracePrompt = 0;
98656 #endif /* NDEBUG */
98657
98658 #ifndef NDEBUG
98659 /* 
98660 ** Turn parser tracing on by giving a stream to which to write the trace
98661 ** and a prompt to preface each trace message.  Tracing is turned off
98662 ** by making either argument NULL 
98663 **
98664 ** Inputs:
98665 ** <ul>
98666 ** <li> A FILE* to which trace output should be written.
98667 **      If NULL, then tracing is turned off.
98668 ** <li> A prefix string written at the beginning of every
98669 **      line of trace output.  If NULL, then tracing is
98670 **      turned off.
98671 ** </ul>
98672 **
98673 ** Outputs:
98674 ** None.
98675 */
98676 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
98677   yyTraceFILE = TraceFILE;
98678   yyTracePrompt = zTracePrompt;
98679   if( yyTraceFILE==0 ) yyTracePrompt = 0;
98680   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
98681 }
98682 #endif /* NDEBUG */
98683
98684 #ifndef NDEBUG
98685 /* For tracing shifts, the names of all terminals and nonterminals
98686 ** are required.  The following table supplies these names */
98687 static const char *const yyTokenName[] = { 
98688   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
98689   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
98690   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
98691   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
98692   "TABLE",         "CREATE",        "IF",            "NOT",         
98693   "EXISTS",        "TEMP",          "LP",            "RP",          
98694   "AS",            "COMMA",         "ID",            "INDEXED",     
98695   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
98696   "ASC",           "ATTACH",        "BEFORE",        "BY",          
98697   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
98698   "DATABASE",      "DESC",          "DETACH",        "EACH",        
98699   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
98700   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
98701   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
98702   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
98703   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
98704   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
98705   "OR",            "AND",           "IS",            "BETWEEN",     
98706   "IN",            "ISNULL",        "NOTNULL",       "NE",          
98707   "EQ",            "GT",            "LE",            "LT",          
98708   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
98709   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
98710   "STAR",          "SLASH",         "REM",           "CONCAT",      
98711   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
98712   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
98713   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
98714   "ON",            "INSERT",        "DELETE",        "UPDATE",      
98715   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
98716   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
98717   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
98718   "JOIN",          "USING",         "ORDER",         "GROUP",       
98719   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
98720   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
98721   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
98722   "THEN",          "ELSE",          "INDEX",         "ALTER",       
98723   "ADD",           "error",         "input",         "cmdlist",     
98724   "ecmd",          "explain",       "cmdx",          "cmd",         
98725   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
98726   "create_table",  "create_table_args",  "createkw",      "temp",        
98727   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
98728   "select",        "column",        "columnid",      "type",        
98729   "carglist",      "id",            "ids",           "typetoken",   
98730   "typename",      "signed",        "plus_num",      "minus_num",   
98731   "carg",          "ccons",         "term",          "expr",        
98732   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
98733   "refargs",       "defer_subclause",  "refarg",        "refact",      
98734   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
98735   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
98736   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
98737   "distinct",      "selcollist",    "from",          "where_opt",   
98738   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
98739   "sclp",          "as",            "seltablist",    "stl_prefix",  
98740   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
98741   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
98742   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
98743   "itemlist",      "exprlist",      "likeop",        "between_op",  
98744   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
98745   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
98746   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
98747   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
98748   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
98749   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
98750   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
98751 };
98752 #endif /* NDEBUG */
98753
98754 #ifndef NDEBUG
98755 /* For tracing reduce actions, the names of all rules are required.
98756 */
98757 static const char *const yyRuleName[] = {
98758  /*   0 */ "input ::= cmdlist",
98759  /*   1 */ "cmdlist ::= cmdlist ecmd",
98760  /*   2 */ "cmdlist ::= ecmd",
98761  /*   3 */ "ecmd ::= SEMI",
98762  /*   4 */ "ecmd ::= explain cmdx SEMI",
98763  /*   5 */ "explain ::=",
98764  /*   6 */ "explain ::= EXPLAIN",
98765  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
98766  /*   8 */ "cmdx ::= cmd",
98767  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
98768  /*  10 */ "trans_opt ::=",
98769  /*  11 */ "trans_opt ::= TRANSACTION",
98770  /*  12 */ "trans_opt ::= TRANSACTION nm",
98771  /*  13 */ "transtype ::=",
98772  /*  14 */ "transtype ::= DEFERRED",
98773  /*  15 */ "transtype ::= IMMEDIATE",
98774  /*  16 */ "transtype ::= EXCLUSIVE",
98775  /*  17 */ "cmd ::= COMMIT trans_opt",
98776  /*  18 */ "cmd ::= END trans_opt",
98777  /*  19 */ "cmd ::= ROLLBACK trans_opt",
98778  /*  20 */ "savepoint_opt ::= SAVEPOINT",
98779  /*  21 */ "savepoint_opt ::=",
98780  /*  22 */ "cmd ::= SAVEPOINT nm",
98781  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
98782  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
98783  /*  25 */ "cmd ::= create_table create_table_args",
98784  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
98785  /*  27 */ "createkw ::= CREATE",
98786  /*  28 */ "ifnotexists ::=",
98787  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
98788  /*  30 */ "temp ::= TEMP",
98789  /*  31 */ "temp ::=",
98790  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
98791  /*  33 */ "create_table_args ::= AS select",
98792  /*  34 */ "columnlist ::= columnlist COMMA column",
98793  /*  35 */ "columnlist ::= column",
98794  /*  36 */ "column ::= columnid type carglist",
98795  /*  37 */ "columnid ::= nm",
98796  /*  38 */ "id ::= ID",
98797  /*  39 */ "id ::= INDEXED",
98798  /*  40 */ "ids ::= ID|STRING",
98799  /*  41 */ "nm ::= id",
98800  /*  42 */ "nm ::= STRING",
98801  /*  43 */ "nm ::= JOIN_KW",
98802  /*  44 */ "type ::=",
98803  /*  45 */ "type ::= typetoken",
98804  /*  46 */ "typetoken ::= typename",
98805  /*  47 */ "typetoken ::= typename LP signed RP",
98806  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
98807  /*  49 */ "typename ::= ids",
98808  /*  50 */ "typename ::= typename ids",
98809  /*  51 */ "signed ::= plus_num",
98810  /*  52 */ "signed ::= minus_num",
98811  /*  53 */ "carglist ::= carglist carg",
98812  /*  54 */ "carglist ::=",
98813  /*  55 */ "carg ::= CONSTRAINT nm ccons",
98814  /*  56 */ "carg ::= ccons",
98815  /*  57 */ "ccons ::= DEFAULT term",
98816  /*  58 */ "ccons ::= DEFAULT LP expr RP",
98817  /*  59 */ "ccons ::= DEFAULT PLUS term",
98818  /*  60 */ "ccons ::= DEFAULT MINUS term",
98819  /*  61 */ "ccons ::= DEFAULT id",
98820  /*  62 */ "ccons ::= NULL onconf",
98821  /*  63 */ "ccons ::= NOT NULL onconf",
98822  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
98823  /*  65 */ "ccons ::= UNIQUE onconf",
98824  /*  66 */ "ccons ::= CHECK LP expr RP",
98825  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
98826  /*  68 */ "ccons ::= defer_subclause",
98827  /*  69 */ "ccons ::= COLLATE ids",
98828  /*  70 */ "autoinc ::=",
98829  /*  71 */ "autoinc ::= AUTOINCR",
98830  /*  72 */ "refargs ::=",
98831  /*  73 */ "refargs ::= refargs refarg",
98832  /*  74 */ "refarg ::= MATCH nm",
98833  /*  75 */ "refarg ::= ON INSERT refact",
98834  /*  76 */ "refarg ::= ON DELETE refact",
98835  /*  77 */ "refarg ::= ON UPDATE refact",
98836  /*  78 */ "refact ::= SET NULL",
98837  /*  79 */ "refact ::= SET DEFAULT",
98838  /*  80 */ "refact ::= CASCADE",
98839  /*  81 */ "refact ::= RESTRICT",
98840  /*  82 */ "refact ::= NO ACTION",
98841  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
98842  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
98843  /*  85 */ "init_deferred_pred_opt ::=",
98844  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
98845  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
98846  /*  88 */ "conslist_opt ::=",
98847  /*  89 */ "conslist_opt ::= COMMA conslist",
98848  /*  90 */ "conslist ::= conslist COMMA tcons",
98849  /*  91 */ "conslist ::= conslist tcons",
98850  /*  92 */ "conslist ::= tcons",
98851  /*  93 */ "tcons ::= CONSTRAINT nm",
98852  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
98853  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
98854  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
98855  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
98856  /*  98 */ "defer_subclause_opt ::=",
98857  /*  99 */ "defer_subclause_opt ::= defer_subclause",
98858  /* 100 */ "onconf ::=",
98859  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
98860  /* 102 */ "orconf ::=",
98861  /* 103 */ "orconf ::= OR resolvetype",
98862  /* 104 */ "resolvetype ::= raisetype",
98863  /* 105 */ "resolvetype ::= IGNORE",
98864  /* 106 */ "resolvetype ::= REPLACE",
98865  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
98866  /* 108 */ "ifexists ::= IF EXISTS",
98867  /* 109 */ "ifexists ::=",
98868  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
98869  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
98870  /* 112 */ "cmd ::= select",
98871  /* 113 */ "select ::= oneselect",
98872  /* 114 */ "select ::= select multiselect_op oneselect",
98873  /* 115 */ "multiselect_op ::= UNION",
98874  /* 116 */ "multiselect_op ::= UNION ALL",
98875  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
98876  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
98877  /* 119 */ "distinct ::= DISTINCT",
98878  /* 120 */ "distinct ::= ALL",
98879  /* 121 */ "distinct ::=",
98880  /* 122 */ "sclp ::= selcollist COMMA",
98881  /* 123 */ "sclp ::=",
98882  /* 124 */ "selcollist ::= sclp expr as",
98883  /* 125 */ "selcollist ::= sclp STAR",
98884  /* 126 */ "selcollist ::= sclp nm DOT STAR",
98885  /* 127 */ "as ::= AS nm",
98886  /* 128 */ "as ::= ids",
98887  /* 129 */ "as ::=",
98888  /* 130 */ "from ::=",
98889  /* 131 */ "from ::= FROM seltablist",
98890  /* 132 */ "stl_prefix ::= seltablist joinop",
98891  /* 133 */ "stl_prefix ::=",
98892  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
98893  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
98894  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
98895  /* 137 */ "dbnm ::=",
98896  /* 138 */ "dbnm ::= DOT nm",
98897  /* 139 */ "fullname ::= nm dbnm",
98898  /* 140 */ "joinop ::= COMMA|JOIN",
98899  /* 141 */ "joinop ::= JOIN_KW JOIN",
98900  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
98901  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
98902  /* 144 */ "on_opt ::= ON expr",
98903  /* 145 */ "on_opt ::=",
98904  /* 146 */ "indexed_opt ::=",
98905  /* 147 */ "indexed_opt ::= INDEXED BY nm",
98906  /* 148 */ "indexed_opt ::= NOT INDEXED",
98907  /* 149 */ "using_opt ::= USING LP inscollist RP",
98908  /* 150 */ "using_opt ::=",
98909  /* 151 */ "orderby_opt ::=",
98910  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
98911  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
98912  /* 154 */ "sortlist ::= sortitem sortorder",
98913  /* 155 */ "sortitem ::= expr",
98914  /* 156 */ "sortorder ::= ASC",
98915  /* 157 */ "sortorder ::= DESC",
98916  /* 158 */ "sortorder ::=",
98917  /* 159 */ "groupby_opt ::=",
98918  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
98919  /* 161 */ "having_opt ::=",
98920  /* 162 */ "having_opt ::= HAVING expr",
98921  /* 163 */ "limit_opt ::=",
98922  /* 164 */ "limit_opt ::= LIMIT expr",
98923  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
98924  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
98925  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
98926  /* 168 */ "where_opt ::=",
98927  /* 169 */ "where_opt ::= WHERE expr",
98928  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
98929  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
98930  /* 172 */ "setlist ::= nm EQ expr",
98931  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
98932  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
98933  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
98934  /* 176 */ "insert_cmd ::= INSERT orconf",
98935  /* 177 */ "insert_cmd ::= REPLACE",
98936  /* 178 */ "itemlist ::= itemlist COMMA expr",
98937  /* 179 */ "itemlist ::= expr",
98938  /* 180 */ "inscollist_opt ::=",
98939  /* 181 */ "inscollist_opt ::= LP inscollist RP",
98940  /* 182 */ "inscollist ::= inscollist COMMA nm",
98941  /* 183 */ "inscollist ::= nm",
98942  /* 184 */ "expr ::= term",
98943  /* 185 */ "expr ::= LP expr RP",
98944  /* 186 */ "term ::= NULL",
98945  /* 187 */ "expr ::= id",
98946  /* 188 */ "expr ::= JOIN_KW",
98947  /* 189 */ "expr ::= nm DOT nm",
98948  /* 190 */ "expr ::= nm DOT nm DOT nm",
98949  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
98950  /* 192 */ "term ::= STRING",
98951  /* 193 */ "expr ::= REGISTER",
98952  /* 194 */ "expr ::= VARIABLE",
98953  /* 195 */ "expr ::= expr COLLATE ids",
98954  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
98955  /* 197 */ "expr ::= ID LP distinct exprlist RP",
98956  /* 198 */ "expr ::= ID LP STAR RP",
98957  /* 199 */ "term ::= CTIME_KW",
98958  /* 200 */ "expr ::= expr AND expr",
98959  /* 201 */ "expr ::= expr OR expr",
98960  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
98961  /* 203 */ "expr ::= expr EQ|NE expr",
98962  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
98963  /* 205 */ "expr ::= expr PLUS|MINUS expr",
98964  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
98965  /* 207 */ "expr ::= expr CONCAT expr",
98966  /* 208 */ "likeop ::= LIKE_KW",
98967  /* 209 */ "likeop ::= NOT LIKE_KW",
98968  /* 210 */ "likeop ::= MATCH",
98969  /* 211 */ "likeop ::= NOT MATCH",
98970  /* 212 */ "expr ::= expr likeop expr",
98971  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
98972  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
98973  /* 215 */ "expr ::= expr NOT NULL",
98974  /* 216 */ "expr ::= expr IS expr",
98975  /* 217 */ "expr ::= expr IS NOT expr",
98976  /* 218 */ "expr ::= NOT expr",
98977  /* 219 */ "expr ::= BITNOT expr",
98978  /* 220 */ "expr ::= MINUS expr",
98979  /* 221 */ "expr ::= PLUS expr",
98980  /* 222 */ "between_op ::= BETWEEN",
98981  /* 223 */ "between_op ::= NOT BETWEEN",
98982  /* 224 */ "expr ::= expr between_op expr AND expr",
98983  /* 225 */ "in_op ::= IN",
98984  /* 226 */ "in_op ::= NOT IN",
98985  /* 227 */ "expr ::= expr in_op LP exprlist RP",
98986  /* 228 */ "expr ::= LP select RP",
98987  /* 229 */ "expr ::= expr in_op LP select RP",
98988  /* 230 */ "expr ::= expr in_op nm dbnm",
98989  /* 231 */ "expr ::= EXISTS LP select RP",
98990  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
98991  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
98992  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
98993  /* 235 */ "case_else ::= ELSE expr",
98994  /* 236 */ "case_else ::=",
98995  /* 237 */ "case_operand ::= expr",
98996  /* 238 */ "case_operand ::=",
98997  /* 239 */ "exprlist ::= nexprlist",
98998  /* 240 */ "exprlist ::=",
98999  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
99000  /* 242 */ "nexprlist ::= expr",
99001  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
99002  /* 244 */ "uniqueflag ::= UNIQUE",
99003  /* 245 */ "uniqueflag ::=",
99004  /* 246 */ "idxlist_opt ::=",
99005  /* 247 */ "idxlist_opt ::= LP idxlist RP",
99006  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
99007  /* 249 */ "idxlist ::= nm collate sortorder",
99008  /* 250 */ "collate ::=",
99009  /* 251 */ "collate ::= COLLATE ids",
99010  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
99011  /* 253 */ "cmd ::= VACUUM",
99012  /* 254 */ "cmd ::= VACUUM nm",
99013  /* 255 */ "cmd ::= PRAGMA nm dbnm",
99014  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
99015  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
99016  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
99017  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
99018  /* 260 */ "nmnum ::= plus_num",
99019  /* 261 */ "nmnum ::= nm",
99020  /* 262 */ "nmnum ::= ON",
99021  /* 263 */ "nmnum ::= DELETE",
99022  /* 264 */ "nmnum ::= DEFAULT",
99023  /* 265 */ "plus_num ::= plus_opt number",
99024  /* 266 */ "minus_num ::= MINUS number",
99025  /* 267 */ "number ::= INTEGER|FLOAT",
99026  /* 268 */ "plus_opt ::= PLUS",
99027  /* 269 */ "plus_opt ::=",
99028  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
99029  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
99030  /* 272 */ "trigger_time ::= BEFORE",
99031  /* 273 */ "trigger_time ::= AFTER",
99032  /* 274 */ "trigger_time ::= INSTEAD OF",
99033  /* 275 */ "trigger_time ::=",
99034  /* 276 */ "trigger_event ::= DELETE|INSERT",
99035  /* 277 */ "trigger_event ::= UPDATE",
99036  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
99037  /* 279 */ "foreach_clause ::=",
99038  /* 280 */ "foreach_clause ::= FOR EACH ROW",
99039  /* 281 */ "when_clause ::=",
99040  /* 282 */ "when_clause ::= WHEN expr",
99041  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
99042  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
99043  /* 285 */ "trnm ::= nm",
99044  /* 286 */ "trnm ::= nm DOT nm",
99045  /* 287 */ "tridxby ::=",
99046  /* 288 */ "tridxby ::= INDEXED BY nm",
99047  /* 289 */ "tridxby ::= NOT INDEXED",
99048  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
99049  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
99050  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
99051  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
99052  /* 294 */ "trigger_cmd ::= select",
99053  /* 295 */ "expr ::= RAISE LP IGNORE RP",
99054  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
99055  /* 297 */ "raisetype ::= ROLLBACK",
99056  /* 298 */ "raisetype ::= ABORT",
99057  /* 299 */ "raisetype ::= FAIL",
99058  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
99059  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
99060  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
99061  /* 303 */ "key_opt ::=",
99062  /* 304 */ "key_opt ::= KEY expr",
99063  /* 305 */ "database_kw_opt ::= DATABASE",
99064  /* 306 */ "database_kw_opt ::=",
99065  /* 307 */ "cmd ::= REINDEX",
99066  /* 308 */ "cmd ::= REINDEX nm dbnm",
99067  /* 309 */ "cmd ::= ANALYZE",
99068  /* 310 */ "cmd ::= ANALYZE nm dbnm",
99069  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
99070  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
99071  /* 313 */ "add_column_fullname ::= fullname",
99072  /* 314 */ "kwcolumn_opt ::=",
99073  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
99074  /* 316 */ "cmd ::= create_vtab",
99075  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
99076  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
99077  /* 319 */ "vtabarglist ::= vtabarg",
99078  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
99079  /* 321 */ "vtabarg ::=",
99080  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
99081  /* 323 */ "vtabargtoken ::= ANY",
99082  /* 324 */ "vtabargtoken ::= lp anylist RP",
99083  /* 325 */ "lp ::= LP",
99084  /* 326 */ "anylist ::=",
99085  /* 327 */ "anylist ::= anylist LP anylist RP",
99086  /* 328 */ "anylist ::= anylist ANY",
99087 };
99088 #endif /* NDEBUG */
99089
99090
99091 #if YYSTACKDEPTH<=0
99092 /*
99093 ** Try to increase the size of the parser stack.
99094 */
99095 static void yyGrowStack(yyParser *p){
99096   int newSize;
99097   yyStackEntry *pNew;
99098
99099   newSize = p->yystksz*2 + 100;
99100   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
99101   if( pNew ){
99102     p->yystack = pNew;
99103     p->yystksz = newSize;
99104 #ifndef NDEBUG
99105     if( yyTraceFILE ){
99106       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
99107               yyTracePrompt, p->yystksz);
99108     }
99109 #endif
99110   }
99111 }
99112 #endif
99113
99114 /* 
99115 ** This function allocates a new parser.
99116 ** The only argument is a pointer to a function which works like
99117 ** malloc.
99118 **
99119 ** Inputs:
99120 ** A pointer to the function used to allocate memory.
99121 **
99122 ** Outputs:
99123 ** A pointer to a parser.  This pointer is used in subsequent calls
99124 ** to sqlite3Parser and sqlite3ParserFree.
99125 */
99126 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
99127   yyParser *pParser;
99128   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
99129   if( pParser ){
99130     pParser->yyidx = -1;
99131 #ifdef YYTRACKMAXSTACKDEPTH
99132     pParser->yyidxMax = 0;
99133 #endif
99134 #if YYSTACKDEPTH<=0
99135     pParser->yystack = NULL;
99136     pParser->yystksz = 0;
99137     yyGrowStack(pParser);
99138 #endif
99139   }
99140   return pParser;
99141 }
99142
99143 /* The following function deletes the value associated with a
99144 ** symbol.  The symbol can be either a terminal or nonterminal.
99145 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
99146 ** the value.
99147 */
99148 static void yy_destructor(
99149   yyParser *yypParser,    /* The parser */
99150   YYCODETYPE yymajor,     /* Type code for object to destroy */
99151   YYMINORTYPE *yypminor   /* The object to be destroyed */
99152 ){
99153   sqlite3ParserARG_FETCH;
99154   switch( yymajor ){
99155     /* Here is inserted the actions which take place when a
99156     ** terminal or non-terminal is destroyed.  This can happen
99157     ** when the symbol is popped from the stack during a
99158     ** reduce or during error processing or when a parser is 
99159     ** being destroyed before it is finished parsing.
99160     **
99161     ** Note: during a reduce, the only symbols destroyed are those
99162     ** which appear on the RHS of the rule, but which are not used
99163     ** inside the C code.
99164     */
99165     case 160: /* select */
99166     case 194: /* oneselect */
99167 {
99168 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
99169 }
99170       break;
99171     case 174: /* term */
99172     case 175: /* expr */
99173 {
99174 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
99175 }
99176       break;
99177     case 179: /* idxlist_opt */
99178     case 187: /* idxlist */
99179     case 197: /* selcollist */
99180     case 200: /* groupby_opt */
99181     case 202: /* orderby_opt */
99182     case 204: /* sclp */
99183     case 214: /* sortlist */
99184     case 216: /* nexprlist */
99185     case 217: /* setlist */
99186     case 220: /* itemlist */
99187     case 221: /* exprlist */
99188     case 226: /* case_exprlist */
99189 {
99190 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
99191 }
99192       break;
99193     case 193: /* fullname */
99194     case 198: /* from */
99195     case 206: /* seltablist */
99196     case 207: /* stl_prefix */
99197 {
99198 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
99199 }
99200       break;
99201     case 199: /* where_opt */
99202     case 201: /* having_opt */
99203     case 210: /* on_opt */
99204     case 215: /* sortitem */
99205     case 225: /* case_operand */
99206     case 227: /* case_else */
99207     case 238: /* when_clause */
99208     case 243: /* key_opt */
99209 {
99210 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
99211 }
99212       break;
99213     case 211: /* using_opt */
99214     case 213: /* inscollist */
99215     case 219: /* inscollist_opt */
99216 {
99217 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
99218 }
99219       break;
99220     case 234: /* trigger_cmd_list */
99221     case 239: /* trigger_cmd */
99222 {
99223 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
99224 }
99225       break;
99226     case 236: /* trigger_event */
99227 {
99228 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
99229 }
99230       break;
99231     default:  break;   /* If no destructor action specified: do nothing */
99232   }
99233 }
99234
99235 /*
99236 ** Pop the parser's stack once.
99237 **
99238 ** If there is a destructor routine associated with the token which
99239 ** is popped from the stack, then call it.
99240 **
99241 ** Return the major token number for the symbol popped.
99242 */
99243 static int yy_pop_parser_stack(yyParser *pParser){
99244   YYCODETYPE yymajor;
99245   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
99246
99247   /* There is no mechanism by which the parser stack can be popped below
99248   ** empty in SQLite.  */
99249   if( NEVER(pParser->yyidx<0) ) return 0;
99250 #ifndef NDEBUG
99251   if( yyTraceFILE && pParser->yyidx>=0 ){
99252     fprintf(yyTraceFILE,"%sPopping %s\n",
99253       yyTracePrompt,
99254       yyTokenName[yytos->major]);
99255   }
99256 #endif
99257   yymajor = yytos->major;
99258   yy_destructor(pParser, yymajor, &yytos->minor);
99259   pParser->yyidx--;
99260   return yymajor;
99261 }
99262
99263 /* 
99264 ** Deallocate and destroy a parser.  Destructors are all called for
99265 ** all stack elements before shutting the parser down.
99266 **
99267 ** Inputs:
99268 ** <ul>
99269 ** <li>  A pointer to the parser.  This should be a pointer
99270 **       obtained from sqlite3ParserAlloc.
99271 ** <li>  A pointer to a function used to reclaim memory obtained
99272 **       from malloc.
99273 ** </ul>
99274 */
99275 SQLITE_PRIVATE void sqlite3ParserFree(
99276   void *p,                    /* The parser to be deleted */
99277   void (*freeProc)(void*)     /* Function used to reclaim memory */
99278 ){
99279   yyParser *pParser = (yyParser*)p;
99280   /* In SQLite, we never try to destroy a parser that was not successfully
99281   ** created in the first place. */
99282   if( NEVER(pParser==0) ) return;
99283   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
99284 #if YYSTACKDEPTH<=0
99285   free(pParser->yystack);
99286 #endif
99287   (*freeProc)((void*)pParser);
99288 }
99289
99290 /*
99291 ** Return the peak depth of the stack for a parser.
99292 */
99293 #ifdef YYTRACKMAXSTACKDEPTH
99294 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
99295   yyParser *pParser = (yyParser*)p;
99296   return pParser->yyidxMax;
99297 }
99298 #endif
99299
99300 /*
99301 ** Find the appropriate action for a parser given the terminal
99302 ** look-ahead token iLookAhead.
99303 **
99304 ** If the look-ahead token is YYNOCODE, then check to see if the action is
99305 ** independent of the look-ahead.  If it is, return the action, otherwise
99306 ** return YY_NO_ACTION.
99307 */
99308 static int yy_find_shift_action(
99309   yyParser *pParser,        /* The parser */
99310   YYCODETYPE iLookAhead     /* The look-ahead token */
99311 ){
99312   int i;
99313   int stateno = pParser->yystack[pParser->yyidx].stateno;
99314  
99315   if( stateno>YY_SHIFT_COUNT
99316    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
99317     return yy_default[stateno];
99318   }
99319   assert( iLookAhead!=YYNOCODE );
99320   i += iLookAhead;
99321   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
99322     if( iLookAhead>0 ){
99323 #ifdef YYFALLBACK
99324       YYCODETYPE iFallback;            /* Fallback token */
99325       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
99326              && (iFallback = yyFallback[iLookAhead])!=0 ){
99327 #ifndef NDEBUG
99328         if( yyTraceFILE ){
99329           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
99330              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
99331         }
99332 #endif
99333         return yy_find_shift_action(pParser, iFallback);
99334       }
99335 #endif
99336 #ifdef YYWILDCARD
99337       {
99338         int j = i - iLookAhead + YYWILDCARD;
99339         if( 
99340 #if YY_SHIFT_MIN+YYWILDCARD<0
99341           j>=0 &&
99342 #endif
99343 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
99344           j<YY_ACTTAB_COUNT &&
99345 #endif
99346           yy_lookahead[j]==YYWILDCARD
99347         ){
99348 #ifndef NDEBUG
99349           if( yyTraceFILE ){
99350             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
99351                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
99352           }
99353 #endif /* NDEBUG */
99354           return yy_action[j];
99355         }
99356       }
99357 #endif /* YYWILDCARD */
99358     }
99359     return yy_default[stateno];
99360   }else{
99361     return yy_action[i];
99362   }
99363 }
99364
99365 /*
99366 ** Find the appropriate action for a parser given the non-terminal
99367 ** look-ahead token iLookAhead.
99368 **
99369 ** If the look-ahead token is YYNOCODE, then check to see if the action is
99370 ** independent of the look-ahead.  If it is, return the action, otherwise
99371 ** return YY_NO_ACTION.
99372 */
99373 static int yy_find_reduce_action(
99374   int stateno,              /* Current state number */
99375   YYCODETYPE iLookAhead     /* The look-ahead token */
99376 ){
99377   int i;
99378 #ifdef YYERRORSYMBOL
99379   if( stateno>YY_REDUCE_COUNT ){
99380     return yy_default[stateno];
99381   }
99382 #else
99383   assert( stateno<=YY_REDUCE_COUNT );
99384 #endif
99385   i = yy_reduce_ofst[stateno];
99386   assert( i!=YY_REDUCE_USE_DFLT );
99387   assert( iLookAhead!=YYNOCODE );
99388   i += iLookAhead;
99389 #ifdef YYERRORSYMBOL
99390   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
99391     return yy_default[stateno];
99392   }
99393 #else
99394   assert( i>=0 && i<YY_ACTTAB_COUNT );
99395   assert( yy_lookahead[i]==iLookAhead );
99396 #endif
99397   return yy_action[i];
99398 }
99399
99400 /*
99401 ** The following routine is called if the stack overflows.
99402 */
99403 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
99404    sqlite3ParserARG_FETCH;
99405    yypParser->yyidx--;
99406 #ifndef NDEBUG
99407    if( yyTraceFILE ){
99408      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
99409    }
99410 #endif
99411    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
99412    /* Here code is inserted which will execute if the parser
99413    ** stack every overflows */
99414
99415   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
99416   sqlite3ErrorMsg(pParse, "parser stack overflow");
99417   pParse->parseError = 1;
99418    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
99419 }
99420
99421 /*
99422 ** Perform a shift action.
99423 */
99424 static void yy_shift(
99425   yyParser *yypParser,          /* The parser to be shifted */
99426   int yyNewState,               /* The new state to shift in */
99427   int yyMajor,                  /* The major token to shift in */
99428   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
99429 ){
99430   yyStackEntry *yytos;
99431   yypParser->yyidx++;
99432 #ifdef YYTRACKMAXSTACKDEPTH
99433   if( yypParser->yyidx>yypParser->yyidxMax ){
99434     yypParser->yyidxMax = yypParser->yyidx;
99435   }
99436 #endif
99437 #if YYSTACKDEPTH>0 
99438   if( yypParser->yyidx>=YYSTACKDEPTH ){
99439     yyStackOverflow(yypParser, yypMinor);
99440     return;
99441   }
99442 #else
99443   if( yypParser->yyidx>=yypParser->yystksz ){
99444     yyGrowStack(yypParser);
99445     if( yypParser->yyidx>=yypParser->yystksz ){
99446       yyStackOverflow(yypParser, yypMinor);
99447       return;
99448     }
99449   }
99450 #endif
99451   yytos = &yypParser->yystack[yypParser->yyidx];
99452   yytos->stateno = (YYACTIONTYPE)yyNewState;
99453   yytos->major = (YYCODETYPE)yyMajor;
99454   yytos->minor = *yypMinor;
99455 #ifndef NDEBUG
99456   if( yyTraceFILE && yypParser->yyidx>0 ){
99457     int i;
99458     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
99459     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
99460     for(i=1; i<=yypParser->yyidx; i++)
99461       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
99462     fprintf(yyTraceFILE,"\n");
99463   }
99464 #endif
99465 }
99466
99467 /* The following table contains information about every rule that
99468 ** is used during the reduce.
99469 */
99470 static const struct {
99471   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
99472   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
99473 } yyRuleInfo[] = {
99474   { 142, 1 },
99475   { 143, 2 },
99476   { 143, 1 },
99477   { 144, 1 },
99478   { 144, 3 },
99479   { 145, 0 },
99480   { 145, 1 },
99481   { 145, 3 },
99482   { 146, 1 },
99483   { 147, 3 },
99484   { 149, 0 },
99485   { 149, 1 },
99486   { 149, 2 },
99487   { 148, 0 },
99488   { 148, 1 },
99489   { 148, 1 },
99490   { 148, 1 },
99491   { 147, 2 },
99492   { 147, 2 },
99493   { 147, 2 },
99494   { 151, 1 },
99495   { 151, 0 },
99496   { 147, 2 },
99497   { 147, 3 },
99498   { 147, 5 },
99499   { 147, 2 },
99500   { 152, 6 },
99501   { 154, 1 },
99502   { 156, 0 },
99503   { 156, 3 },
99504   { 155, 1 },
99505   { 155, 0 },
99506   { 153, 4 },
99507   { 153, 2 },
99508   { 158, 3 },
99509   { 158, 1 },
99510   { 161, 3 },
99511   { 162, 1 },
99512   { 165, 1 },
99513   { 165, 1 },
99514   { 166, 1 },
99515   { 150, 1 },
99516   { 150, 1 },
99517   { 150, 1 },
99518   { 163, 0 },
99519   { 163, 1 },
99520   { 167, 1 },
99521   { 167, 4 },
99522   { 167, 6 },
99523   { 168, 1 },
99524   { 168, 2 },
99525   { 169, 1 },
99526   { 169, 1 },
99527   { 164, 2 },
99528   { 164, 0 },
99529   { 172, 3 },
99530   { 172, 1 },
99531   { 173, 2 },
99532   { 173, 4 },
99533   { 173, 3 },
99534   { 173, 3 },
99535   { 173, 2 },
99536   { 173, 2 },
99537   { 173, 3 },
99538   { 173, 5 },
99539   { 173, 2 },
99540   { 173, 4 },
99541   { 173, 4 },
99542   { 173, 1 },
99543   { 173, 2 },
99544   { 178, 0 },
99545   { 178, 1 },
99546   { 180, 0 },
99547   { 180, 2 },
99548   { 182, 2 },
99549   { 182, 3 },
99550   { 182, 3 },
99551   { 182, 3 },
99552   { 183, 2 },
99553   { 183, 2 },
99554   { 183, 1 },
99555   { 183, 1 },
99556   { 183, 2 },
99557   { 181, 3 },
99558   { 181, 2 },
99559   { 184, 0 },
99560   { 184, 2 },
99561   { 184, 2 },
99562   { 159, 0 },
99563   { 159, 2 },
99564   { 185, 3 },
99565   { 185, 2 },
99566   { 185, 1 },
99567   { 186, 2 },
99568   { 186, 7 },
99569   { 186, 5 },
99570   { 186, 5 },
99571   { 186, 10 },
99572   { 188, 0 },
99573   { 188, 1 },
99574   { 176, 0 },
99575   { 176, 3 },
99576   { 189, 0 },
99577   { 189, 2 },
99578   { 190, 1 },
99579   { 190, 1 },
99580   { 190, 1 },
99581   { 147, 4 },
99582   { 192, 2 },
99583   { 192, 0 },
99584   { 147, 8 },
99585   { 147, 4 },
99586   { 147, 1 },
99587   { 160, 1 },
99588   { 160, 3 },
99589   { 195, 1 },
99590   { 195, 2 },
99591   { 195, 1 },
99592   { 194, 9 },
99593   { 196, 1 },
99594   { 196, 1 },
99595   { 196, 0 },
99596   { 204, 2 },
99597   { 204, 0 },
99598   { 197, 3 },
99599   { 197, 2 },
99600   { 197, 4 },
99601   { 205, 2 },
99602   { 205, 1 },
99603   { 205, 0 },
99604   { 198, 0 },
99605   { 198, 2 },
99606   { 207, 2 },
99607   { 207, 0 },
99608   { 206, 7 },
99609   { 206, 7 },
99610   { 206, 7 },
99611   { 157, 0 },
99612   { 157, 2 },
99613   { 193, 2 },
99614   { 208, 1 },
99615   { 208, 2 },
99616   { 208, 3 },
99617   { 208, 4 },
99618   { 210, 2 },
99619   { 210, 0 },
99620   { 209, 0 },
99621   { 209, 3 },
99622   { 209, 2 },
99623   { 211, 4 },
99624   { 211, 0 },
99625   { 202, 0 },
99626   { 202, 3 },
99627   { 214, 4 },
99628   { 214, 2 },
99629   { 215, 1 },
99630   { 177, 1 },
99631   { 177, 1 },
99632   { 177, 0 },
99633   { 200, 0 },
99634   { 200, 3 },
99635   { 201, 0 },
99636   { 201, 2 },
99637   { 203, 0 },
99638   { 203, 2 },
99639   { 203, 4 },
99640   { 203, 4 },
99641   { 147, 5 },
99642   { 199, 0 },
99643   { 199, 2 },
99644   { 147, 7 },
99645   { 217, 5 },
99646   { 217, 3 },
99647   { 147, 8 },
99648   { 147, 5 },
99649   { 147, 6 },
99650   { 218, 2 },
99651   { 218, 1 },
99652   { 220, 3 },
99653   { 220, 1 },
99654   { 219, 0 },
99655   { 219, 3 },
99656   { 213, 3 },
99657   { 213, 1 },
99658   { 175, 1 },
99659   { 175, 3 },
99660   { 174, 1 },
99661   { 175, 1 },
99662   { 175, 1 },
99663   { 175, 3 },
99664   { 175, 5 },
99665   { 174, 1 },
99666   { 174, 1 },
99667   { 175, 1 },
99668   { 175, 1 },
99669   { 175, 3 },
99670   { 175, 6 },
99671   { 175, 5 },
99672   { 175, 4 },
99673   { 174, 1 },
99674   { 175, 3 },
99675   { 175, 3 },
99676   { 175, 3 },
99677   { 175, 3 },
99678   { 175, 3 },
99679   { 175, 3 },
99680   { 175, 3 },
99681   { 175, 3 },
99682   { 222, 1 },
99683   { 222, 2 },
99684   { 222, 1 },
99685   { 222, 2 },
99686   { 175, 3 },
99687   { 175, 5 },
99688   { 175, 2 },
99689   { 175, 3 },
99690   { 175, 3 },
99691   { 175, 4 },
99692   { 175, 2 },
99693   { 175, 2 },
99694   { 175, 2 },
99695   { 175, 2 },
99696   { 223, 1 },
99697   { 223, 2 },
99698   { 175, 5 },
99699   { 224, 1 },
99700   { 224, 2 },
99701   { 175, 5 },
99702   { 175, 3 },
99703   { 175, 5 },
99704   { 175, 4 },
99705   { 175, 4 },
99706   { 175, 5 },
99707   { 226, 5 },
99708   { 226, 4 },
99709   { 227, 2 },
99710   { 227, 0 },
99711   { 225, 1 },
99712   { 225, 0 },
99713   { 221, 1 },
99714   { 221, 0 },
99715   { 216, 3 },
99716   { 216, 1 },
99717   { 147, 11 },
99718   { 228, 1 },
99719   { 228, 0 },
99720   { 179, 0 },
99721   { 179, 3 },
99722   { 187, 5 },
99723   { 187, 3 },
99724   { 229, 0 },
99725   { 229, 2 },
99726   { 147, 4 },
99727   { 147, 1 },
99728   { 147, 2 },
99729   { 147, 3 },
99730   { 147, 5 },
99731   { 147, 6 },
99732   { 147, 5 },
99733   { 147, 6 },
99734   { 230, 1 },
99735   { 230, 1 },
99736   { 230, 1 },
99737   { 230, 1 },
99738   { 230, 1 },
99739   { 170, 2 },
99740   { 171, 2 },
99741   { 232, 1 },
99742   { 231, 1 },
99743   { 231, 0 },
99744   { 147, 5 },
99745   { 233, 11 },
99746   { 235, 1 },
99747   { 235, 1 },
99748   { 235, 2 },
99749   { 235, 0 },
99750   { 236, 1 },
99751   { 236, 1 },
99752   { 236, 3 },
99753   { 237, 0 },
99754   { 237, 3 },
99755   { 238, 0 },
99756   { 238, 2 },
99757   { 234, 3 },
99758   { 234, 2 },
99759   { 240, 1 },
99760   { 240, 3 },
99761   { 241, 0 },
99762   { 241, 3 },
99763   { 241, 2 },
99764   { 239, 7 },
99765   { 239, 8 },
99766   { 239, 5 },
99767   { 239, 5 },
99768   { 239, 1 },
99769   { 175, 4 },
99770   { 175, 6 },
99771   { 191, 1 },
99772   { 191, 1 },
99773   { 191, 1 },
99774   { 147, 4 },
99775   { 147, 6 },
99776   { 147, 3 },
99777   { 243, 0 },
99778   { 243, 2 },
99779   { 242, 1 },
99780   { 242, 0 },
99781   { 147, 1 },
99782   { 147, 3 },
99783   { 147, 1 },
99784   { 147, 3 },
99785   { 147, 6 },
99786   { 147, 6 },
99787   { 244, 1 },
99788   { 245, 0 },
99789   { 245, 1 },
99790   { 147, 1 },
99791   { 147, 4 },
99792   { 246, 7 },
99793   { 247, 1 },
99794   { 247, 3 },
99795   { 248, 0 },
99796   { 248, 2 },
99797   { 249, 1 },
99798   { 249, 3 },
99799   { 250, 1 },
99800   { 251, 0 },
99801   { 251, 4 },
99802   { 251, 2 },
99803 };
99804
99805 static void yy_accept(yyParser*);  /* Forward Declaration */
99806
99807 /*
99808 ** Perform a reduce action and the shift that must immediately
99809 ** follow the reduce.
99810 */
99811 static void yy_reduce(
99812   yyParser *yypParser,         /* The parser */
99813   int yyruleno                 /* Number of the rule by which to reduce */
99814 ){
99815   int yygoto;                     /* The next state */
99816   int yyact;                      /* The next action */
99817   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
99818   yyStackEntry *yymsp;            /* The top of the parser's stack */
99819   int yysize;                     /* Amount to pop the stack */
99820   sqlite3ParserARG_FETCH;
99821   yymsp = &yypParser->yystack[yypParser->yyidx];
99822 #ifndef NDEBUG
99823   if( yyTraceFILE && yyruleno>=0 
99824         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
99825     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
99826       yyRuleName[yyruleno]);
99827   }
99828 #endif /* NDEBUG */
99829
99830   /* Silence complaints from purify about yygotominor being uninitialized
99831   ** in some cases when it is copied into the stack after the following
99832   ** switch.  yygotominor is uninitialized when a rule reduces that does
99833   ** not set the value of its left-hand side nonterminal.  Leaving the
99834   ** value of the nonterminal uninitialized is utterly harmless as long
99835   ** as the value is never used.  So really the only thing this code
99836   ** accomplishes is to quieten purify.  
99837   **
99838   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
99839   ** without this code, their parser segfaults.  I'm not sure what there
99840   ** parser is doing to make this happen.  This is the second bug report
99841   ** from wireshark this week.  Clearly they are stressing Lemon in ways
99842   ** that it has not been previously stressed...  (SQLite ticket #2172)
99843   */
99844   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
99845   yygotominor = yyzerominor;
99846
99847
99848   switch( yyruleno ){
99849   /* Beginning here are the reduction cases.  A typical example
99850   ** follows:
99851   **   case 0:
99852   **  #line <lineno> <grammarfile>
99853   **     { ... }           // User supplied code
99854   **  #line <lineno> <thisfile>
99855   **     break;
99856   */
99857       case 5: /* explain ::= */
99858 { sqlite3BeginParse(pParse, 0); }
99859         break;
99860       case 6: /* explain ::= EXPLAIN */
99861 { sqlite3BeginParse(pParse, 1); }
99862         break;
99863       case 7: /* explain ::= EXPLAIN QUERY PLAN */
99864 { sqlite3BeginParse(pParse, 2); }
99865         break;
99866       case 8: /* cmdx ::= cmd */
99867 { sqlite3FinishCoding(pParse); }
99868         break;
99869       case 9: /* cmd ::= BEGIN transtype trans_opt */
99870 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
99871         break;
99872       case 13: /* transtype ::= */
99873 {yygotominor.yy4 = TK_DEFERRED;}
99874         break;
99875       case 14: /* transtype ::= DEFERRED */
99876       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
99877       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
99878       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
99879       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
99880 {yygotominor.yy4 = yymsp[0].major;}
99881         break;
99882       case 17: /* cmd ::= COMMIT trans_opt */
99883       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
99884 {sqlite3CommitTransaction(pParse);}
99885         break;
99886       case 19: /* cmd ::= ROLLBACK trans_opt */
99887 {sqlite3RollbackTransaction(pParse);}
99888         break;
99889       case 22: /* cmd ::= SAVEPOINT nm */
99890 {
99891   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
99892 }
99893         break;
99894       case 23: /* cmd ::= RELEASE savepoint_opt nm */
99895 {
99896   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
99897 }
99898         break;
99899       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
99900 {
99901   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
99902 }
99903         break;
99904       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
99905 {
99906    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
99907 }
99908         break;
99909       case 27: /* createkw ::= CREATE */
99910 {
99911   pParse->db->lookaside.bEnabled = 0;
99912   yygotominor.yy0 = yymsp[0].minor.yy0;
99913 }
99914         break;
99915       case 28: /* ifnotexists ::= */
99916       case 31: /* temp ::= */ yytestcase(yyruleno==31);
99917       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
99918       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
99919       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
99920       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
99921       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
99922       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
99923       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
99924       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
99925       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
99926       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
99927 {yygotominor.yy4 = 0;}
99928         break;
99929       case 29: /* ifnotexists ::= IF NOT EXISTS */
99930       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
99931       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
99932       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
99933       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
99934       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
99935       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
99936       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
99937 {yygotominor.yy4 = 1;}
99938         break;
99939       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
99940 {
99941   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
99942 }
99943         break;
99944       case 33: /* create_table_args ::= AS select */
99945 {
99946   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
99947   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
99948 }
99949         break;
99950       case 36: /* column ::= columnid type carglist */
99951 {
99952   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
99953   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
99954 }
99955         break;
99956       case 37: /* columnid ::= nm */
99957 {
99958   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
99959   yygotominor.yy0 = yymsp[0].minor.yy0;
99960 }
99961         break;
99962       case 38: /* id ::= ID */
99963       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
99964       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
99965       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
99966       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
99967       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
99968       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
99969       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
99970       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
99971       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
99972       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
99973       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
99974       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
99975       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
99976       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
99977       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
99978       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
99979       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
99980       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
99981       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
99982       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
99983       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
99984 {yygotominor.yy0 = yymsp[0].minor.yy0;}
99985         break;
99986       case 45: /* type ::= typetoken */
99987 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
99988         break;
99989       case 47: /* typetoken ::= typename LP signed RP */
99990 {
99991   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
99992   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
99993 }
99994         break;
99995       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
99996 {
99997   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
99998   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
99999 }
100000         break;
100001       case 50: /* typename ::= typename ids */
100002 {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);}
100003         break;
100004       case 57: /* ccons ::= DEFAULT term */
100005       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
100006 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
100007         break;
100008       case 58: /* ccons ::= DEFAULT LP expr RP */
100009 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
100010         break;
100011       case 60: /* ccons ::= DEFAULT MINUS term */
100012 {
100013   ExprSpan v;
100014   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
100015   v.zStart = yymsp[-1].minor.yy0.z;
100016   v.zEnd = yymsp[0].minor.yy118.zEnd;
100017   sqlite3AddDefaultValue(pParse,&v);
100018 }
100019         break;
100020       case 61: /* ccons ::= DEFAULT id */
100021 {
100022   ExprSpan v;
100023   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
100024   sqlite3AddDefaultValue(pParse,&v);
100025 }
100026         break;
100027       case 63: /* ccons ::= NOT NULL onconf */
100028 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
100029         break;
100030       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
100031 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
100032         break;
100033       case 65: /* ccons ::= UNIQUE onconf */
100034 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
100035         break;
100036       case 66: /* ccons ::= CHECK LP expr RP */
100037 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
100038         break;
100039       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
100040 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
100041         break;
100042       case 68: /* ccons ::= defer_subclause */
100043 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
100044         break;
100045       case 69: /* ccons ::= COLLATE ids */
100046 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
100047         break;
100048       case 72: /* refargs ::= */
100049 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
100050         break;
100051       case 73: /* refargs ::= refargs refarg */
100052 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
100053         break;
100054       case 74: /* refarg ::= MATCH nm */
100055       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
100056 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
100057         break;
100058       case 76: /* refarg ::= ON DELETE refact */
100059 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
100060         break;
100061       case 77: /* refarg ::= ON UPDATE refact */
100062 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
100063         break;
100064       case 78: /* refact ::= SET NULL */
100065 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
100066         break;
100067       case 79: /* refact ::= SET DEFAULT */
100068 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
100069         break;
100070       case 80: /* refact ::= CASCADE */
100071 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
100072         break;
100073       case 81: /* refact ::= RESTRICT */
100074 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
100075         break;
100076       case 82: /* refact ::= NO ACTION */
100077 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
100078         break;
100079       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
100080       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
100081       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
100082       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
100083 {yygotominor.yy4 = yymsp[0].minor.yy4;}
100084         break;
100085       case 88: /* conslist_opt ::= */
100086 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
100087         break;
100088       case 89: /* conslist_opt ::= COMMA conslist */
100089 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
100090         break;
100091       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
100092 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
100093         break;
100094       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
100095 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
100096         break;
100097       case 96: /* tcons ::= CHECK LP expr RP onconf */
100098 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
100099         break;
100100       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
100101 {
100102     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
100103     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
100104 }
100105         break;
100106       case 100: /* onconf ::= */
100107 {yygotominor.yy4 = OE_Default;}
100108         break;
100109       case 102: /* orconf ::= */
100110 {yygotominor.yy210 = OE_Default;}
100111         break;
100112       case 103: /* orconf ::= OR resolvetype */
100113 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
100114         break;
100115       case 105: /* resolvetype ::= IGNORE */
100116 {yygotominor.yy4 = OE_Ignore;}
100117         break;
100118       case 106: /* resolvetype ::= REPLACE */
100119 {yygotominor.yy4 = OE_Replace;}
100120         break;
100121       case 107: /* cmd ::= DROP TABLE ifexists fullname */
100122 {
100123   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
100124 }
100125         break;
100126       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
100127 {
100128   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
100129 }
100130         break;
100131       case 111: /* cmd ::= DROP VIEW ifexists fullname */
100132 {
100133   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
100134 }
100135         break;
100136       case 112: /* cmd ::= select */
100137 {
100138   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
100139   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
100140   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
100141 }
100142         break;
100143       case 113: /* select ::= oneselect */
100144 {yygotominor.yy387 = yymsp[0].minor.yy387;}
100145         break;
100146       case 114: /* select ::= select multiselect_op oneselect */
100147 {
100148   if( yymsp[0].minor.yy387 ){
100149     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
100150     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
100151   }else{
100152     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
100153   }
100154   yygotominor.yy387 = yymsp[0].minor.yy387;
100155 }
100156         break;
100157       case 116: /* multiselect_op ::= UNION ALL */
100158 {yygotominor.yy4 = TK_ALL;}
100159         break;
100160       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
100161 {
100162   yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
100163 }
100164         break;
100165       case 122: /* sclp ::= selcollist COMMA */
100166       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
100167 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
100168         break;
100169       case 123: /* sclp ::= */
100170       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
100171       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
100172       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
100173       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
100174 {yygotominor.yy322 = 0;}
100175         break;
100176       case 124: /* selcollist ::= sclp expr as */
100177 {
100178    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
100179    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
100180    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
100181 }
100182         break;
100183       case 125: /* selcollist ::= sclp STAR */
100184 {
100185   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
100186   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
100187 }
100188         break;
100189       case 126: /* selcollist ::= sclp nm DOT STAR */
100190 {
100191   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
100192   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100193   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
100194   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
100195 }
100196         break;
100197       case 129: /* as ::= */
100198 {yygotominor.yy0.n = 0;}
100199         break;
100200       case 130: /* from ::= */
100201 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
100202         break;
100203       case 131: /* from ::= FROM seltablist */
100204 {
100205   yygotominor.yy259 = yymsp[0].minor.yy259;
100206   sqlite3SrcListShiftJoinType(yygotominor.yy259);
100207 }
100208         break;
100209       case 132: /* stl_prefix ::= seltablist joinop */
100210 {
100211    yygotominor.yy259 = yymsp[-1].minor.yy259;
100212    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
100213 }
100214         break;
100215       case 133: /* stl_prefix ::= */
100216 {yygotominor.yy259 = 0;}
100217         break;
100218       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
100219 {
100220   yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100221   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
100222 }
100223         break;
100224       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
100225 {
100226     yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100227   }
100228         break;
100229       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
100230 {
100231     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
100232       yygotominor.yy259 = yymsp[-4].minor.yy259;
100233     }else{
100234       Select *pSubquery;
100235       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
100236       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
100237       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100238     }
100239   }
100240         break;
100241       case 137: /* dbnm ::= */
100242       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
100243 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
100244         break;
100245       case 139: /* fullname ::= nm dbnm */
100246 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
100247         break;
100248       case 140: /* joinop ::= COMMA|JOIN */
100249 { yygotominor.yy4 = JT_INNER; }
100250         break;
100251       case 141: /* joinop ::= JOIN_KW JOIN */
100252 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
100253         break;
100254       case 142: /* joinop ::= JOIN_KW nm JOIN */
100255 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
100256         break;
100257       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
100258 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
100259         break;
100260       case 144: /* on_opt ::= ON expr */
100261       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
100262       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
100263       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
100264       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
100265       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
100266 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
100267         break;
100268       case 145: /* on_opt ::= */
100269       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
100270       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
100271       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
100272       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
100273 {yygotominor.yy314 = 0;}
100274         break;
100275       case 148: /* indexed_opt ::= NOT INDEXED */
100276 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
100277         break;
100278       case 149: /* using_opt ::= USING LP inscollist RP */
100279       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
100280 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
100281         break;
100282       case 150: /* using_opt ::= */
100283       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
100284 {yygotominor.yy384 = 0;}
100285         break;
100286       case 152: /* orderby_opt ::= ORDER BY sortlist */
100287       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
100288       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
100289 {yygotominor.yy322 = yymsp[0].minor.yy322;}
100290         break;
100291       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
100292 {
100293   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
100294   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100295 }
100296         break;
100297       case 154: /* sortlist ::= sortitem sortorder */
100298 {
100299   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
100300   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
100301 }
100302         break;
100303       case 156: /* sortorder ::= ASC */
100304       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
100305 {yygotominor.yy4 = SQLITE_SO_ASC;}
100306         break;
100307       case 157: /* sortorder ::= DESC */
100308 {yygotominor.yy4 = SQLITE_SO_DESC;}
100309         break;
100310       case 163: /* limit_opt ::= */
100311 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
100312         break;
100313       case 164: /* limit_opt ::= LIMIT expr */
100314 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
100315         break;
100316       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
100317 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
100318         break;
100319       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
100320 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
100321         break;
100322       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
100323 {
100324   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
100325   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
100326 }
100327         break;
100328       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
100329 {
100330   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
100331   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
100332   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
100333 }
100334         break;
100335       case 171: /* setlist ::= setlist COMMA nm EQ expr */
100336 {
100337   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
100338   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100339 }
100340         break;
100341       case 172: /* setlist ::= nm EQ expr */
100342 {
100343   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
100344   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100345 }
100346         break;
100347       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
100348 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
100349         break;
100350       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
100351 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
100352         break;
100353       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
100354 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
100355         break;
100356       case 176: /* insert_cmd ::= INSERT orconf */
100357 {yygotominor.yy210 = yymsp[0].minor.yy210;}
100358         break;
100359       case 177: /* insert_cmd ::= REPLACE */
100360 {yygotominor.yy210 = OE_Replace;}
100361         break;
100362       case 178: /* itemlist ::= itemlist COMMA expr */
100363       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
100364 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
100365         break;
100366       case 179: /* itemlist ::= expr */
100367       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
100368 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
100369         break;
100370       case 182: /* inscollist ::= inscollist COMMA nm */
100371 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
100372         break;
100373       case 183: /* inscollist ::= nm */
100374 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
100375         break;
100376       case 184: /* expr ::= term */
100377 {yygotominor.yy118 = yymsp[0].minor.yy118;}
100378         break;
100379       case 185: /* expr ::= LP expr RP */
100380 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
100381         break;
100382       case 186: /* term ::= NULL */
100383       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
100384       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
100385 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
100386         break;
100387       case 187: /* expr ::= id */
100388       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
100389 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
100390         break;
100391       case 189: /* expr ::= nm DOT nm */
100392 {
100393   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100394   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100395   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
100396   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
100397 }
100398         break;
100399       case 190: /* expr ::= nm DOT nm DOT nm */
100400 {
100401   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
100402   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100403   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100404   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
100405   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
100406   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100407 }
100408         break;
100409       case 193: /* expr ::= REGISTER */
100410 {
100411   /* When doing a nested parse, one can include terms in an expression
100412   ** that look like this:   #1 #2 ...  These terms refer to registers
100413   ** in the virtual machine.  #N is the N-th register. */
100414   if( pParse->nested==0 ){
100415     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
100416     yygotominor.yy118.pExpr = 0;
100417   }else{
100418     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
100419     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
100420   }
100421   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100422 }
100423         break;
100424       case 194: /* expr ::= VARIABLE */
100425 {
100426   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
100427   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
100428   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100429 }
100430         break;
100431       case 195: /* expr ::= expr COLLATE ids */
100432 {
100433   yygotominor.yy118.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
100434   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
100435   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100436 }
100437         break;
100438       case 196: /* expr ::= CAST LP expr AS typetoken RP */
100439 {
100440   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
100441   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
100442 }
100443         break;
100444       case 197: /* expr ::= ID LP distinct exprlist RP */
100445 {
100446   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
100447     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
100448   }
100449   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
100450   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100451   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
100452     yygotominor.yy118.pExpr->flags |= EP_Distinct;
100453   }
100454 }
100455         break;
100456       case 198: /* expr ::= ID LP STAR RP */
100457 {
100458   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
100459   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
100460 }
100461         break;
100462       case 199: /* term ::= CTIME_KW */
100463 {
100464   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
100465   ** treated as functions that return constants */
100466   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
100467   if( yygotominor.yy118.pExpr ){
100468     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
100469   }
100470   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100471 }
100472         break;
100473       case 200: /* expr ::= expr AND expr */
100474       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
100475       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
100476       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
100477       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
100478       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
100479       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
100480       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
100481 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
100482         break;
100483       case 208: /* likeop ::= LIKE_KW */
100484       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
100485 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
100486         break;
100487       case 209: /* likeop ::= NOT LIKE_KW */
100488       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
100489 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
100490         break;
100491       case 212: /* expr ::= expr likeop expr */
100492 {
100493   ExprList *pList;
100494   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
100495   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
100496   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
100497   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100498   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
100499   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100500   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
100501 }
100502         break;
100503       case 213: /* expr ::= expr likeop expr ESCAPE expr */
100504 {
100505   ExprList *pList;
100506   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100507   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
100508   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
100509   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
100510   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100511   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100512   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100513   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
100514 }
100515         break;
100516       case 214: /* expr ::= expr ISNULL|NOTNULL */
100517 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
100518         break;
100519       case 215: /* expr ::= expr NOT NULL */
100520 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
100521         break;
100522       case 216: /* expr ::= expr IS expr */
100523 {
100524   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
100525   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
100526 }
100527         break;
100528       case 217: /* expr ::= expr IS NOT expr */
100529 {
100530   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
100531   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
100532 }
100533         break;
100534       case 218: /* expr ::= NOT expr */
100535       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
100536 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100537         break;
100538       case 220: /* expr ::= MINUS expr */
100539 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100540         break;
100541       case 221: /* expr ::= PLUS expr */
100542 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100543         break;
100544       case 224: /* expr ::= expr between_op expr AND expr */
100545 {
100546   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100547   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
100548   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100549   if( yygotominor.yy118.pExpr ){
100550     yygotominor.yy118.pExpr->x.pList = pList;
100551   }else{
100552     sqlite3ExprListDelete(pParse->db, pList);
100553   } 
100554   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100555   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100556   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100557 }
100558         break;
100559       case 227: /* expr ::= expr in_op LP exprlist RP */
100560 {
100561     if( yymsp[-1].minor.yy322==0 ){
100562       /* Expressions of the form
100563       **
100564       **      expr1 IN ()
100565       **      expr1 NOT IN ()
100566       **
100567       ** simplify to constants 0 (false) and 1 (true), respectively,
100568       ** regardless of the value of expr1.
100569       */
100570       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
100571       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
100572     }else{
100573       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100574       if( yygotominor.yy118.pExpr ){
100575         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
100576         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100577       }else{
100578         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
100579       }
100580       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100581     }
100582     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100583     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100584   }
100585         break;
100586       case 228: /* expr ::= LP select RP */
100587 {
100588     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
100589     if( yygotominor.yy118.pExpr ){
100590       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
100591       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100592       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100593     }else{
100594       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100595     }
100596     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
100597     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100598   }
100599         break;
100600       case 229: /* expr ::= expr in_op LP select RP */
100601 {
100602     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100603     if( yygotominor.yy118.pExpr ){
100604       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
100605       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100606       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100607     }else{
100608       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100609     }
100610     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100611     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100612     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100613   }
100614         break;
100615       case 230: /* expr ::= expr in_op nm dbnm */
100616 {
100617     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
100618     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
100619     if( yygotominor.yy118.pExpr ){
100620       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
100621       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100622       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100623     }else{
100624       sqlite3SrcListDelete(pParse->db, pSrc);
100625     }
100626     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100627     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
100628     yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
100629   }
100630         break;
100631       case 231: /* expr ::= EXISTS LP select RP */
100632 {
100633     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
100634     if( p ){
100635       p->x.pSelect = yymsp[-1].minor.yy387;
100636       ExprSetProperty(p, EP_xIsSelect);
100637       sqlite3ExprSetHeight(pParse, p);
100638     }else{
100639       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100640     }
100641     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
100642     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100643   }
100644         break;
100645       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
100646 {
100647   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
100648   if( yygotominor.yy118.pExpr ){
100649     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
100650     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100651   }else{
100652     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
100653   }
100654   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
100655   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100656 }
100657         break;
100658       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
100659 {
100660   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
100661   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
100662 }
100663         break;
100664       case 234: /* case_exprlist ::= WHEN expr THEN expr */
100665 {
100666   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100667   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
100668 }
100669         break;
100670       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
100671 {
100672   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
100673                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
100674                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
100675 }
100676         break;
100677       case 244: /* uniqueflag ::= UNIQUE */
100678       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
100679 {yygotominor.yy4 = OE_Abort;}
100680         break;
100681       case 245: /* uniqueflag ::= */
100682 {yygotominor.yy4 = OE_None;}
100683         break;
100684       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
100685 {
100686   Expr *p = 0;
100687   if( yymsp[-1].minor.yy0.n>0 ){
100688     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
100689     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100690   }
100691   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
100692   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
100693   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
100694   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100695 }
100696         break;
100697       case 249: /* idxlist ::= nm collate sortorder */
100698 {
100699   Expr *p = 0;
100700   if( yymsp[-1].minor.yy0.n>0 ){
100701     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
100702     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100703   }
100704   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
100705   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100706   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
100707   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100708 }
100709         break;
100710       case 250: /* collate ::= */
100711 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
100712         break;
100713       case 252: /* cmd ::= DROP INDEX ifexists fullname */
100714 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
100715         break;
100716       case 253: /* cmd ::= VACUUM */
100717       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
100718 {sqlite3Vacuum(pParse);}
100719         break;
100720       case 255: /* cmd ::= PRAGMA nm dbnm */
100721 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
100722         break;
100723       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
100724 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
100725         break;
100726       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
100727 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
100728         break;
100729       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
100730 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
100731         break;
100732       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
100733 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
100734         break;
100735       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
100736 {
100737   Token all;
100738   all.z = yymsp[-3].minor.yy0.z;
100739   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
100740   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
100741 }
100742         break;
100743       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
100744 {
100745   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
100746   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
100747 }
100748         break;
100749       case 272: /* trigger_time ::= BEFORE */
100750       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
100751 { yygotominor.yy4 = TK_BEFORE; }
100752         break;
100753       case 273: /* trigger_time ::= AFTER */
100754 { yygotominor.yy4 = TK_AFTER;  }
100755         break;
100756       case 274: /* trigger_time ::= INSTEAD OF */
100757 { yygotominor.yy4 = TK_INSTEAD;}
100758         break;
100759       case 276: /* trigger_event ::= DELETE|INSERT */
100760       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
100761 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
100762         break;
100763       case 278: /* trigger_event ::= UPDATE OF inscollist */
100764 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
100765         break;
100766       case 281: /* when_clause ::= */
100767       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
100768 { yygotominor.yy314 = 0; }
100769         break;
100770       case 282: /* when_clause ::= WHEN expr */
100771       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
100772 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
100773         break;
100774       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
100775 {
100776   assert( yymsp[-2].minor.yy203!=0 );
100777   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
100778   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
100779   yygotominor.yy203 = yymsp[-2].minor.yy203;
100780 }
100781         break;
100782       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
100783
100784   assert( yymsp[-1].minor.yy203!=0 );
100785   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
100786   yygotominor.yy203 = yymsp[-1].minor.yy203;
100787 }
100788         break;
100789       case 286: /* trnm ::= nm DOT nm */
100790 {
100791   yygotominor.yy0 = yymsp[0].minor.yy0;
100792   sqlite3ErrorMsg(pParse, 
100793         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
100794         "statements within triggers");
100795 }
100796         break;
100797       case 288: /* tridxby ::= INDEXED BY nm */
100798 {
100799   sqlite3ErrorMsg(pParse,
100800         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
100801         "within triggers");
100802 }
100803         break;
100804       case 289: /* tridxby ::= NOT INDEXED */
100805 {
100806   sqlite3ErrorMsg(pParse,
100807         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
100808         "within triggers");
100809 }
100810         break;
100811       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
100812 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
100813         break;
100814       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
100815 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
100816         break;
100817       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
100818 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
100819         break;
100820       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
100821 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
100822         break;
100823       case 294: /* trigger_cmd ::= select */
100824 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
100825         break;
100826       case 295: /* expr ::= RAISE LP IGNORE RP */
100827 {
100828   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
100829   if( yygotominor.yy118.pExpr ){
100830     yygotominor.yy118.pExpr->affinity = OE_Ignore;
100831   }
100832   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
100833   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100834 }
100835         break;
100836       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
100837 {
100838   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
100839   if( yygotominor.yy118.pExpr ) {
100840     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
100841   }
100842   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
100843   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100844 }
100845         break;
100846       case 297: /* raisetype ::= ROLLBACK */
100847 {yygotominor.yy4 = OE_Rollback;}
100848         break;
100849       case 299: /* raisetype ::= FAIL */
100850 {yygotominor.yy4 = OE_Fail;}
100851         break;
100852       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
100853 {
100854   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
100855 }
100856         break;
100857       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
100858 {
100859   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
100860 }
100861         break;
100862       case 302: /* cmd ::= DETACH database_kw_opt expr */
100863 {
100864   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
100865 }
100866         break;
100867       case 307: /* cmd ::= REINDEX */
100868 {sqlite3Reindex(pParse, 0, 0);}
100869         break;
100870       case 308: /* cmd ::= REINDEX nm dbnm */
100871 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100872         break;
100873       case 309: /* cmd ::= ANALYZE */
100874 {sqlite3Analyze(pParse, 0, 0);}
100875         break;
100876       case 310: /* cmd ::= ANALYZE nm dbnm */
100877 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100878         break;
100879       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
100880 {
100881   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
100882 }
100883         break;
100884       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
100885 {
100886   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
100887 }
100888         break;
100889       case 313: /* add_column_fullname ::= fullname */
100890 {
100891   pParse->db->lookaside.bEnabled = 0;
100892   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
100893 }
100894         break;
100895       case 316: /* cmd ::= create_vtab */
100896 {sqlite3VtabFinishParse(pParse,0);}
100897         break;
100898       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
100899 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
100900         break;
100901       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
100902 {
100903     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
100904 }
100905         break;
100906       case 321: /* vtabarg ::= */
100907 {sqlite3VtabArgInit(pParse);}
100908         break;
100909       case 323: /* vtabargtoken ::= ANY */
100910       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
100911       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
100912 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
100913         break;
100914       default:
100915       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
100916       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
100917       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
100918       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
100919       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
100920       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
100921       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
100922       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
100923       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
100924       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
100925       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
100926       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
100927       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
100928       /* (44) type ::= */ yytestcase(yyruleno==44);
100929       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
100930       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
100931       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
100932       /* (54) carglist ::= */ yytestcase(yyruleno==54);
100933       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
100934       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
100935       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
100936       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
100937       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
100938       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
100939       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
100940       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
100941       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
100942       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
100943       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
100944       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
100945       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
100946       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
100947       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
100948       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
100949       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
100950       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
100951       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
100952       /* (326) anylist ::= */ yytestcase(yyruleno==326);
100953       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
100954       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
100955         break;
100956   };
100957   yygoto = yyRuleInfo[yyruleno].lhs;
100958   yysize = yyRuleInfo[yyruleno].nrhs;
100959   yypParser->yyidx -= yysize;
100960   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
100961   if( yyact < YYNSTATE ){
100962 #ifdef NDEBUG
100963     /* If we are not debugging and the reduce action popped at least
100964     ** one element off the stack, then we can push the new element back
100965     ** onto the stack here, and skip the stack overflow test in yy_shift().
100966     ** That gives a significant speed improvement. */
100967     if( yysize ){
100968       yypParser->yyidx++;
100969       yymsp -= yysize-1;
100970       yymsp->stateno = (YYACTIONTYPE)yyact;
100971       yymsp->major = (YYCODETYPE)yygoto;
100972       yymsp->minor = yygotominor;
100973     }else
100974 #endif
100975     {
100976       yy_shift(yypParser,yyact,yygoto,&yygotominor);
100977     }
100978   }else{
100979     assert( yyact == YYNSTATE + YYNRULE + 1 );
100980     yy_accept(yypParser);
100981   }
100982 }
100983
100984 /*
100985 ** The following code executes when the parse fails
100986 */
100987 #ifndef YYNOERRORRECOVERY
100988 static void yy_parse_failed(
100989   yyParser *yypParser           /* The parser */
100990 ){
100991   sqlite3ParserARG_FETCH;
100992 #ifndef NDEBUG
100993   if( yyTraceFILE ){
100994     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
100995   }
100996 #endif
100997   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100998   /* Here code is inserted which will be executed whenever the
100999   ** parser fails */
101000   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101001 }
101002 #endif /* YYNOERRORRECOVERY */
101003
101004 /*
101005 ** The following code executes when a syntax error first occurs.
101006 */
101007 static void yy_syntax_error(
101008   yyParser *yypParser,           /* The parser */
101009   int yymajor,                   /* The major type of the error token */
101010   YYMINORTYPE yyminor            /* The minor type of the error token */
101011 ){
101012   sqlite3ParserARG_FETCH;
101013 #define TOKEN (yyminor.yy0)
101014
101015   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
101016   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
101017   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
101018   pParse->parseError = 1;
101019   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101020 }
101021
101022 /*
101023 ** The following is executed when the parser accepts
101024 */
101025 static void yy_accept(
101026   yyParser *yypParser           /* The parser */
101027 ){
101028   sqlite3ParserARG_FETCH;
101029 #ifndef NDEBUG
101030   if( yyTraceFILE ){
101031     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
101032   }
101033 #endif
101034   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
101035   /* Here code is inserted which will be executed whenever the
101036   ** parser accepts */
101037   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101038 }
101039
101040 /* The main parser program.
101041 ** The first argument is a pointer to a structure obtained from
101042 ** "sqlite3ParserAlloc" which describes the current state of the parser.
101043 ** The second argument is the major token number.  The third is
101044 ** the minor token.  The fourth optional argument is whatever the
101045 ** user wants (and specified in the grammar) and is available for
101046 ** use by the action routines.
101047 **
101048 ** Inputs:
101049 ** <ul>
101050 ** <li> A pointer to the parser (an opaque structure.)
101051 ** <li> The major token number.
101052 ** <li> The minor token number.
101053 ** <li> An option argument of a grammar-specified type.
101054 ** </ul>
101055 **
101056 ** Outputs:
101057 ** None.
101058 */
101059 SQLITE_PRIVATE void sqlite3Parser(
101060   void *yyp,                   /* The parser */
101061   int yymajor,                 /* The major token code number */
101062   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
101063   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
101064 ){
101065   YYMINORTYPE yyminorunion;
101066   int yyact;            /* The parser action. */
101067   int yyendofinput;     /* True if we are at the end of input */
101068 #ifdef YYERRORSYMBOL
101069   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
101070 #endif
101071   yyParser *yypParser;  /* The parser */
101072
101073   /* (re)initialize the parser, if necessary */
101074   yypParser = (yyParser*)yyp;
101075   if( yypParser->yyidx<0 ){
101076 #if YYSTACKDEPTH<=0
101077     if( yypParser->yystksz <=0 ){
101078       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
101079       yyminorunion = yyzerominor;
101080       yyStackOverflow(yypParser, &yyminorunion);
101081       return;
101082     }
101083 #endif
101084     yypParser->yyidx = 0;
101085     yypParser->yyerrcnt = -1;
101086     yypParser->yystack[0].stateno = 0;
101087     yypParser->yystack[0].major = 0;
101088   }
101089   yyminorunion.yy0 = yyminor;
101090   yyendofinput = (yymajor==0);
101091   sqlite3ParserARG_STORE;
101092
101093 #ifndef NDEBUG
101094   if( yyTraceFILE ){
101095     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
101096   }
101097 #endif
101098
101099   do{
101100     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
101101     if( yyact<YYNSTATE ){
101102       assert( !yyendofinput );  /* Impossible to shift the $ token */
101103       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
101104       yypParser->yyerrcnt--;
101105       yymajor = YYNOCODE;
101106     }else if( yyact < YYNSTATE + YYNRULE ){
101107       yy_reduce(yypParser,yyact-YYNSTATE);
101108     }else{
101109       assert( yyact == YY_ERROR_ACTION );
101110 #ifdef YYERRORSYMBOL
101111       int yymx;
101112 #endif
101113 #ifndef NDEBUG
101114       if( yyTraceFILE ){
101115         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
101116       }
101117 #endif
101118 #ifdef YYERRORSYMBOL
101119       /* A syntax error has occurred.
101120       ** The response to an error depends upon whether or not the
101121       ** grammar defines an error token "ERROR".  
101122       **
101123       ** This is what we do if the grammar does define ERROR:
101124       **
101125       **  * Call the %syntax_error function.
101126       **
101127       **  * Begin popping the stack until we enter a state where
101128       **    it is legal to shift the error symbol, then shift
101129       **    the error symbol.
101130       **
101131       **  * Set the error count to three.
101132       **
101133       **  * Begin accepting and shifting new tokens.  No new error
101134       **    processing will occur until three tokens have been
101135       **    shifted successfully.
101136       **
101137       */
101138       if( yypParser->yyerrcnt<0 ){
101139         yy_syntax_error(yypParser,yymajor,yyminorunion);
101140       }
101141       yymx = yypParser->yystack[yypParser->yyidx].major;
101142       if( yymx==YYERRORSYMBOL || yyerrorhit ){
101143 #ifndef NDEBUG
101144         if( yyTraceFILE ){
101145           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
101146              yyTracePrompt,yyTokenName[yymajor]);
101147         }
101148 #endif
101149         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
101150         yymajor = YYNOCODE;
101151       }else{
101152          while(
101153           yypParser->yyidx >= 0 &&
101154           yymx != YYERRORSYMBOL &&
101155           (yyact = yy_find_reduce_action(
101156                         yypParser->yystack[yypParser->yyidx].stateno,
101157                         YYERRORSYMBOL)) >= YYNSTATE
101158         ){
101159           yy_pop_parser_stack(yypParser);
101160         }
101161         if( yypParser->yyidx < 0 || yymajor==0 ){
101162           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101163           yy_parse_failed(yypParser);
101164           yymajor = YYNOCODE;
101165         }else if( yymx!=YYERRORSYMBOL ){
101166           YYMINORTYPE u2;
101167           u2.YYERRSYMDT = 0;
101168           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
101169         }
101170       }
101171       yypParser->yyerrcnt = 3;
101172       yyerrorhit = 1;
101173 #elif defined(YYNOERRORRECOVERY)
101174       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
101175       ** do any kind of error recovery.  Instead, simply invoke the syntax
101176       ** error routine and continue going as if nothing had happened.
101177       **
101178       ** Applications can set this macro (for example inside %include) if
101179       ** they intend to abandon the parse upon the first syntax error seen.
101180       */
101181       yy_syntax_error(yypParser,yymajor,yyminorunion);
101182       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101183       yymajor = YYNOCODE;
101184       
101185 #else  /* YYERRORSYMBOL is not defined */
101186       /* This is what we do if the grammar does not define ERROR:
101187       **
101188       **  * Report an error message, and throw away the input token.
101189       **
101190       **  * If the input token is $, then fail the parse.
101191       **
101192       ** As before, subsequent error messages are suppressed until
101193       ** three input tokens have been successfully shifted.
101194       */
101195       if( yypParser->yyerrcnt<=0 ){
101196         yy_syntax_error(yypParser,yymajor,yyminorunion);
101197       }
101198       yypParser->yyerrcnt = 3;
101199       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101200       if( yyendofinput ){
101201         yy_parse_failed(yypParser);
101202       }
101203       yymajor = YYNOCODE;
101204 #endif
101205     }
101206   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
101207   return;
101208 }
101209
101210 /************** End of parse.c ***********************************************/
101211 /************** Begin file tokenize.c ****************************************/
101212 /*
101213 ** 2001 September 15
101214 **
101215 ** The author disclaims copyright to this source code.  In place of
101216 ** a legal notice, here is a blessing:
101217 **
101218 **    May you do good and not evil.
101219 **    May you find forgiveness for yourself and forgive others.
101220 **    May you share freely, never taking more than you give.
101221 **
101222 *************************************************************************
101223 ** An tokenizer for SQL
101224 **
101225 ** This file contains C code that splits an SQL input string up into
101226 ** individual tokens and sends those tokens one-by-one over to the
101227 ** parser for analysis.
101228 */
101229
101230 /*
101231 ** The charMap() macro maps alphabetic characters into their
101232 ** lower-case ASCII equivalent.  On ASCII machines, this is just
101233 ** an upper-to-lower case map.  On EBCDIC machines we also need
101234 ** to adjust the encoding.  Only alphabetic characters and underscores
101235 ** need to be translated.
101236 */
101237 #ifdef SQLITE_ASCII
101238 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
101239 #endif
101240 #ifdef SQLITE_EBCDIC
101241 # define charMap(X) ebcdicToAscii[(unsigned char)X]
101242 const unsigned char ebcdicToAscii[] = {
101243 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
101244    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
101245    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
101246    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
101247    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
101248    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
101249    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
101250    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
101251    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
101252    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
101253    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
101254    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
101255    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
101256    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
101257    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
101258    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
101259    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
101260 };
101261 #endif
101262
101263 /*
101264 ** The sqlite3KeywordCode function looks up an identifier to determine if
101265 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
101266 ** returned.  If the input is not a keyword, TK_ID is returned.
101267 **
101268 ** The implementation of this routine was generated by a program,
101269 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
101270 ** The output of the mkkeywordhash.c program is written into a file
101271 ** named keywordhash.h and then included into this source file by
101272 ** the #include below.
101273 */
101274 /************** Include keywordhash.h in the middle of tokenize.c ************/
101275 /************** Begin file keywordhash.h *************************************/
101276 /***** This file contains automatically generated code ******
101277 **
101278 ** The code in this file has been automatically generated by
101279 **
101280 **   sqlite/tool/mkkeywordhash.c
101281 **
101282 ** The code in this file implements a function that determines whether
101283 ** or not a given identifier is really an SQL keyword.  The same thing
101284 ** might be implemented more directly using a hand-written hash table.
101285 ** But by using this automatically generated code, the size of the code
101286 ** is substantially reduced.  This is important for embedded applications
101287 ** on platforms with limited memory.
101288 */
101289 /* Hash score: 175 */
101290 static int keywordCode(const char *z, int n){
101291   /* zText[] encodes 811 bytes of keywords in 541 bytes */
101292   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
101293   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
101294   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
101295   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
101296   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
101297   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
101298   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
101299   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
101300   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
101301   /*   INITIALLY                                                          */
101302   static const char zText[540] = {
101303     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
101304     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
101305     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
101306     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
101307     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
101308     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
101309     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
101310     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
101311     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
101312     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
101313     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
101314     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
101315     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
101316     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
101317     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
101318     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
101319     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
101320     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
101321     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
101322     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
101323     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
101324     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
101325     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
101326     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
101327     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
101328     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
101329     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
101330     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
101331     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
101332     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
101333   };
101334   static const unsigned char aHash[127] = {
101335       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
101336       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
101337      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
101338        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
101339        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
101340       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
101341       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
101342       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
101343       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
101344       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
101345   };
101346   static const unsigned char aNext[121] = {
101347        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
101348        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
101349        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
101350        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
101351        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
101352       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
101353       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
101354        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
101355      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
101356       35,  64,   0,   0,
101357   };
101358   static const unsigned char aLen[121] = {
101359        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
101360        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
101361       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
101362        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
101363        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
101364        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
101365        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
101366        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
101367        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
101368        6,   4,   9,   3,
101369   };
101370   static const unsigned short int aOffset[121] = {
101371        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
101372       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
101373       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
101374      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
101375      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
101376      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
101377      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
101378      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
101379      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
101380      521, 527, 531, 536,
101381   };
101382   static const unsigned char aCode[121] = {
101383     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
101384     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
101385     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
101386     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
101387     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
101388     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
101389     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
101390     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
101391     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
101392     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
101393     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
101394     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
101395     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
101396     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
101397     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
101398     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
101399     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
101400     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
101401     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
101402     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
101403     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
101404     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
101405     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
101406     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
101407     TK_ALL,        
101408   };
101409   int h, i;
101410   if( n<2 ) return TK_ID;
101411   h = ((charMap(z[0])*4) ^
101412       (charMap(z[n-1])*3) ^
101413       n) % 127;
101414   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
101415     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
101416       testcase( i==0 ); /* REINDEX */
101417       testcase( i==1 ); /* INDEXED */
101418       testcase( i==2 ); /* INDEX */
101419       testcase( i==3 ); /* DESC */
101420       testcase( i==4 ); /* ESCAPE */
101421       testcase( i==5 ); /* EACH */
101422       testcase( i==6 ); /* CHECK */
101423       testcase( i==7 ); /* KEY */
101424       testcase( i==8 ); /* BEFORE */
101425       testcase( i==9 ); /* FOREIGN */
101426       testcase( i==10 ); /* FOR */
101427       testcase( i==11 ); /* IGNORE */
101428       testcase( i==12 ); /* REGEXP */
101429       testcase( i==13 ); /* EXPLAIN */
101430       testcase( i==14 ); /* INSTEAD */
101431       testcase( i==15 ); /* ADD */
101432       testcase( i==16 ); /* DATABASE */
101433       testcase( i==17 ); /* AS */
101434       testcase( i==18 ); /* SELECT */
101435       testcase( i==19 ); /* TABLE */
101436       testcase( i==20 ); /* LEFT */
101437       testcase( i==21 ); /* THEN */
101438       testcase( i==22 ); /* END */
101439       testcase( i==23 ); /* DEFERRABLE */
101440       testcase( i==24 ); /* ELSE */
101441       testcase( i==25 ); /* EXCEPT */
101442       testcase( i==26 ); /* TRANSACTION */
101443       testcase( i==27 ); /* ACTION */
101444       testcase( i==28 ); /* ON */
101445       testcase( i==29 ); /* NATURAL */
101446       testcase( i==30 ); /* ALTER */
101447       testcase( i==31 ); /* RAISE */
101448       testcase( i==32 ); /* EXCLUSIVE */
101449       testcase( i==33 ); /* EXISTS */
101450       testcase( i==34 ); /* SAVEPOINT */
101451       testcase( i==35 ); /* INTERSECT */
101452       testcase( i==36 ); /* TRIGGER */
101453       testcase( i==37 ); /* REFERENCES */
101454       testcase( i==38 ); /* CONSTRAINT */
101455       testcase( i==39 ); /* INTO */
101456       testcase( i==40 ); /* OFFSET */
101457       testcase( i==41 ); /* OF */
101458       testcase( i==42 ); /* SET */
101459       testcase( i==43 ); /* TEMPORARY */
101460       testcase( i==44 ); /* TEMP */
101461       testcase( i==45 ); /* OR */
101462       testcase( i==46 ); /* UNIQUE */
101463       testcase( i==47 ); /* QUERY */
101464       testcase( i==48 ); /* ATTACH */
101465       testcase( i==49 ); /* HAVING */
101466       testcase( i==50 ); /* GROUP */
101467       testcase( i==51 ); /* UPDATE */
101468       testcase( i==52 ); /* BEGIN */
101469       testcase( i==53 ); /* INNER */
101470       testcase( i==54 ); /* RELEASE */
101471       testcase( i==55 ); /* BETWEEN */
101472       testcase( i==56 ); /* NOTNULL */
101473       testcase( i==57 ); /* NOT */
101474       testcase( i==58 ); /* NO */
101475       testcase( i==59 ); /* NULL */
101476       testcase( i==60 ); /* LIKE */
101477       testcase( i==61 ); /* CASCADE */
101478       testcase( i==62 ); /* ASC */
101479       testcase( i==63 ); /* DELETE */
101480       testcase( i==64 ); /* CASE */
101481       testcase( i==65 ); /* COLLATE */
101482       testcase( i==66 ); /* CREATE */
101483       testcase( i==67 ); /* CURRENT_DATE */
101484       testcase( i==68 ); /* DETACH */
101485       testcase( i==69 ); /* IMMEDIATE */
101486       testcase( i==70 ); /* JOIN */
101487       testcase( i==71 ); /* INSERT */
101488       testcase( i==72 ); /* MATCH */
101489       testcase( i==73 ); /* PLAN */
101490       testcase( i==74 ); /* ANALYZE */
101491       testcase( i==75 ); /* PRAGMA */
101492       testcase( i==76 ); /* ABORT */
101493       testcase( i==77 ); /* VALUES */
101494       testcase( i==78 ); /* VIRTUAL */
101495       testcase( i==79 ); /* LIMIT */
101496       testcase( i==80 ); /* WHEN */
101497       testcase( i==81 ); /* WHERE */
101498       testcase( i==82 ); /* RENAME */
101499       testcase( i==83 ); /* AFTER */
101500       testcase( i==84 ); /* REPLACE */
101501       testcase( i==85 ); /* AND */
101502       testcase( i==86 ); /* DEFAULT */
101503       testcase( i==87 ); /* AUTOINCREMENT */
101504       testcase( i==88 ); /* TO */
101505       testcase( i==89 ); /* IN */
101506       testcase( i==90 ); /* CAST */
101507       testcase( i==91 ); /* COLUMN */
101508       testcase( i==92 ); /* COMMIT */
101509       testcase( i==93 ); /* CONFLICT */
101510       testcase( i==94 ); /* CROSS */
101511       testcase( i==95 ); /* CURRENT_TIMESTAMP */
101512       testcase( i==96 ); /* CURRENT_TIME */
101513       testcase( i==97 ); /* PRIMARY */
101514       testcase( i==98 ); /* DEFERRED */
101515       testcase( i==99 ); /* DISTINCT */
101516       testcase( i==100 ); /* IS */
101517       testcase( i==101 ); /* DROP */
101518       testcase( i==102 ); /* FAIL */
101519       testcase( i==103 ); /* FROM */
101520       testcase( i==104 ); /* FULL */
101521       testcase( i==105 ); /* GLOB */
101522       testcase( i==106 ); /* BY */
101523       testcase( i==107 ); /* IF */
101524       testcase( i==108 ); /* ISNULL */
101525       testcase( i==109 ); /* ORDER */
101526       testcase( i==110 ); /* RESTRICT */
101527       testcase( i==111 ); /* OUTER */
101528       testcase( i==112 ); /* RIGHT */
101529       testcase( i==113 ); /* ROLLBACK */
101530       testcase( i==114 ); /* ROW */
101531       testcase( i==115 ); /* UNION */
101532       testcase( i==116 ); /* USING */
101533       testcase( i==117 ); /* VACUUM */
101534       testcase( i==118 ); /* VIEW */
101535       testcase( i==119 ); /* INITIALLY */
101536       testcase( i==120 ); /* ALL */
101537       return aCode[i];
101538     }
101539   }
101540   return TK_ID;
101541 }
101542 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
101543   return keywordCode((char*)z, n);
101544 }
101545 #define SQLITE_N_KEYWORD 121
101546
101547 /************** End of keywordhash.h *****************************************/
101548 /************** Continuing where we left off in tokenize.c *******************/
101549
101550
101551 /*
101552 ** If X is a character that can be used in an identifier then
101553 ** IdChar(X) will be true.  Otherwise it is false.
101554 **
101555 ** For ASCII, any character with the high-order bit set is
101556 ** allowed in an identifier.  For 7-bit characters, 
101557 ** sqlite3IsIdChar[X] must be 1.
101558 **
101559 ** For EBCDIC, the rules are more complex but have the same
101560 ** end result.
101561 **
101562 ** Ticket #1066.  the SQL standard does not allow '$' in the
101563 ** middle of identfiers.  But many SQL implementations do. 
101564 ** SQLite will allow '$' in identifiers for compatibility.
101565 ** But the feature is undocumented.
101566 */
101567 #ifdef SQLITE_ASCII
101568 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
101569 #endif
101570 #ifdef SQLITE_EBCDIC
101571 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
101572 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
101573     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
101574     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
101575     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
101576     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
101577     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
101578     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
101579     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
101580     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
101581     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
101582     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
101583     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
101584     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
101585 };
101586 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
101587 #endif
101588
101589
101590 /*
101591 ** Return the length of the token that begins at z[0]. 
101592 ** Store the token type in *tokenType before returning.
101593 */
101594 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
101595   int i, c;
101596   switch( *z ){
101597     case ' ': case '\t': case '\n': case '\f': case '\r': {
101598       testcase( z[0]==' ' );
101599       testcase( z[0]=='\t' );
101600       testcase( z[0]=='\n' );
101601       testcase( z[0]=='\f' );
101602       testcase( z[0]=='\r' );
101603       for(i=1; sqlite3Isspace(z[i]); i++){}
101604       *tokenType = TK_SPACE;
101605       return i;
101606     }
101607     case '-': {
101608       if( z[1]=='-' ){
101609         /* IMP: R-15891-05542 -- syntax diagram for comments */
101610         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
101611         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101612         return i;
101613       }
101614       *tokenType = TK_MINUS;
101615       return 1;
101616     }
101617     case '(': {
101618       *tokenType = TK_LP;
101619       return 1;
101620     }
101621     case ')': {
101622       *tokenType = TK_RP;
101623       return 1;
101624     }
101625     case ';': {
101626       *tokenType = TK_SEMI;
101627       return 1;
101628     }
101629     case '+': {
101630       *tokenType = TK_PLUS;
101631       return 1;
101632     }
101633     case '*': {
101634       *tokenType = TK_STAR;
101635       return 1;
101636     }
101637     case '/': {
101638       if( z[1]!='*' || z[2]==0 ){
101639         *tokenType = TK_SLASH;
101640         return 1;
101641       }
101642       /* IMP: R-15891-05542 -- syntax diagram for comments */
101643       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
101644       if( c ) i++;
101645       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101646       return i;
101647     }
101648     case '%': {
101649       *tokenType = TK_REM;
101650       return 1;
101651     }
101652     case '=': {
101653       *tokenType = TK_EQ;
101654       return 1 + (z[1]=='=');
101655     }
101656     case '<': {
101657       if( (c=z[1])=='=' ){
101658         *tokenType = TK_LE;
101659         return 2;
101660       }else if( c=='>' ){
101661         *tokenType = TK_NE;
101662         return 2;
101663       }else if( c=='<' ){
101664         *tokenType = TK_LSHIFT;
101665         return 2;
101666       }else{
101667         *tokenType = TK_LT;
101668         return 1;
101669       }
101670     }
101671     case '>': {
101672       if( (c=z[1])=='=' ){
101673         *tokenType = TK_GE;
101674         return 2;
101675       }else if( c=='>' ){
101676         *tokenType = TK_RSHIFT;
101677         return 2;
101678       }else{
101679         *tokenType = TK_GT;
101680         return 1;
101681       }
101682     }
101683     case '!': {
101684       if( z[1]!='=' ){
101685         *tokenType = TK_ILLEGAL;
101686         return 2;
101687       }else{
101688         *tokenType = TK_NE;
101689         return 2;
101690       }
101691     }
101692     case '|': {
101693       if( z[1]!='|' ){
101694         *tokenType = TK_BITOR;
101695         return 1;
101696       }else{
101697         *tokenType = TK_CONCAT;
101698         return 2;
101699       }
101700     }
101701     case ',': {
101702       *tokenType = TK_COMMA;
101703       return 1;
101704     }
101705     case '&': {
101706       *tokenType = TK_BITAND;
101707       return 1;
101708     }
101709     case '~': {
101710       *tokenType = TK_BITNOT;
101711       return 1;
101712     }
101713     case '`':
101714     case '\'':
101715     case '"': {
101716       int delim = z[0];
101717       testcase( delim=='`' );
101718       testcase( delim=='\'' );
101719       testcase( delim=='"' );
101720       for(i=1; (c=z[i])!=0; i++){
101721         if( c==delim ){
101722           if( z[i+1]==delim ){
101723             i++;
101724           }else{
101725             break;
101726           }
101727         }
101728       }
101729       if( c=='\'' ){
101730         *tokenType = TK_STRING;
101731         return i+1;
101732       }else if( c!=0 ){
101733         *tokenType = TK_ID;
101734         return i+1;
101735       }else{
101736         *tokenType = TK_ILLEGAL;
101737         return i;
101738       }
101739     }
101740     case '.': {
101741 #ifndef SQLITE_OMIT_FLOATING_POINT
101742       if( !sqlite3Isdigit(z[1]) )
101743 #endif
101744       {
101745         *tokenType = TK_DOT;
101746         return 1;
101747       }
101748       /* If the next character is a digit, this is a floating point
101749       ** number that begins with ".".  Fall thru into the next case */
101750     }
101751     case '0': case '1': case '2': case '3': case '4':
101752     case '5': case '6': case '7': case '8': case '9': {
101753       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
101754       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
101755       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
101756       testcase( z[0]=='9' );
101757       *tokenType = TK_INTEGER;
101758       for(i=0; sqlite3Isdigit(z[i]); i++){}
101759 #ifndef SQLITE_OMIT_FLOATING_POINT
101760       if( z[i]=='.' ){
101761         i++;
101762         while( sqlite3Isdigit(z[i]) ){ i++; }
101763         *tokenType = TK_FLOAT;
101764       }
101765       if( (z[i]=='e' || z[i]=='E') &&
101766            ( sqlite3Isdigit(z[i+1]) 
101767             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
101768            )
101769       ){
101770         i += 2;
101771         while( sqlite3Isdigit(z[i]) ){ i++; }
101772         *tokenType = TK_FLOAT;
101773       }
101774 #endif
101775       while( IdChar(z[i]) ){
101776         *tokenType = TK_ILLEGAL;
101777         i++;
101778       }
101779       return i;
101780     }
101781     case '[': {
101782       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
101783       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
101784       return i;
101785     }
101786     case '?': {
101787       *tokenType = TK_VARIABLE;
101788       for(i=1; sqlite3Isdigit(z[i]); i++){}
101789       return i;
101790     }
101791     case '#': {
101792       for(i=1; sqlite3Isdigit(z[i]); i++){}
101793       if( i>1 ){
101794         /* Parameters of the form #NNN (where NNN is a number) are used
101795         ** internally by sqlite3NestedParse.  */
101796         *tokenType = TK_REGISTER;
101797         return i;
101798       }
101799       /* Fall through into the next case if the '#' is not followed by
101800       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
101801     }
101802 #ifndef SQLITE_OMIT_TCL_VARIABLE
101803     case '$':
101804 #endif
101805     case '@':  /* For compatibility with MS SQL Server */
101806     case ':': {
101807       int n = 0;
101808       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
101809       *tokenType = TK_VARIABLE;
101810       for(i=1; (c=z[i])!=0; i++){
101811         if( IdChar(c) ){
101812           n++;
101813 #ifndef SQLITE_OMIT_TCL_VARIABLE
101814         }else if( c=='(' && n>0 ){
101815           do{
101816             i++;
101817           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
101818           if( c==')' ){
101819             i++;
101820           }else{
101821             *tokenType = TK_ILLEGAL;
101822           }
101823           break;
101824         }else if( c==':' && z[i+1]==':' ){
101825           i++;
101826 #endif
101827         }else{
101828           break;
101829         }
101830       }
101831       if( n==0 ) *tokenType = TK_ILLEGAL;
101832       return i;
101833     }
101834 #ifndef SQLITE_OMIT_BLOB_LITERAL
101835     case 'x': case 'X': {
101836       testcase( z[0]=='x' ); testcase( z[0]=='X' );
101837       if( z[1]=='\'' ){
101838         *tokenType = TK_BLOB;
101839         for(i=2; (c=z[i])!=0 && c!='\''; i++){
101840           if( !sqlite3Isxdigit(c) ){
101841             *tokenType = TK_ILLEGAL;
101842           }
101843         }
101844         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
101845         if( c ) i++;
101846         return i;
101847       }
101848       /* Otherwise fall through to the next case */
101849     }
101850 #endif
101851     default: {
101852       if( !IdChar(*z) ){
101853         break;
101854       }
101855       for(i=1; IdChar(z[i]); i++){}
101856       *tokenType = keywordCode((char*)z, i);
101857       return i;
101858     }
101859   }
101860   *tokenType = TK_ILLEGAL;
101861   return 1;
101862 }
101863
101864 /*
101865 ** Run the parser on the given SQL string.  The parser structure is
101866 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
101867 ** then an and attempt is made to write an error message into 
101868 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
101869 ** error message.
101870 */
101871 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
101872   int nErr = 0;                   /* Number of errors encountered */
101873   int i;                          /* Loop counter */
101874   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
101875   int tokenType;                  /* type of the next token */
101876   int lastTokenParsed = -1;       /* type of the previous token */
101877   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
101878   sqlite3 *db = pParse->db;       /* The database connection */
101879   int mxSqlLen;                   /* Max length of an SQL string */
101880
101881
101882   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
101883   if( db->activeVdbeCnt==0 ){
101884     db->u1.isInterrupted = 0;
101885   }
101886   pParse->rc = SQLITE_OK;
101887   pParse->zTail = zSql;
101888   i = 0;
101889   assert( pzErrMsg!=0 );
101890   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
101891   if( pEngine==0 ){
101892     db->mallocFailed = 1;
101893     return SQLITE_NOMEM;
101894   }
101895   assert( pParse->pNewTable==0 );
101896   assert( pParse->pNewTrigger==0 );
101897   assert( pParse->nVar==0 );
101898   assert( pParse->nVarExpr==0 );
101899   assert( pParse->nVarExprAlloc==0 );
101900   assert( pParse->apVarExpr==0 );
101901   enableLookaside = db->lookaside.bEnabled;
101902   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
101903   while( !db->mallocFailed && zSql[i]!=0 ){
101904     assert( i>=0 );
101905     pParse->sLastToken.z = &zSql[i];
101906     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
101907     i += pParse->sLastToken.n;
101908     if( i>mxSqlLen ){
101909       pParse->rc = SQLITE_TOOBIG;
101910       break;
101911     }
101912     switch( tokenType ){
101913       case TK_SPACE: {
101914         if( db->u1.isInterrupted ){
101915           sqlite3ErrorMsg(pParse, "interrupt");
101916           pParse->rc = SQLITE_INTERRUPT;
101917           goto abort_parse;
101918         }
101919         break;
101920       }
101921       case TK_ILLEGAL: {
101922         sqlite3DbFree(db, *pzErrMsg);
101923         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
101924                         &pParse->sLastToken);
101925         nErr++;
101926         goto abort_parse;
101927       }
101928       case TK_SEMI: {
101929         pParse->zTail = &zSql[i];
101930         /* Fall thru into the default case */
101931       }
101932       default: {
101933         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
101934         lastTokenParsed = tokenType;
101935         if( pParse->rc!=SQLITE_OK ){
101936           goto abort_parse;
101937         }
101938         break;
101939       }
101940     }
101941   }
101942 abort_parse:
101943   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
101944     if( lastTokenParsed!=TK_SEMI ){
101945       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
101946       pParse->zTail = &zSql[i];
101947     }
101948     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
101949   }
101950 #ifdef YYTRACKMAXSTACKDEPTH
101951   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
101952       sqlite3ParserStackPeak(pEngine)
101953   );
101954 #endif /* YYDEBUG */
101955   sqlite3ParserFree(pEngine, sqlite3_free);
101956   db->lookaside.bEnabled = enableLookaside;
101957   if( db->mallocFailed ){
101958     pParse->rc = SQLITE_NOMEM;
101959   }
101960   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
101961     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
101962   }
101963   assert( pzErrMsg!=0 );
101964   if( pParse->zErrMsg ){
101965     *pzErrMsg = pParse->zErrMsg;
101966     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
101967     pParse->zErrMsg = 0;
101968     nErr++;
101969   }
101970   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
101971     sqlite3VdbeDelete(pParse->pVdbe);
101972     pParse->pVdbe = 0;
101973   }
101974 #ifndef SQLITE_OMIT_SHARED_CACHE
101975   if( pParse->nested==0 ){
101976     sqlite3DbFree(db, pParse->aTableLock);
101977     pParse->aTableLock = 0;
101978     pParse->nTableLock = 0;
101979   }
101980 #endif
101981 #ifndef SQLITE_OMIT_VIRTUALTABLE
101982   sqlite3DbFree(db, pParse->apVtabLock);
101983 #endif
101984
101985   if( !IN_DECLARE_VTAB ){
101986     /* If the pParse->declareVtab flag is set, do not delete any table 
101987     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
101988     ** will take responsibility for freeing the Table structure.
101989     */
101990     sqlite3DeleteTable(pParse->pNewTable);
101991   }
101992
101993   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
101994   sqlite3DbFree(db, pParse->apVarExpr);
101995   sqlite3DbFree(db, pParse->aAlias);
101996   while( pParse->pAinc ){
101997     AutoincInfo *p = pParse->pAinc;
101998     pParse->pAinc = p->pNext;
101999     sqlite3DbFree(db, p);
102000   }
102001   while( pParse->pZombieTab ){
102002     Table *p = pParse->pZombieTab;
102003     pParse->pZombieTab = p->pNextZombie;
102004     sqlite3DeleteTable(p);
102005   }
102006   if( nErr>0 && pParse->rc==SQLITE_OK ){
102007     pParse->rc = SQLITE_ERROR;
102008   }
102009   return nErr;
102010 }
102011
102012 /************** End of tokenize.c ********************************************/
102013 /************** Begin file complete.c ****************************************/
102014 /*
102015 ** 2001 September 15
102016 **
102017 ** The author disclaims copyright to this source code.  In place of
102018 ** a legal notice, here is a blessing:
102019 **
102020 **    May you do good and not evil.
102021 **    May you find forgiveness for yourself and forgive others.
102022 **    May you share freely, never taking more than you give.
102023 **
102024 *************************************************************************
102025 ** An tokenizer for SQL
102026 **
102027 ** This file contains C code that implements the sqlite3_complete() API.
102028 ** This code used to be part of the tokenizer.c source file.  But by
102029 ** separating it out, the code will be automatically omitted from
102030 ** static links that do not use it.
102031 */
102032 #ifndef SQLITE_OMIT_COMPLETE
102033
102034 /*
102035 ** This is defined in tokenize.c.  We just have to import the definition.
102036 */
102037 #ifndef SQLITE_AMALGAMATION
102038 #ifdef SQLITE_ASCII
102039 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
102040 #endif
102041 #ifdef SQLITE_EBCDIC
102042 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
102043 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
102044 #endif
102045 #endif /* SQLITE_AMALGAMATION */
102046
102047
102048 /*
102049 ** Token types used by the sqlite3_complete() routine.  See the header
102050 ** comments on that procedure for additional information.
102051 */
102052 #define tkSEMI    0
102053 #define tkWS      1
102054 #define tkOTHER   2
102055 #ifndef SQLITE_OMIT_TRIGGER
102056 #define tkEXPLAIN 3
102057 #define tkCREATE  4
102058 #define tkTEMP    5
102059 #define tkTRIGGER 6
102060 #define tkEND     7
102061 #endif
102062
102063 /*
102064 ** Return TRUE if the given SQL string ends in a semicolon.
102065 **
102066 ** Special handling is require for CREATE TRIGGER statements.
102067 ** Whenever the CREATE TRIGGER keywords are seen, the statement
102068 ** must end with ";END;".
102069 **
102070 ** This implementation uses a state machine with 8 states:
102071 **
102072 **   (0) INVALID   We have not yet seen a non-whitespace character.
102073 **
102074 **   (1) START     At the beginning or end of an SQL statement.  This routine
102075 **                 returns 1 if it ends in the START state and 0 if it ends
102076 **                 in any other state.
102077 **
102078 **   (2) NORMAL    We are in the middle of statement which ends with a single
102079 **                 semicolon.
102080 **
102081 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
102082 **                 a statement.
102083 **
102084 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
102085 **                 statement, possibly preceeded by EXPLAIN and/or followed by
102086 **                 TEMP or TEMPORARY
102087 **
102088 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
102089 **                 ended by a semicolon, the keyword END, and another semicolon.
102090 **
102091 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
102092 **                 the end of a trigger definition.
102093 **
102094 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
102095 **                 of a trigger difinition.
102096 **
102097 ** Transitions between states above are determined by tokens extracted
102098 ** from the input.  The following tokens are significant:
102099 **
102100 **   (0) tkSEMI      A semicolon.
102101 **   (1) tkWS        Whitespace.
102102 **   (2) tkOTHER     Any other SQL token.
102103 **   (3) tkEXPLAIN   The "explain" keyword.
102104 **   (4) tkCREATE    The "create" keyword.
102105 **   (5) tkTEMP      The "temp" or "temporary" keyword.
102106 **   (6) tkTRIGGER   The "trigger" keyword.
102107 **   (7) tkEND       The "end" keyword.
102108 **
102109 ** Whitespace never causes a state transition and is always ignored.
102110 ** This means that a SQL string of all whitespace is invalid.
102111 **
102112 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
102113 ** to recognize the end of a trigger can be omitted.  All we have to do
102114 ** is look for a semicolon that is not part of an string or comment.
102115 */
102116 SQLITE_API int sqlite3_complete(const char *zSql){
102117   u8 state = 0;   /* Current state, using numbers defined in header comment */
102118   u8 token;       /* Value of the next token */
102119
102120 #ifndef SQLITE_OMIT_TRIGGER
102121   /* A complex statement machine used to detect the end of a CREATE TRIGGER
102122   ** statement.  This is the normal case.
102123   */
102124   static const u8 trans[8][8] = {
102125                      /* Token:                                                */
102126      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
102127      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
102128      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
102129      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
102130      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
102131      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
102132      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
102133      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
102134      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
102135   };
102136 #else
102137   /* If triggers are not supported by this compile then the statement machine
102138   ** used to detect the end of a statement is much simplier
102139   */
102140   static const u8 trans[3][3] = {
102141                      /* Token:           */
102142      /* State:       **  SEMI  WS  OTHER */
102143      /* 0 INVALID: */ {    1,  0,     2, },
102144      /* 1   START: */ {    1,  1,     2, },
102145      /* 2  NORMAL: */ {    1,  2,     2, },
102146   };
102147 #endif /* SQLITE_OMIT_TRIGGER */
102148
102149   while( *zSql ){
102150     switch( *zSql ){
102151       case ';': {  /* A semicolon */
102152         token = tkSEMI;
102153         break;
102154       }
102155       case ' ':
102156       case '\r':
102157       case '\t':
102158       case '\n':
102159       case '\f': {  /* White space is ignored */
102160         token = tkWS;
102161         break;
102162       }
102163       case '/': {   /* C-style comments */
102164         if( zSql[1]!='*' ){
102165           token = tkOTHER;
102166           break;
102167         }
102168         zSql += 2;
102169         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
102170         if( zSql[0]==0 ) return 0;
102171         zSql++;
102172         token = tkWS;
102173         break;
102174       }
102175       case '-': {   /* SQL-style comments from "--" to end of line */
102176         if( zSql[1]!='-' ){
102177           token = tkOTHER;
102178           break;
102179         }
102180         while( *zSql && *zSql!='\n' ){ zSql++; }
102181         if( *zSql==0 ) return state==1;
102182         token = tkWS;
102183         break;
102184       }
102185       case '[': {   /* Microsoft-style identifiers in [...] */
102186         zSql++;
102187         while( *zSql && *zSql!=']' ){ zSql++; }
102188         if( *zSql==0 ) return 0;
102189         token = tkOTHER;
102190         break;
102191       }
102192       case '`':     /* Grave-accent quoted symbols used by MySQL */
102193       case '"':     /* single- and double-quoted strings */
102194       case '\'': {
102195         int c = *zSql;
102196         zSql++;
102197         while( *zSql && *zSql!=c ){ zSql++; }
102198         if( *zSql==0 ) return 0;
102199         token = tkOTHER;
102200         break;
102201       }
102202       default: {
102203 #ifdef SQLITE_EBCDIC
102204         unsigned char c;
102205 #endif
102206         if( IdChar((u8)*zSql) ){
102207           /* Keywords and unquoted identifiers */
102208           int nId;
102209           for(nId=1; IdChar(zSql[nId]); nId++){}
102210 #ifdef SQLITE_OMIT_TRIGGER
102211           token = tkOTHER;
102212 #else
102213           switch( *zSql ){
102214             case 'c': case 'C': {
102215               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
102216                 token = tkCREATE;
102217               }else{
102218                 token = tkOTHER;
102219               }
102220               break;
102221             }
102222             case 't': case 'T': {
102223               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
102224                 token = tkTRIGGER;
102225               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
102226                 token = tkTEMP;
102227               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
102228                 token = tkTEMP;
102229               }else{
102230                 token = tkOTHER;
102231               }
102232               break;
102233             }
102234             case 'e':  case 'E': {
102235               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
102236                 token = tkEND;
102237               }else
102238 #ifndef SQLITE_OMIT_EXPLAIN
102239               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
102240                 token = tkEXPLAIN;
102241               }else
102242 #endif
102243               {
102244                 token = tkOTHER;
102245               }
102246               break;
102247             }
102248             default: {
102249               token = tkOTHER;
102250               break;
102251             }
102252           }
102253 #endif /* SQLITE_OMIT_TRIGGER */
102254           zSql += nId-1;
102255         }else{
102256           /* Operators and special symbols */
102257           token = tkOTHER;
102258         }
102259         break;
102260       }
102261     }
102262     state = trans[state][token];
102263     zSql++;
102264   }
102265   return state==1;
102266 }
102267
102268 #ifndef SQLITE_OMIT_UTF16
102269 /*
102270 ** This routine is the same as the sqlite3_complete() routine described
102271 ** above, except that the parameter is required to be UTF-16 encoded, not
102272 ** UTF-8.
102273 */
102274 SQLITE_API int sqlite3_complete16(const void *zSql){
102275   sqlite3_value *pVal;
102276   char const *zSql8;
102277   int rc = SQLITE_NOMEM;
102278
102279 #ifndef SQLITE_OMIT_AUTOINIT
102280   rc = sqlite3_initialize();
102281   if( rc ) return rc;
102282 #endif
102283   pVal = sqlite3ValueNew(0);
102284   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
102285   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
102286   if( zSql8 ){
102287     rc = sqlite3_complete(zSql8);
102288   }else{
102289     rc = SQLITE_NOMEM;
102290   }
102291   sqlite3ValueFree(pVal);
102292   return sqlite3ApiExit(0, rc);
102293 }
102294 #endif /* SQLITE_OMIT_UTF16 */
102295 #endif /* SQLITE_OMIT_COMPLETE */
102296
102297 /************** End of complete.c ********************************************/
102298 /************** Begin file main.c ********************************************/
102299 /*
102300 ** 2001 September 15
102301 **
102302 ** The author disclaims copyright to this source code.  In place of
102303 ** a legal notice, here is a blessing:
102304 **
102305 **    May you do good and not evil.
102306 **    May you find forgiveness for yourself and forgive others.
102307 **    May you share freely, never taking more than you give.
102308 **
102309 *************************************************************************
102310 ** Main file for the SQLite library.  The routines in this file
102311 ** implement the programmer interface to the library.  Routines in
102312 ** other files are for internal use by SQLite and should not be
102313 ** accessed by users of the library.
102314 */
102315
102316 #ifdef SQLITE_ENABLE_FTS3
102317 /************** Include fts3.h in the middle of main.c ***********************/
102318 /************** Begin file fts3.h ********************************************/
102319 /*
102320 ** 2006 Oct 10
102321 **
102322 ** The author disclaims copyright to this source code.  In place of
102323 ** a legal notice, here is a blessing:
102324 **
102325 **    May you do good and not evil.
102326 **    May you find forgiveness for yourself and forgive others.
102327 **    May you share freely, never taking more than you give.
102328 **
102329 ******************************************************************************
102330 **
102331 ** This header file is used by programs that want to link against the
102332 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
102333 */
102334
102335 #if 0
102336 extern "C" {
102337 #endif  /* __cplusplus */
102338
102339 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
102340
102341 #if 0
102342 }  /* extern "C" */
102343 #endif  /* __cplusplus */
102344
102345 /************** End of fts3.h ************************************************/
102346 /************** Continuing where we left off in main.c ***********************/
102347 #endif
102348 #ifdef SQLITE_ENABLE_RTREE
102349 /************** Include rtree.h in the middle of main.c **********************/
102350 /************** Begin file rtree.h *******************************************/
102351 /*
102352 ** 2008 May 26
102353 **
102354 ** The author disclaims copyright to this source code.  In place of
102355 ** a legal notice, here is a blessing:
102356 **
102357 **    May you do good and not evil.
102358 **    May you find forgiveness for yourself and forgive others.
102359 **    May you share freely, never taking more than you give.
102360 **
102361 ******************************************************************************
102362 **
102363 ** This header file is used by programs that want to link against the
102364 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
102365 */
102366
102367 #if 0
102368 extern "C" {
102369 #endif  /* __cplusplus */
102370
102371 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
102372
102373 #if 0
102374 }  /* extern "C" */
102375 #endif  /* __cplusplus */
102376
102377 /************** End of rtree.h ***********************************************/
102378 /************** Continuing where we left off in main.c ***********************/
102379 #endif
102380 #ifdef SQLITE_ENABLE_ICU
102381 /************** Include sqliteicu.h in the middle of main.c ******************/
102382 /************** Begin file sqliteicu.h ***************************************/
102383 /*
102384 ** 2008 May 26
102385 **
102386 ** The author disclaims copyright to this source code.  In place of
102387 ** a legal notice, here is a blessing:
102388 **
102389 **    May you do good and not evil.
102390 **    May you find forgiveness for yourself and forgive others.
102391 **    May you share freely, never taking more than you give.
102392 **
102393 ******************************************************************************
102394 **
102395 ** This header file is used by programs that want to link against the
102396 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
102397 */
102398
102399 #if 0
102400 extern "C" {
102401 #endif  /* __cplusplus */
102402
102403 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
102404
102405 #if 0
102406 }  /* extern "C" */
102407 #endif  /* __cplusplus */
102408
102409
102410 /************** End of sqliteicu.h *******************************************/
102411 /************** Continuing where we left off in main.c ***********************/
102412 #endif
102413
102414 /*
102415 ** The version of the library
102416 */
102417 #ifndef SQLITE_AMALGAMATION
102418 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
102419 #endif
102420 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
102421 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
102422 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
102423 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
102424
102425 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
102426 /*
102427 ** If the following function pointer is not NULL and if
102428 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
102429 ** I/O active are written using this function.  These messages
102430 ** are intended for debugging activity only.
102431 */
102432 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
102433 #endif
102434
102435 /*
102436 ** If the following global variable points to a string which is the
102437 ** name of a directory, then that directory will be used to store
102438 ** temporary files.
102439 **
102440 ** See also the "PRAGMA temp_store_directory" SQL command.
102441 */
102442 SQLITE_API char *sqlite3_temp_directory = 0;
102443
102444 /*
102445 ** Initialize SQLite.  
102446 **
102447 ** This routine must be called to initialize the memory allocation,
102448 ** VFS, and mutex subsystems prior to doing any serious work with
102449 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
102450 ** this routine will be called automatically by key routines such as
102451 ** sqlite3_open().  
102452 **
102453 ** This routine is a no-op except on its very first call for the process,
102454 ** or for the first call after a call to sqlite3_shutdown.
102455 **
102456 ** The first thread to call this routine runs the initialization to
102457 ** completion.  If subsequent threads call this routine before the first
102458 ** thread has finished the initialization process, then the subsequent
102459 ** threads must block until the first thread finishes with the initialization.
102460 **
102461 ** The first thread might call this routine recursively.  Recursive
102462 ** calls to this routine should not block, of course.  Otherwise the
102463 ** initialization process would never complete.
102464 **
102465 ** Let X be the first thread to enter this routine.  Let Y be some other
102466 ** thread.  Then while the initial invocation of this routine by X is
102467 ** incomplete, it is required that:
102468 **
102469 **    *  Calls to this routine from Y must block until the outer-most
102470 **       call by X completes.
102471 **
102472 **    *  Recursive calls to this routine from thread X return immediately
102473 **       without blocking.
102474 */
102475 SQLITE_API int sqlite3_initialize(void){
102476   sqlite3_mutex *pMaster;                      /* The main static mutex */
102477   int rc;                                      /* Result code */
102478
102479 #ifdef SQLITE_OMIT_WSD
102480   rc = sqlite3_wsd_init(4096, 24);
102481   if( rc!=SQLITE_OK ){
102482     return rc;
102483   }
102484 #endif
102485
102486   /* If SQLite is already completely initialized, then this call
102487   ** to sqlite3_initialize() should be a no-op.  But the initialization
102488   ** must be complete.  So isInit must not be set until the very end
102489   ** of this routine.
102490   */
102491   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
102492
102493   /* Make sure the mutex subsystem is initialized.  If unable to 
102494   ** initialize the mutex subsystem, return early with the error.
102495   ** If the system is so sick that we are unable to allocate a mutex,
102496   ** there is not much SQLite is going to be able to do.
102497   **
102498   ** The mutex subsystem must take care of serializing its own
102499   ** initialization.
102500   */
102501   rc = sqlite3MutexInit();
102502   if( rc ) return rc;
102503
102504   /* Initialize the malloc() system and the recursive pInitMutex mutex.
102505   ** This operation is protected by the STATIC_MASTER mutex.  Note that
102506   ** MutexAlloc() is called for a static mutex prior to initializing the
102507   ** malloc subsystem - this implies that the allocation of a static
102508   ** mutex must not require support from the malloc subsystem.
102509   */
102510   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102511   sqlite3_mutex_enter(pMaster);
102512   sqlite3GlobalConfig.isMutexInit = 1;
102513   if( !sqlite3GlobalConfig.isMallocInit ){
102514     rc = sqlite3MallocInit();
102515   }
102516   if( rc==SQLITE_OK ){
102517     sqlite3GlobalConfig.isMallocInit = 1;
102518     if( !sqlite3GlobalConfig.pInitMutex ){
102519       sqlite3GlobalConfig.pInitMutex =
102520            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
102521       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
102522         rc = SQLITE_NOMEM;
102523       }
102524     }
102525   }
102526   if( rc==SQLITE_OK ){
102527     sqlite3GlobalConfig.nRefInitMutex++;
102528   }
102529   sqlite3_mutex_leave(pMaster);
102530
102531   /* If rc is not SQLITE_OK at this point, then either the malloc
102532   ** subsystem could not be initialized or the system failed to allocate
102533   ** the pInitMutex mutex. Return an error in either case.  */
102534   if( rc!=SQLITE_OK ){
102535     return rc;
102536   }
102537
102538   /* Do the rest of the initialization under the recursive mutex so
102539   ** that we will be able to handle recursive calls into
102540   ** sqlite3_initialize().  The recursive calls normally come through
102541   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
102542   ** recursive calls might also be possible.
102543   */
102544   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
102545   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
102546     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
102547     sqlite3GlobalConfig.inProgress = 1;
102548     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
102549     sqlite3RegisterGlobalFunctions();
102550     if( sqlite3GlobalConfig.isPCacheInit==0 ){
102551       rc = sqlite3PcacheInitialize();
102552     }
102553     if( rc==SQLITE_OK ){
102554       sqlite3GlobalConfig.isPCacheInit = 1;
102555       rc = sqlite3OsInit();
102556     }
102557     if( rc==SQLITE_OK ){
102558       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
102559           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
102560       sqlite3GlobalConfig.isInit = 1;
102561     }
102562     sqlite3GlobalConfig.inProgress = 0;
102563   }
102564   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
102565
102566   /* Go back under the static mutex and clean up the recursive
102567   ** mutex to prevent a resource leak.
102568   */
102569   sqlite3_mutex_enter(pMaster);
102570   sqlite3GlobalConfig.nRefInitMutex--;
102571   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
102572     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
102573     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
102574     sqlite3GlobalConfig.pInitMutex = 0;
102575   }
102576   sqlite3_mutex_leave(pMaster);
102577
102578   /* The following is just a sanity check to make sure SQLite has
102579   ** been compiled correctly.  It is important to run this code, but
102580   ** we don't want to run it too often and soak up CPU cycles for no
102581   ** reason.  So we run it once during initialization.
102582   */
102583 #ifndef NDEBUG
102584 #ifndef SQLITE_OMIT_FLOATING_POINT
102585   /* This section of code's only "output" is via assert() statements. */
102586   if ( rc==SQLITE_OK ){
102587     u64 x = (((u64)1)<<63)-1;
102588     double y;
102589     assert(sizeof(x)==8);
102590     assert(sizeof(x)==sizeof(y));
102591     memcpy(&y, &x, 8);
102592     assert( sqlite3IsNaN(y) );
102593   }
102594 #endif
102595 #endif
102596
102597   return rc;
102598 }
102599
102600 /*
102601 ** Undo the effects of sqlite3_initialize().  Must not be called while
102602 ** there are outstanding database connections or memory allocations or
102603 ** while any part of SQLite is otherwise in use in any thread.  This
102604 ** routine is not threadsafe.  But it is safe to invoke this routine
102605 ** on when SQLite is already shut down.  If SQLite is already shut down
102606 ** when this routine is invoked, then this routine is a harmless no-op.
102607 */
102608 SQLITE_API int sqlite3_shutdown(void){
102609   if( sqlite3GlobalConfig.isInit ){
102610     sqlite3_os_end();
102611     sqlite3_reset_auto_extension();
102612     sqlite3GlobalConfig.isInit = 0;
102613   }
102614   if( sqlite3GlobalConfig.isPCacheInit ){
102615     sqlite3PcacheShutdown();
102616     sqlite3GlobalConfig.isPCacheInit = 0;
102617   }
102618   if( sqlite3GlobalConfig.isMallocInit ){
102619     sqlite3MallocEnd();
102620     sqlite3GlobalConfig.isMallocInit = 0;
102621   }
102622   if( sqlite3GlobalConfig.isMutexInit ){
102623     sqlite3MutexEnd();
102624     sqlite3GlobalConfig.isMutexInit = 0;
102625   }
102626
102627   return SQLITE_OK;
102628 }
102629
102630 /*
102631 ** This API allows applications to modify the global configuration of
102632 ** the SQLite library at run-time.
102633 **
102634 ** This routine should only be called when there are no outstanding
102635 ** database connections or memory allocations.  This routine is not
102636 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
102637 ** behavior.
102638 */
102639 SQLITE_API int sqlite3_config(int op, ...){
102640   va_list ap;
102641   int rc = SQLITE_OK;
102642
102643   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
102644   ** the SQLite library is in use. */
102645   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
102646
102647   va_start(ap, op);
102648   switch( op ){
102649
102650     /* Mutex configuration options are only available in a threadsafe
102651     ** compile. 
102652     */
102653 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
102654     case SQLITE_CONFIG_SINGLETHREAD: {
102655       /* Disable all mutexing */
102656       sqlite3GlobalConfig.bCoreMutex = 0;
102657       sqlite3GlobalConfig.bFullMutex = 0;
102658       break;
102659     }
102660     case SQLITE_CONFIG_MULTITHREAD: {
102661       /* Disable mutexing of database connections */
102662       /* Enable mutexing of core data structures */
102663       sqlite3GlobalConfig.bCoreMutex = 1;
102664       sqlite3GlobalConfig.bFullMutex = 0;
102665       break;
102666     }
102667     case SQLITE_CONFIG_SERIALIZED: {
102668       /* Enable all mutexing */
102669       sqlite3GlobalConfig.bCoreMutex = 1;
102670       sqlite3GlobalConfig.bFullMutex = 1;
102671       break;
102672     }
102673     case SQLITE_CONFIG_MUTEX: {
102674       /* Specify an alternative mutex implementation */
102675       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
102676       break;
102677     }
102678     case SQLITE_CONFIG_GETMUTEX: {
102679       /* Retrieve the current mutex implementation */
102680       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
102681       break;
102682     }
102683 #endif
102684
102685
102686     case SQLITE_CONFIG_MALLOC: {
102687       /* Specify an alternative malloc implementation */
102688       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
102689       break;
102690     }
102691     case SQLITE_CONFIG_GETMALLOC: {
102692       /* Retrieve the current malloc() implementation */
102693       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
102694       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
102695       break;
102696     }
102697     case SQLITE_CONFIG_MEMSTATUS: {
102698       /* Enable or disable the malloc status collection */
102699       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
102700       break;
102701     }
102702     case SQLITE_CONFIG_SCRATCH: {
102703       /* Designate a buffer for scratch memory space */
102704       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
102705       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
102706       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
102707       break;
102708     }
102709     case SQLITE_CONFIG_PAGECACHE: {
102710       /* Designate a buffer for page cache memory space */
102711       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
102712       sqlite3GlobalConfig.szPage = va_arg(ap, int);
102713       sqlite3GlobalConfig.nPage = va_arg(ap, int);
102714       break;
102715     }
102716
102717     case SQLITE_CONFIG_PCACHE: {
102718       /* Specify an alternative page cache implementation */
102719       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
102720       break;
102721     }
102722
102723     case SQLITE_CONFIG_GETPCACHE: {
102724       if( sqlite3GlobalConfig.pcache.xInit==0 ){
102725         sqlite3PCacheSetDefault();
102726       }
102727       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
102728       break;
102729     }
102730
102731 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
102732     case SQLITE_CONFIG_HEAP: {
102733       /* Designate a buffer for heap memory space */
102734       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
102735       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
102736       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
102737
102738       if( sqlite3GlobalConfig.pHeap==0 ){
102739         /* If the heap pointer is NULL, then restore the malloc implementation
102740         ** back to NULL pointers too.  This will cause the malloc to go
102741         ** back to its default implementation when sqlite3_initialize() is
102742         ** run.
102743         */
102744         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
102745       }else{
102746         /* The heap pointer is not NULL, then install one of the
102747         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
102748         ** ENABLE_MEMSYS5 is defined, return an error.
102749         */
102750 #ifdef SQLITE_ENABLE_MEMSYS3
102751         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
102752 #endif
102753 #ifdef SQLITE_ENABLE_MEMSYS5
102754         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
102755 #endif
102756       }
102757       break;
102758     }
102759 #endif
102760
102761     case SQLITE_CONFIG_LOOKASIDE: {
102762       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
102763       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
102764       break;
102765     }
102766     
102767     /* Record a pointer to the logger funcction and its first argument.
102768     ** The default is NULL.  Logging is disabled if the function pointer is
102769     ** NULL.
102770     */
102771     case SQLITE_CONFIG_LOG: {
102772       /* MSVC is picky about pulling func ptrs from va lists.
102773       ** http://support.microsoft.com/kb/47961
102774       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
102775       */
102776       typedef void(*LOGFUNC_t)(void*,int,const char*);
102777       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
102778       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
102779       break;
102780     }
102781
102782     default: {
102783       rc = SQLITE_ERROR;
102784       break;
102785     }
102786   }
102787   va_end(ap);
102788   return rc;
102789 }
102790
102791 /*
102792 ** Set up the lookaside buffers for a database connection.
102793 ** Return SQLITE_OK on success.  
102794 ** If lookaside is already active, return SQLITE_BUSY.
102795 **
102796 ** The sz parameter is the number of bytes in each lookaside slot.
102797 ** The cnt parameter is the number of slots.  If pStart is NULL the
102798 ** space for the lookaside memory is obtained from sqlite3_malloc().
102799 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
102800 ** the lookaside memory.
102801 */
102802 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
102803   void *pStart;
102804   if( db->lookaside.nOut ){
102805     return SQLITE_BUSY;
102806   }
102807   /* Free any existing lookaside buffer for this handle before
102808   ** allocating a new one so we don't have to have space for 
102809   ** both at the same time.
102810   */
102811   if( db->lookaside.bMalloced ){
102812     sqlite3_free(db->lookaside.pStart);
102813   }
102814   /* The size of a lookaside slot needs to be larger than a pointer
102815   ** to be useful.
102816   */
102817   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
102818   if( cnt<0 ) cnt = 0;
102819   if( sz==0 || cnt==0 ){
102820     sz = 0;
102821     pStart = 0;
102822   }else if( pBuf==0 ){
102823     sz = ROUND8(sz);
102824     sqlite3BeginBenignMalloc();
102825     pStart = sqlite3Malloc( sz*cnt );
102826     sqlite3EndBenignMalloc();
102827   }else{
102828     sz = ROUNDDOWN8(sz);
102829     pStart = pBuf;
102830   }
102831   db->lookaside.pStart = pStart;
102832   db->lookaside.pFree = 0;
102833   db->lookaside.sz = (u16)sz;
102834   if( pStart ){
102835     int i;
102836     LookasideSlot *p;
102837     assert( sz > (int)sizeof(LookasideSlot*) );
102838     p = (LookasideSlot*)pStart;
102839     for(i=cnt-1; i>=0; i--){
102840       p->pNext = db->lookaside.pFree;
102841       db->lookaside.pFree = p;
102842       p = (LookasideSlot*)&((u8*)p)[sz];
102843     }
102844     db->lookaside.pEnd = p;
102845     db->lookaside.bEnabled = 1;
102846     db->lookaside.bMalloced = pBuf==0 ?1:0;
102847   }else{
102848     db->lookaside.pEnd = 0;
102849     db->lookaside.bEnabled = 0;
102850     db->lookaside.bMalloced = 0;
102851   }
102852   return SQLITE_OK;
102853 }
102854
102855 /*
102856 ** Return the mutex associated with a database connection.
102857 */
102858 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
102859   return db->mutex;
102860 }
102861
102862 /*
102863 ** Configuration settings for an individual database connection
102864 */
102865 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
102866   va_list ap;
102867   int rc;
102868   va_start(ap, op);
102869   switch( op ){
102870     case SQLITE_DBCONFIG_LOOKASIDE: {
102871       void *pBuf = va_arg(ap, void*);
102872       int sz = va_arg(ap, int);
102873       int cnt = va_arg(ap, int);
102874       rc = setupLookaside(db, pBuf, sz, cnt);
102875       break;
102876     }
102877     default: {
102878       rc = SQLITE_ERROR;
102879       break;
102880     }
102881   }
102882   va_end(ap);
102883   return rc;
102884 }
102885
102886
102887 /*
102888 ** Return true if the buffer z[0..n-1] contains all spaces.
102889 */
102890 static int allSpaces(const char *z, int n){
102891   while( n>0 && z[n-1]==' ' ){ n--; }
102892   return n==0;
102893 }
102894
102895 /*
102896 ** This is the default collating function named "BINARY" which is always
102897 ** available.
102898 **
102899 ** If the padFlag argument is not NULL then space padding at the end
102900 ** of strings is ignored.  This implements the RTRIM collation.
102901 */
102902 static int binCollFunc(
102903   void *padFlag,
102904   int nKey1, const void *pKey1,
102905   int nKey2, const void *pKey2
102906 ){
102907   int rc, n;
102908   n = nKey1<nKey2 ? nKey1 : nKey2;
102909   rc = memcmp(pKey1, pKey2, n);
102910   if( rc==0 ){
102911     if( padFlag
102912      && allSpaces(((char*)pKey1)+n, nKey1-n)
102913      && allSpaces(((char*)pKey2)+n, nKey2-n)
102914     ){
102915       /* Leave rc unchanged at 0 */
102916     }else{
102917       rc = nKey1 - nKey2;
102918     }
102919   }
102920   return rc;
102921 }
102922
102923 /*
102924 ** Another built-in collating sequence: NOCASE. 
102925 **
102926 ** This collating sequence is intended to be used for "case independant
102927 ** comparison". SQLite's knowledge of upper and lower case equivalents
102928 ** extends only to the 26 characters used in the English language.
102929 **
102930 ** At the moment there is only a UTF-8 implementation.
102931 */
102932 static int nocaseCollatingFunc(
102933   void *NotUsed,
102934   int nKey1, const void *pKey1,
102935   int nKey2, const void *pKey2
102936 ){
102937   int r = sqlite3StrNICmp(
102938       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
102939   UNUSED_PARAMETER(NotUsed);
102940   if( 0==r ){
102941     r = nKey1-nKey2;
102942   }
102943   return r;
102944 }
102945
102946 /*
102947 ** Return the ROWID of the most recent insert
102948 */
102949 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
102950   return db->lastRowid;
102951 }
102952
102953 /*
102954 ** Return the number of changes in the most recent call to sqlite3_exec().
102955 */
102956 SQLITE_API int sqlite3_changes(sqlite3 *db){
102957   return db->nChange;
102958 }
102959
102960 /*
102961 ** Return the number of changes since the database handle was opened.
102962 */
102963 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
102964   return db->nTotalChange;
102965 }
102966
102967 /*
102968 ** Close all open savepoints. This function only manipulates fields of the
102969 ** database handle object, it does not close any savepoints that may be open
102970 ** at the b-tree/pager level.
102971 */
102972 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
102973   while( db->pSavepoint ){
102974     Savepoint *pTmp = db->pSavepoint;
102975     db->pSavepoint = pTmp->pNext;
102976     sqlite3DbFree(db, pTmp);
102977   }
102978   db->nSavepoint = 0;
102979   db->nStatement = 0;
102980   db->isTransactionSavepoint = 0;
102981 }
102982
102983 /*
102984 ** Close an existing SQLite database
102985 */
102986 SQLITE_API int sqlite3_close(sqlite3 *db){
102987   HashElem *i;
102988   int j;
102989
102990   if( !db ){
102991     return SQLITE_OK;
102992   }
102993   if( !sqlite3SafetyCheckSickOrOk(db) ){
102994     return SQLITE_MISUSE_BKPT;
102995   }
102996   sqlite3_mutex_enter(db->mutex);
102997
102998   sqlite3ResetInternalSchema(db, 0);
102999
103000   /* If a transaction is open, the ResetInternalSchema() call above
103001   ** will not have called the xDisconnect() method on any virtual
103002   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
103003   ** call will do so. We need to do this before the check for active
103004   ** SQL statements below, as the v-table implementation may be storing
103005   ** some prepared statements internally.
103006   */
103007   sqlite3VtabRollback(db);
103008
103009   /* If there are any outstanding VMs, return SQLITE_BUSY. */
103010   if( db->pVdbe ){
103011     sqlite3Error(db, SQLITE_BUSY, 
103012         "unable to close due to unfinalised statements");
103013     sqlite3_mutex_leave(db->mutex);
103014     return SQLITE_BUSY;
103015   }
103016   assert( sqlite3SafetyCheckSickOrOk(db) );
103017
103018   for(j=0; j<db->nDb; j++){
103019     Btree *pBt = db->aDb[j].pBt;
103020     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
103021       sqlite3Error(db, SQLITE_BUSY, 
103022           "unable to close due to unfinished backup operation");
103023       sqlite3_mutex_leave(db->mutex);
103024       return SQLITE_BUSY;
103025     }
103026   }
103027
103028   /* Free any outstanding Savepoint structures. */
103029   sqlite3CloseSavepoints(db);
103030
103031   for(j=0; j<db->nDb; j++){
103032     struct Db *pDb = &db->aDb[j];
103033     if( pDb->pBt ){
103034       sqlite3BtreeClose(pDb->pBt);
103035       pDb->pBt = 0;
103036       if( j!=1 ){
103037         pDb->pSchema = 0;
103038       }
103039     }
103040   }
103041   sqlite3ResetInternalSchema(db, 0);
103042
103043   /* Tell the code in notify.c that the connection no longer holds any
103044   ** locks and does not require any further unlock-notify callbacks.
103045   */
103046   sqlite3ConnectionClosed(db);
103047
103048   assert( db->nDb<=2 );
103049   assert( db->aDb==db->aDbStatic );
103050   for(j=0; j<ArraySize(db->aFunc.a); j++){
103051     FuncDef *pNext, *pHash, *p;
103052     for(p=db->aFunc.a[j]; p; p=pHash){
103053       pHash = p->pHash;
103054       while( p ){
103055         pNext = p->pNext;
103056         sqlite3DbFree(db, p);
103057         p = pNext;
103058       }
103059     }
103060   }
103061   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
103062     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
103063     /* Invoke any destructors registered for collation sequence user data. */
103064     for(j=0; j<3; j++){
103065       if( pColl[j].xDel ){
103066         pColl[j].xDel(pColl[j].pUser);
103067       }
103068     }
103069     sqlite3DbFree(db, pColl);
103070   }
103071   sqlite3HashClear(&db->aCollSeq);
103072 #ifndef SQLITE_OMIT_VIRTUALTABLE
103073   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
103074     Module *pMod = (Module *)sqliteHashData(i);
103075     if( pMod->xDestroy ){
103076       pMod->xDestroy(pMod->pAux);
103077     }
103078     sqlite3DbFree(db, pMod);
103079   }
103080   sqlite3HashClear(&db->aModule);
103081 #endif
103082
103083   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
103084   if( db->pErr ){
103085     sqlite3ValueFree(db->pErr);
103086   }
103087   sqlite3CloseExtensions(db);
103088
103089   db->magic = SQLITE_MAGIC_ERROR;
103090
103091   /* The temp-database schema is allocated differently from the other schema
103092   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
103093   ** So it needs to be freed here. Todo: Why not roll the temp schema into
103094   ** the same sqliteMalloc() as the one that allocates the database 
103095   ** structure?
103096   */
103097   sqlite3DbFree(db, db->aDb[1].pSchema);
103098   sqlite3_mutex_leave(db->mutex);
103099   db->magic = SQLITE_MAGIC_CLOSED;
103100   sqlite3_mutex_free(db->mutex);
103101   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
103102   if( db->lookaside.bMalloced ){
103103     sqlite3_free(db->lookaside.pStart);
103104   }
103105   sqlite3_free(db);
103106   return SQLITE_OK;
103107 }
103108
103109 /*
103110 ** Rollback all database files.
103111 */
103112 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
103113   int i;
103114   int inTrans = 0;
103115   assert( sqlite3_mutex_held(db->mutex) );
103116   sqlite3BeginBenignMalloc();
103117   for(i=0; i<db->nDb; i++){
103118     if( db->aDb[i].pBt ){
103119       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
103120         inTrans = 1;
103121       }
103122       sqlite3BtreeRollback(db->aDb[i].pBt);
103123       db->aDb[i].inTrans = 0;
103124     }
103125   }
103126   sqlite3VtabRollback(db);
103127   sqlite3EndBenignMalloc();
103128
103129   if( db->flags&SQLITE_InternChanges ){
103130     sqlite3ExpirePreparedStatements(db);
103131     sqlite3ResetInternalSchema(db, 0);
103132   }
103133
103134   /* Any deferred constraint violations have now been resolved. */
103135   db->nDeferredCons = 0;
103136
103137   /* If one has been configured, invoke the rollback-hook callback */
103138   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
103139     db->xRollbackCallback(db->pRollbackArg);
103140   }
103141 }
103142
103143 /*
103144 ** Return a static string that describes the kind of error specified in the
103145 ** argument.
103146 */
103147 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
103148   static const char* const aMsg[] = {
103149     /* SQLITE_OK          */ "not an error",
103150     /* SQLITE_ERROR       */ "SQL logic error or missing database",
103151     /* SQLITE_INTERNAL    */ 0,
103152     /* SQLITE_PERM        */ "access permission denied",
103153     /* SQLITE_ABORT       */ "callback requested query abort",
103154     /* SQLITE_BUSY        */ "database is locked",
103155     /* SQLITE_LOCKED      */ "database table is locked",
103156     /* SQLITE_NOMEM       */ "out of memory",
103157     /* SQLITE_READONLY    */ "attempt to write a readonly database",
103158     /* SQLITE_INTERRUPT   */ "interrupted",
103159     /* SQLITE_IOERR       */ "disk I/O error",
103160     /* SQLITE_CORRUPT     */ "database disk image is malformed",
103161     /* SQLITE_NOTFOUND    */ 0,
103162     /* SQLITE_FULL        */ "database or disk is full",
103163     /* SQLITE_CANTOPEN    */ "unable to open database file",
103164     /* SQLITE_PROTOCOL    */ "locking protocol",
103165     /* SQLITE_EMPTY       */ "table contains no data",
103166     /* SQLITE_SCHEMA      */ "database schema has changed",
103167     /* SQLITE_TOOBIG      */ "string or blob too big",
103168     /* SQLITE_CONSTRAINT  */ "constraint failed",
103169     /* SQLITE_MISMATCH    */ "datatype mismatch",
103170     /* SQLITE_MISUSE      */ "library routine called out of sequence",
103171     /* SQLITE_NOLFS       */ "large file support is disabled",
103172     /* SQLITE_AUTH        */ "authorization denied",
103173     /* SQLITE_FORMAT      */ "auxiliary database format error",
103174     /* SQLITE_RANGE       */ "bind or column index out of range",
103175     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
103176   };
103177   rc &= 0xff;
103178   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
103179     return aMsg[rc];
103180   }else{
103181     return "unknown error";
103182   }
103183 }
103184
103185 /*
103186 ** This routine implements a busy callback that sleeps and tries
103187 ** again until a timeout value is reached.  The timeout value is
103188 ** an integer number of milliseconds passed in as the first
103189 ** argument.
103190 */
103191 static int sqliteDefaultBusyCallback(
103192  void *ptr,               /* Database connection */
103193  int count                /* Number of times table has been busy */
103194 ){
103195 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
103196   static const u8 delays[] =
103197      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
103198   static const u8 totals[] =
103199      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
103200 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
103201   sqlite3 *db = (sqlite3 *)ptr;
103202   int timeout = db->busyTimeout;
103203   int delay, prior;
103204
103205   assert( count>=0 );
103206   if( count < NDELAY ){
103207     delay = delays[count];
103208     prior = totals[count];
103209   }else{
103210     delay = delays[NDELAY-1];
103211     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
103212   }
103213   if( prior + delay > timeout ){
103214     delay = timeout - prior;
103215     if( delay<=0 ) return 0;
103216   }
103217   sqlite3OsSleep(db->pVfs, delay*1000);
103218   return 1;
103219 #else
103220   sqlite3 *db = (sqlite3 *)ptr;
103221   int timeout = ((sqlite3 *)ptr)->busyTimeout;
103222   if( (count+1)*1000 > timeout ){
103223     return 0;
103224   }
103225   sqlite3OsSleep(db->pVfs, 1000000);
103226   return 1;
103227 #endif
103228 }
103229
103230 /*
103231 ** Invoke the given busy handler.
103232 **
103233 ** This routine is called when an operation failed with a lock.
103234 ** If this routine returns non-zero, the lock is retried.  If it
103235 ** returns 0, the operation aborts with an SQLITE_BUSY error.
103236 */
103237 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
103238   int rc;
103239   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
103240   rc = p->xFunc(p->pArg, p->nBusy);
103241   if( rc==0 ){
103242     p->nBusy = -1;
103243   }else{
103244     p->nBusy++;
103245   }
103246   return rc; 
103247 }
103248
103249 /*
103250 ** This routine sets the busy callback for an Sqlite database to the
103251 ** given callback function with the given argument.
103252 */
103253 SQLITE_API int sqlite3_busy_handler(
103254   sqlite3 *db,
103255   int (*xBusy)(void*,int),
103256   void *pArg
103257 ){
103258   sqlite3_mutex_enter(db->mutex);
103259   db->busyHandler.xFunc = xBusy;
103260   db->busyHandler.pArg = pArg;
103261   db->busyHandler.nBusy = 0;
103262   sqlite3_mutex_leave(db->mutex);
103263   return SQLITE_OK;
103264 }
103265
103266 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
103267 /*
103268 ** This routine sets the progress callback for an Sqlite database to the
103269 ** given callback function with the given argument. The progress callback will
103270 ** be invoked every nOps opcodes.
103271 */
103272 SQLITE_API void sqlite3_progress_handler(
103273   sqlite3 *db, 
103274   int nOps,
103275   int (*xProgress)(void*), 
103276   void *pArg
103277 ){
103278   sqlite3_mutex_enter(db->mutex);
103279   if( nOps>0 ){
103280     db->xProgress = xProgress;
103281     db->nProgressOps = nOps;
103282     db->pProgressArg = pArg;
103283   }else{
103284     db->xProgress = 0;
103285     db->nProgressOps = 0;
103286     db->pProgressArg = 0;
103287   }
103288   sqlite3_mutex_leave(db->mutex);
103289 }
103290 #endif
103291
103292
103293 /*
103294 ** This routine installs a default busy handler that waits for the
103295 ** specified number of milliseconds before returning 0.
103296 */
103297 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
103298   if( ms>0 ){
103299     db->busyTimeout = ms;
103300     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
103301   }else{
103302     sqlite3_busy_handler(db, 0, 0);
103303   }
103304   return SQLITE_OK;
103305 }
103306
103307 /*
103308 ** Cause any pending operation to stop at its earliest opportunity.
103309 */
103310 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
103311   db->u1.isInterrupted = 1;
103312 }
103313
103314
103315 /*
103316 ** This function is exactly the same as sqlite3_create_function(), except
103317 ** that it is designed to be called by internal code. The difference is
103318 ** that if a malloc() fails in sqlite3_create_function(), an error code
103319 ** is returned and the mallocFailed flag cleared. 
103320 */
103321 SQLITE_PRIVATE int sqlite3CreateFunc(
103322   sqlite3 *db,
103323   const char *zFunctionName,
103324   int nArg,
103325   int enc,
103326   void *pUserData,
103327   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
103328   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
103329   void (*xFinal)(sqlite3_context*)
103330 ){
103331   FuncDef *p;
103332   int nName;
103333
103334   assert( sqlite3_mutex_held(db->mutex) );
103335   if( zFunctionName==0 ||
103336       (xFunc && (xFinal || xStep)) || 
103337       (!xFunc && (xFinal && !xStep)) ||
103338       (!xFunc && (!xFinal && xStep)) ||
103339       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
103340       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
103341     return SQLITE_MISUSE_BKPT;
103342   }
103343   
103344 #ifndef SQLITE_OMIT_UTF16
103345   /* If SQLITE_UTF16 is specified as the encoding type, transform this
103346   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
103347   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
103348   **
103349   ** If SQLITE_ANY is specified, add three versions of the function
103350   ** to the hash table.
103351   */
103352   if( enc==SQLITE_UTF16 ){
103353     enc = SQLITE_UTF16NATIVE;
103354   }else if( enc==SQLITE_ANY ){
103355     int rc;
103356     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
103357          pUserData, xFunc, xStep, xFinal);
103358     if( rc==SQLITE_OK ){
103359       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
103360           pUserData, xFunc, xStep, xFinal);
103361     }
103362     if( rc!=SQLITE_OK ){
103363       return rc;
103364     }
103365     enc = SQLITE_UTF16BE;
103366   }
103367 #else
103368   enc = SQLITE_UTF8;
103369 #endif
103370   
103371   /* Check if an existing function is being overridden or deleted. If so,
103372   ** and there are active VMs, then return SQLITE_BUSY. If a function
103373   ** is being overridden/deleted but there are no active VMs, allow the
103374   ** operation to continue but invalidate all precompiled statements.
103375   */
103376   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
103377   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
103378     if( db->activeVdbeCnt ){
103379       sqlite3Error(db, SQLITE_BUSY, 
103380         "unable to delete/modify user-function due to active statements");
103381       assert( !db->mallocFailed );
103382       return SQLITE_BUSY;
103383     }else{
103384       sqlite3ExpirePreparedStatements(db);
103385     }
103386   }
103387
103388   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
103389   assert(p || db->mallocFailed);
103390   if( !p ){
103391     return SQLITE_NOMEM;
103392   }
103393   p->flags = 0;
103394   p->xFunc = xFunc;
103395   p->xStep = xStep;
103396   p->xFinalize = xFinal;
103397   p->pUserData = pUserData;
103398   p->nArg = (u16)nArg;
103399   return SQLITE_OK;
103400 }
103401
103402 /*
103403 ** Create new user functions.
103404 */
103405 SQLITE_API int sqlite3_create_function(
103406   sqlite3 *db,
103407   const char *zFunctionName,
103408   int nArg,
103409   int enc,
103410   void *p,
103411   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
103412   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
103413   void (*xFinal)(sqlite3_context*)
103414 ){
103415   int rc;
103416   sqlite3_mutex_enter(db->mutex);
103417   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
103418   rc = sqlite3ApiExit(db, rc);
103419   sqlite3_mutex_leave(db->mutex);
103420   return rc;
103421 }
103422
103423 #ifndef SQLITE_OMIT_UTF16
103424 SQLITE_API int sqlite3_create_function16(
103425   sqlite3 *db,
103426   const void *zFunctionName,
103427   int nArg,
103428   int eTextRep,
103429   void *p,
103430   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
103431   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
103432   void (*xFinal)(sqlite3_context*)
103433 ){
103434   int rc;
103435   char *zFunc8;
103436   sqlite3_mutex_enter(db->mutex);
103437   assert( !db->mallocFailed );
103438   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
103439   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
103440   sqlite3DbFree(db, zFunc8);
103441   rc = sqlite3ApiExit(db, rc);
103442   sqlite3_mutex_leave(db->mutex);
103443   return rc;
103444 }
103445 #endif
103446
103447
103448 /*
103449 ** Declare that a function has been overloaded by a virtual table.
103450 **
103451 ** If the function already exists as a regular global function, then
103452 ** this routine is a no-op.  If the function does not exist, then create
103453 ** a new one that always throws a run-time error.  
103454 **
103455 ** When virtual tables intend to provide an overloaded function, they
103456 ** should call this routine to make sure the global function exists.
103457 ** A global function must exist in order for name resolution to work
103458 ** properly.
103459 */
103460 SQLITE_API int sqlite3_overload_function(
103461   sqlite3 *db,
103462   const char *zName,
103463   int nArg
103464 ){
103465   int nName = sqlite3Strlen30(zName);
103466   int rc;
103467   sqlite3_mutex_enter(db->mutex);
103468   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
103469     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
103470                       0, sqlite3InvalidFunction, 0, 0);
103471   }
103472   rc = sqlite3ApiExit(db, SQLITE_OK);
103473   sqlite3_mutex_leave(db->mutex);
103474   return rc;
103475 }
103476
103477 #ifndef SQLITE_OMIT_TRACE
103478 /*
103479 ** Register a trace function.  The pArg from the previously registered trace
103480 ** is returned.  
103481 **
103482 ** A NULL trace function means that no tracing is executes.  A non-NULL
103483 ** trace is a pointer to a function that is invoked at the start of each
103484 ** SQL statement.
103485 */
103486 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
103487   void *pOld;
103488   sqlite3_mutex_enter(db->mutex);
103489   pOld = db->pTraceArg;
103490   db->xTrace = xTrace;
103491   db->pTraceArg = pArg;
103492   sqlite3_mutex_leave(db->mutex);
103493   return pOld;
103494 }
103495 /*
103496 ** Register a profile function.  The pArg from the previously registered 
103497 ** profile function is returned.  
103498 **
103499 ** A NULL profile function means that no profiling is executes.  A non-NULL
103500 ** profile is a pointer to a function that is invoked at the conclusion of
103501 ** each SQL statement that is run.
103502 */
103503 SQLITE_API void *sqlite3_profile(
103504   sqlite3 *db,
103505   void (*xProfile)(void*,const char*,sqlite_uint64),
103506   void *pArg
103507 ){
103508   void *pOld;
103509   sqlite3_mutex_enter(db->mutex);
103510   pOld = db->pProfileArg;
103511   db->xProfile = xProfile;
103512   db->pProfileArg = pArg;
103513   sqlite3_mutex_leave(db->mutex);
103514   return pOld;
103515 }
103516 #endif /* SQLITE_OMIT_TRACE */
103517
103518 /*** EXPERIMENTAL ***
103519 **
103520 ** Register a function to be invoked when a transaction comments.
103521 ** If the invoked function returns non-zero, then the commit becomes a
103522 ** rollback.
103523 */
103524 SQLITE_API void *sqlite3_commit_hook(
103525   sqlite3 *db,              /* Attach the hook to this database */
103526   int (*xCallback)(void*),  /* Function to invoke on each commit */
103527   void *pArg                /* Argument to the function */
103528 ){
103529   void *pOld;
103530   sqlite3_mutex_enter(db->mutex);
103531   pOld = db->pCommitArg;
103532   db->xCommitCallback = xCallback;
103533   db->pCommitArg = pArg;
103534   sqlite3_mutex_leave(db->mutex);
103535   return pOld;
103536 }
103537
103538 /*
103539 ** Register a callback to be invoked each time a row is updated,
103540 ** inserted or deleted using this database connection.
103541 */
103542 SQLITE_API void *sqlite3_update_hook(
103543   sqlite3 *db,              /* Attach the hook to this database */
103544   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
103545   void *pArg                /* Argument to the function */
103546 ){
103547   void *pRet;
103548   sqlite3_mutex_enter(db->mutex);
103549   pRet = db->pUpdateArg;
103550   db->xUpdateCallback = xCallback;
103551   db->pUpdateArg = pArg;
103552   sqlite3_mutex_leave(db->mutex);
103553   return pRet;
103554 }
103555
103556 /*
103557 ** Register a callback to be invoked each time a transaction is rolled
103558 ** back by this database connection.
103559 */
103560 SQLITE_API void *sqlite3_rollback_hook(
103561   sqlite3 *db,              /* Attach the hook to this database */
103562   void (*xCallback)(void*), /* Callback function */
103563   void *pArg                /* Argument to the function */
103564 ){
103565   void *pRet;
103566   sqlite3_mutex_enter(db->mutex);
103567   pRet = db->pRollbackArg;
103568   db->xRollbackCallback = xCallback;
103569   db->pRollbackArg = pArg;
103570   sqlite3_mutex_leave(db->mutex);
103571   return pRet;
103572 }
103573
103574 #ifndef SQLITE_OMIT_WAL
103575 /*
103576 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
103577 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
103578 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
103579 ** wal_autocheckpoint()).
103580 */ 
103581 SQLITE_PRIVATE int sqlite3WalDefaultHook(
103582   void *pClientData,     /* Argument */
103583   sqlite3 *db,           /* Connection */
103584   const char *zDb,       /* Database */
103585   int nFrame             /* Size of WAL */
103586 ){
103587   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
103588     sqlite3BeginBenignMalloc();
103589     sqlite3_wal_checkpoint(db, zDb);
103590     sqlite3EndBenignMalloc();
103591   }
103592   return SQLITE_OK;
103593 }
103594 #endif /* SQLITE_OMIT_WAL */
103595
103596 /*
103597 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
103598 ** a database after committing a transaction if there are nFrame or
103599 ** more frames in the log file. Passing zero or a negative value as the
103600 ** nFrame parameter disables automatic checkpoints entirely.
103601 **
103602 ** The callback registered by this function replaces any existing callback
103603 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
103604 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
103605 ** configured by this function.
103606 */
103607 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
103608 #ifndef SQLITE_OMIT_WAL
103609   if( nFrame>0 ){
103610     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
103611   }else{
103612     sqlite3_wal_hook(db, 0, 0);
103613   }
103614 #endif
103615   return SQLITE_OK;
103616 }
103617
103618 /*
103619 ** Register a callback to be invoked each time a transaction is written
103620 ** into the write-ahead-log by this database connection.
103621 */
103622 SQLITE_API void *sqlite3_wal_hook(
103623   sqlite3 *db,                    /* Attach the hook to this db handle */
103624   int(*xCallback)(void *, sqlite3*, const char*, int),
103625   void *pArg                      /* First argument passed to xCallback() */
103626 ){
103627 #ifndef SQLITE_OMIT_WAL
103628   void *pRet;
103629   sqlite3_mutex_enter(db->mutex);
103630   pRet = db->pWalArg;
103631   db->xWalCallback = xCallback;
103632   db->pWalArg = pArg;
103633   sqlite3_mutex_leave(db->mutex);
103634   return pRet;
103635 #else
103636   return 0;
103637 #endif
103638 }
103639
103640
103641 /*
103642 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
103643 ** to contains a zero-length string, all attached databases are 
103644 ** checkpointed.
103645 */
103646 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
103647 #ifdef SQLITE_OMIT_WAL
103648   return SQLITE_OK;
103649 #else
103650   int rc;                         /* Return code */
103651   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
103652
103653   sqlite3_mutex_enter(db->mutex);
103654   if( zDb && zDb[0] ){
103655     iDb = sqlite3FindDbName(db, zDb);
103656   }
103657   if( iDb<0 ){
103658     rc = SQLITE_ERROR;
103659     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
103660   }else{
103661     rc = sqlite3Checkpoint(db, iDb);
103662     sqlite3Error(db, rc, 0);
103663   }
103664   rc = sqlite3ApiExit(db, rc);
103665   sqlite3_mutex_leave(db->mutex);
103666   return rc;
103667 #endif
103668 }
103669
103670 #ifndef SQLITE_OMIT_WAL
103671 /*
103672 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
103673 ** not currently open in WAL mode.
103674 **
103675 ** If a transaction is open on the database being checkpointed, this 
103676 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
103677 ** an error occurs while running the checkpoint, an SQLite error code is 
103678 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
103679 **
103680 ** The mutex on database handle db should be held by the caller. The mutex
103681 ** associated with the specific b-tree being checkpointed is taken by
103682 ** this function while the checkpoint is running.
103683 **
103684 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
103685 ** checkpointed. If an error is encountered it is returned immediately -
103686 ** no attempt is made to checkpoint any remaining databases.
103687 */
103688 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
103689   int rc = SQLITE_OK;             /* Return code */
103690   int i;                          /* Used to iterate through attached dbs */
103691
103692   assert( sqlite3_mutex_held(db->mutex) );
103693
103694   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
103695     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
103696       Btree *pBt = db->aDb[i].pBt;
103697       if( pBt ){
103698         if( sqlite3BtreeIsInReadTrans(pBt) ){
103699           rc = SQLITE_LOCKED;
103700         }else{
103701           sqlite3BtreeEnter(pBt);
103702           rc = sqlite3PagerCheckpoint(sqlite3BtreePager(pBt));
103703           sqlite3BtreeLeave(pBt);
103704         }
103705       }
103706     }
103707   }
103708
103709   return rc;
103710 }
103711 #endif /* SQLITE_OMIT_WAL */
103712
103713 /*
103714 ** This function returns true if main-memory should be used instead of
103715 ** a temporary file for transient pager files and statement journals.
103716 ** The value returned depends on the value of db->temp_store (runtime
103717 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
103718 ** following table describes the relationship between these two values
103719 ** and this functions return value.
103720 **
103721 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
103722 **   -----------------     --------------     ------------------------------
103723 **   0                     any                file      (return 0)
103724 **   1                     1                  file      (return 0)
103725 **   1                     2                  memory    (return 1)
103726 **   1                     0                  file      (return 0)
103727 **   2                     1                  file      (return 0)
103728 **   2                     2                  memory    (return 1)
103729 **   2                     0                  memory    (return 1)
103730 **   3                     any                memory    (return 1)
103731 */
103732 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
103733 #if SQLITE_TEMP_STORE==1
103734   return ( db->temp_store==2 );
103735 #endif
103736 #if SQLITE_TEMP_STORE==2
103737   return ( db->temp_store!=1 );
103738 #endif
103739 #if SQLITE_TEMP_STORE==3
103740   return 1;
103741 #endif
103742 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
103743   return 0;
103744 #endif
103745 }
103746
103747 /*
103748 ** This routine is called to create a connection to a database BTree
103749 ** driver.  If zFilename is the name of a file, then that file is
103750 ** opened and used.  If zFilename is the magic name ":memory:" then
103751 ** the database is stored in memory (and is thus forgotten as soon as
103752 ** the connection is closed.)  If zFilename is NULL then the database
103753 ** is a "virtual" database for transient use only and is deleted as
103754 ** soon as the connection is closed.
103755 **
103756 ** A virtual database can be either a disk file (that is automatically
103757 ** deleted when the file is closed) or it an be held entirely in memory.
103758 ** The sqlite3TempInMemory() function is used to determine which.
103759 */
103760 SQLITE_PRIVATE int sqlite3BtreeFactory(
103761   sqlite3 *db,              /* Main database when opening aux otherwise 0 */
103762   const char *zFilename,    /* Name of the file containing the BTree database */
103763   int omitJournal,          /* if TRUE then do not journal this file */
103764   int nCache,               /* How many pages in the page cache */
103765   int vfsFlags,             /* Flags passed through to vfsOpen */
103766   Btree **ppBtree           /* Pointer to new Btree object written here */
103767 ){
103768   int btFlags = 0;
103769   int rc;
103770   
103771   assert( sqlite3_mutex_held(db->mutex) );
103772   assert( ppBtree != 0);
103773   if( omitJournal ){
103774     btFlags |= BTREE_OMIT_JOURNAL;
103775   }
103776   if( db->flags & SQLITE_NoReadlock ){
103777     btFlags |= BTREE_NO_READLOCK;
103778   }
103779 #ifndef SQLITE_OMIT_MEMORYDB
103780   if( zFilename==0 && sqlite3TempInMemory(db) ){
103781     zFilename = ":memory:";
103782   }
103783 #endif
103784
103785   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
103786     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
103787   }
103788   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
103789
103790   /* If the B-Tree was successfully opened, set the pager-cache size to the
103791   ** default value. Except, if the call to BtreeOpen() returned a handle
103792   ** open on an existing shared pager-cache, do not change the pager-cache 
103793   ** size.
103794   */
103795   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
103796     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
103797   }
103798   return rc;
103799 }
103800
103801 /*
103802 ** Return UTF-8 encoded English language explanation of the most recent
103803 ** error.
103804 */
103805 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
103806   const char *z;
103807   if( !db ){
103808     return sqlite3ErrStr(SQLITE_NOMEM);
103809   }
103810   if( !sqlite3SafetyCheckSickOrOk(db) ){
103811     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
103812   }
103813   sqlite3_mutex_enter(db->mutex);
103814   if( db->mallocFailed ){
103815     z = sqlite3ErrStr(SQLITE_NOMEM);
103816   }else{
103817     z = (char*)sqlite3_value_text(db->pErr);
103818     assert( !db->mallocFailed );
103819     if( z==0 ){
103820       z = sqlite3ErrStr(db->errCode);
103821     }
103822   }
103823   sqlite3_mutex_leave(db->mutex);
103824   return z;
103825 }
103826
103827 #ifndef SQLITE_OMIT_UTF16
103828 /*
103829 ** Return UTF-16 encoded English language explanation of the most recent
103830 ** error.
103831 */
103832 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
103833   static const u16 outOfMem[] = {
103834     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
103835   };
103836   static const u16 misuse[] = {
103837     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
103838     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
103839     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
103840     'o', 'u', 't', ' ', 
103841     'o', 'f', ' ', 
103842     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
103843   };
103844
103845   const void *z;
103846   if( !db ){
103847     return (void *)outOfMem;
103848   }
103849   if( !sqlite3SafetyCheckSickOrOk(db) ){
103850     return (void *)misuse;
103851   }
103852   sqlite3_mutex_enter(db->mutex);
103853   if( db->mallocFailed ){
103854     z = (void *)outOfMem;
103855   }else{
103856     z = sqlite3_value_text16(db->pErr);
103857     if( z==0 ){
103858       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
103859            SQLITE_UTF8, SQLITE_STATIC);
103860       z = sqlite3_value_text16(db->pErr);
103861     }
103862     /* A malloc() may have failed within the call to sqlite3_value_text16()
103863     ** above. If this is the case, then the db->mallocFailed flag needs to
103864     ** be cleared before returning. Do this directly, instead of via
103865     ** sqlite3ApiExit(), to avoid setting the database handle error message.
103866     */
103867     db->mallocFailed = 0;
103868   }
103869   sqlite3_mutex_leave(db->mutex);
103870   return z;
103871 }
103872 #endif /* SQLITE_OMIT_UTF16 */
103873
103874 /*
103875 ** Return the most recent error code generated by an SQLite routine. If NULL is
103876 ** passed to this function, we assume a malloc() failed during sqlite3_open().
103877 */
103878 SQLITE_API int sqlite3_errcode(sqlite3 *db){
103879   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103880     return SQLITE_MISUSE_BKPT;
103881   }
103882   if( !db || db->mallocFailed ){
103883     return SQLITE_NOMEM;
103884   }
103885   return db->errCode & db->errMask;
103886 }
103887 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
103888   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103889     return SQLITE_MISUSE_BKPT;
103890   }
103891   if( !db || db->mallocFailed ){
103892     return SQLITE_NOMEM;
103893   }
103894   return db->errCode;
103895 }
103896
103897 /*
103898 ** Create a new collating function for database "db".  The name is zName
103899 ** and the encoding is enc.
103900 */
103901 static int createCollation(
103902   sqlite3* db,
103903   const char *zName, 
103904   u8 enc,
103905   u8 collType,
103906   void* pCtx,
103907   int(*xCompare)(void*,int,const void*,int,const void*),
103908   void(*xDel)(void*)
103909 ){
103910   CollSeq *pColl;
103911   int enc2;
103912   int nName = sqlite3Strlen30(zName);
103913   
103914   assert( sqlite3_mutex_held(db->mutex) );
103915
103916   /* If SQLITE_UTF16 is specified as the encoding type, transform this
103917   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
103918   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
103919   */
103920   enc2 = enc;
103921   testcase( enc2==SQLITE_UTF16 );
103922   testcase( enc2==SQLITE_UTF16_ALIGNED );
103923   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
103924     enc2 = SQLITE_UTF16NATIVE;
103925   }
103926   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
103927     return SQLITE_MISUSE_BKPT;
103928   }
103929
103930   /* Check if this call is removing or replacing an existing collation 
103931   ** sequence. If so, and there are active VMs, return busy. If there
103932   ** are no active VMs, invalidate any pre-compiled statements.
103933   */
103934   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
103935   if( pColl && pColl->xCmp ){
103936     if( db->activeVdbeCnt ){
103937       sqlite3Error(db, SQLITE_BUSY, 
103938         "unable to delete/modify collation sequence due to active statements");
103939       return SQLITE_BUSY;
103940     }
103941     sqlite3ExpirePreparedStatements(db);
103942
103943     /* If collation sequence pColl was created directly by a call to
103944     ** sqlite3_create_collation, and not generated by synthCollSeq(),
103945     ** then any copies made by synthCollSeq() need to be invalidated.
103946     ** Also, collation destructor - CollSeq.xDel() - function may need
103947     ** to be called.
103948     */ 
103949     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
103950       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
103951       int j;
103952       for(j=0; j<3; j++){
103953         CollSeq *p = &aColl[j];
103954         if( p->enc==pColl->enc ){
103955           if( p->xDel ){
103956             p->xDel(p->pUser);
103957           }
103958           p->xCmp = 0;
103959         }
103960       }
103961     }
103962   }
103963
103964   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
103965   if( pColl ){
103966     pColl->xCmp = xCompare;
103967     pColl->pUser = pCtx;
103968     pColl->xDel = xDel;
103969     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
103970     pColl->type = collType;
103971   }
103972   sqlite3Error(db, SQLITE_OK, 0);
103973   return SQLITE_OK;
103974 }
103975
103976
103977 /*
103978 ** This array defines hard upper bounds on limit values.  The
103979 ** initializer must be kept in sync with the SQLITE_LIMIT_*
103980 ** #defines in sqlite3.h.
103981 */
103982 static const int aHardLimit[] = {
103983   SQLITE_MAX_LENGTH,
103984   SQLITE_MAX_SQL_LENGTH,
103985   SQLITE_MAX_COLUMN,
103986   SQLITE_MAX_EXPR_DEPTH,
103987   SQLITE_MAX_COMPOUND_SELECT,
103988   SQLITE_MAX_VDBE_OP,
103989   SQLITE_MAX_FUNCTION_ARG,
103990   SQLITE_MAX_ATTACHED,
103991   SQLITE_MAX_LIKE_PATTERN_LENGTH,
103992   SQLITE_MAX_VARIABLE_NUMBER,
103993   SQLITE_MAX_TRIGGER_DEPTH,
103994 };
103995
103996 /*
103997 ** Make sure the hard limits are set to reasonable values
103998 */
103999 #if SQLITE_MAX_LENGTH<100
104000 # error SQLITE_MAX_LENGTH must be at least 100
104001 #endif
104002 #if SQLITE_MAX_SQL_LENGTH<100
104003 # error SQLITE_MAX_SQL_LENGTH must be at least 100
104004 #endif
104005 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
104006 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
104007 #endif
104008 #if SQLITE_MAX_COMPOUND_SELECT<2
104009 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
104010 #endif
104011 #if SQLITE_MAX_VDBE_OP<40
104012 # error SQLITE_MAX_VDBE_OP must be at least 40
104013 #endif
104014 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
104015 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
104016 #endif
104017 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
104018 # error SQLITE_MAX_ATTACHED must be between 0 and 30
104019 #endif
104020 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
104021 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
104022 #endif
104023 #if SQLITE_MAX_COLUMN>32767
104024 # error SQLITE_MAX_COLUMN must not exceed 32767
104025 #endif
104026 #if SQLITE_MAX_TRIGGER_DEPTH<1
104027 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
104028 #endif
104029
104030
104031 /*
104032 ** Change the value of a limit.  Report the old value.
104033 ** If an invalid limit index is supplied, report -1.
104034 ** Make no changes but still report the old value if the
104035 ** new limit is negative.
104036 **
104037 ** A new lower limit does not shrink existing constructs.
104038 ** It merely prevents new constructs that exceed the limit
104039 ** from forming.
104040 */
104041 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
104042   int oldLimit;
104043   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
104044     return -1;
104045   }
104046   oldLimit = db->aLimit[limitId];
104047   if( newLimit>=0 ){
104048     if( newLimit>aHardLimit[limitId] ){
104049       newLimit = aHardLimit[limitId];
104050     }
104051     db->aLimit[limitId] = newLimit;
104052   }
104053   return oldLimit;
104054 }
104055
104056 /*
104057 ** This routine does the work of opening a database on behalf of
104058 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
104059 ** is UTF-8 encoded.
104060 */
104061 static int openDatabase(
104062   const char *zFilename, /* Database filename UTF-8 encoded */
104063   sqlite3 **ppDb,        /* OUT: Returned database handle */
104064   unsigned flags,        /* Operational flags */
104065   const char *zVfs       /* Name of the VFS to use */
104066 ){
104067   sqlite3 *db;
104068   int rc;
104069   int isThreadsafe;
104070
104071   *ppDb = 0;
104072 #ifndef SQLITE_OMIT_AUTOINIT
104073   rc = sqlite3_initialize();
104074   if( rc ) return rc;
104075 #endif
104076
104077   if( sqlite3GlobalConfig.bCoreMutex==0 ){
104078     isThreadsafe = 0;
104079   }else if( flags & SQLITE_OPEN_NOMUTEX ){
104080     isThreadsafe = 0;
104081   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
104082     isThreadsafe = 1;
104083   }else{
104084     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
104085   }
104086   if( flags & SQLITE_OPEN_PRIVATECACHE ){
104087     flags &= ~SQLITE_OPEN_SHAREDCACHE;
104088   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
104089     flags |= SQLITE_OPEN_SHAREDCACHE;
104090   }
104091
104092   /* Remove harmful bits from the flags parameter
104093   **
104094   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
104095   ** dealt with in the previous code block.  Besides these, the only
104096   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
104097   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
104098   ** off all other flags.
104099   */
104100   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
104101                SQLITE_OPEN_EXCLUSIVE |
104102                SQLITE_OPEN_MAIN_DB |
104103                SQLITE_OPEN_TEMP_DB | 
104104                SQLITE_OPEN_TRANSIENT_DB | 
104105                SQLITE_OPEN_MAIN_JOURNAL | 
104106                SQLITE_OPEN_TEMP_JOURNAL | 
104107                SQLITE_OPEN_SUBJOURNAL | 
104108                SQLITE_OPEN_MASTER_JOURNAL |
104109                SQLITE_OPEN_NOMUTEX |
104110                SQLITE_OPEN_FULLMUTEX
104111              );
104112
104113   /* Allocate the sqlite data structure */
104114   db = sqlite3MallocZero( sizeof(sqlite3) );
104115   if( db==0 ) goto opendb_out;
104116   if( isThreadsafe ){
104117     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
104118     if( db->mutex==0 ){
104119       sqlite3_free(db);
104120       db = 0;
104121       goto opendb_out;
104122     }
104123   }
104124   sqlite3_mutex_enter(db->mutex);
104125   db->errMask = 0xff;
104126   db->nDb = 2;
104127   db->magic = SQLITE_MAGIC_BUSY;
104128   db->aDb = db->aDbStatic;
104129
104130   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
104131   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
104132   db->autoCommit = 1;
104133   db->nextAutovac = -1;
104134   db->nextPagesize = 0;
104135   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
104136 #if SQLITE_DEFAULT_FILE_FORMAT<4
104137                  | SQLITE_LegacyFileFmt
104138 #endif
104139 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
104140                  | SQLITE_LoadExtension
104141 #endif
104142 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
104143                  | SQLITE_RecTriggers
104144 #endif
104145       ;
104146   sqlite3HashInit(&db->aCollSeq);
104147 #ifndef SQLITE_OMIT_VIRTUALTABLE
104148   sqlite3HashInit(&db->aModule);
104149 #endif
104150
104151   db->pVfs = sqlite3_vfs_find(zVfs);
104152   if( !db->pVfs ){
104153     rc = SQLITE_ERROR;
104154     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
104155     goto opendb_out;
104156   }
104157
104158   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
104159   ** and UTF-16, so add a version for each to avoid any unnecessary
104160   ** conversions. The only error that can occur here is a malloc() failure.
104161   */
104162   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
104163                   binCollFunc, 0);
104164   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
104165                   binCollFunc, 0);
104166   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
104167                   binCollFunc, 0);
104168   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
104169                   binCollFunc, 0);
104170   if( db->mallocFailed ){
104171     goto opendb_out;
104172   }
104173   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
104174   assert( db->pDfltColl!=0 );
104175
104176   /* Also add a UTF-8 case-insensitive collation sequence. */
104177   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
104178                   nocaseCollatingFunc, 0);
104179
104180   /* Open the backend database driver */
104181   db->openFlags = flags;
104182   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
104183                            flags | SQLITE_OPEN_MAIN_DB,
104184                            &db->aDb[0].pBt);
104185   if( rc!=SQLITE_OK ){
104186     if( rc==SQLITE_IOERR_NOMEM ){
104187       rc = SQLITE_NOMEM;
104188     }
104189     sqlite3Error(db, rc, 0);
104190     goto opendb_out;
104191   }
104192   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
104193   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
104194
104195
104196   /* The default safety_level for the main database is 'full'; for the temp
104197   ** database it is 'NONE'. This matches the pager layer defaults.  
104198   */
104199   db->aDb[0].zName = "main";
104200   db->aDb[0].safety_level = 3;
104201   db->aDb[1].zName = "temp";
104202   db->aDb[1].safety_level = 1;
104203
104204   db->magic = SQLITE_MAGIC_OPEN;
104205   if( db->mallocFailed ){
104206     goto opendb_out;
104207   }
104208
104209   /* Register all built-in functions, but do not attempt to read the
104210   ** database schema yet. This is delayed until the first time the database
104211   ** is accessed.
104212   */
104213   sqlite3Error(db, SQLITE_OK, 0);
104214   sqlite3RegisterBuiltinFunctions(db);
104215
104216   /* Load automatic extensions - extensions that have been registered
104217   ** using the sqlite3_automatic_extension() API.
104218   */
104219   sqlite3AutoLoadExtensions(db);
104220   rc = sqlite3_errcode(db);
104221   if( rc!=SQLITE_OK ){
104222     goto opendb_out;
104223   }
104224
104225 #ifdef SQLITE_ENABLE_FTS1
104226   if( !db->mallocFailed ){
104227     extern int sqlite3Fts1Init(sqlite3*);
104228     rc = sqlite3Fts1Init(db);
104229   }
104230 #endif
104231
104232 #ifdef SQLITE_ENABLE_FTS2
104233   if( !db->mallocFailed && rc==SQLITE_OK ){
104234     extern int sqlite3Fts2Init(sqlite3*);
104235     rc = sqlite3Fts2Init(db);
104236   }
104237 #endif
104238
104239 #ifdef SQLITE_ENABLE_FTS3
104240   if( !db->mallocFailed && rc==SQLITE_OK ){
104241     rc = sqlite3Fts3Init(db);
104242   }
104243 #endif
104244
104245 #ifdef SQLITE_ENABLE_ICU
104246   if( !db->mallocFailed && rc==SQLITE_OK ){
104247     rc = sqlite3IcuInit(db);
104248   }
104249 #endif
104250
104251 #ifdef SQLITE_ENABLE_RTREE
104252   if( !db->mallocFailed && rc==SQLITE_OK){
104253     rc = sqlite3RtreeInit(db);
104254   }
104255 #endif
104256
104257   sqlite3Error(db, rc, 0);
104258
104259   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
104260   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
104261   ** mode.  Doing nothing at all also makes NORMAL the default.
104262   */
104263 #ifdef SQLITE_DEFAULT_LOCKING_MODE
104264   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
104265   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
104266                           SQLITE_DEFAULT_LOCKING_MODE);
104267 #endif
104268
104269   /* Enable the lookaside-malloc subsystem */
104270   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
104271                         sqlite3GlobalConfig.nLookaside);
104272
104273   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
104274
104275 opendb_out:
104276   if( db ){
104277     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
104278     sqlite3_mutex_leave(db->mutex);
104279   }
104280   rc = sqlite3_errcode(db);
104281   if( rc==SQLITE_NOMEM ){
104282     sqlite3_close(db);
104283     db = 0;
104284   }else if( rc!=SQLITE_OK ){
104285     db->magic = SQLITE_MAGIC_SICK;
104286   }
104287   *ppDb = db;
104288   return sqlite3ApiExit(0, rc);
104289 }
104290
104291 /*
104292 ** Open a new database handle.
104293 */
104294 SQLITE_API int sqlite3_open(
104295   const char *zFilename, 
104296   sqlite3 **ppDb 
104297 ){
104298   return openDatabase(zFilename, ppDb,
104299                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
104300 }
104301 SQLITE_API int sqlite3_open_v2(
104302   const char *filename,   /* Database filename (UTF-8) */
104303   sqlite3 **ppDb,         /* OUT: SQLite db handle */
104304   int flags,              /* Flags */
104305   const char *zVfs        /* Name of VFS module to use */
104306 ){
104307   return openDatabase(filename, ppDb, flags, zVfs);
104308 }
104309
104310 #ifndef SQLITE_OMIT_UTF16
104311 /*
104312 ** Open a new database handle.
104313 */
104314 SQLITE_API int sqlite3_open16(
104315   const void *zFilename, 
104316   sqlite3 **ppDb
104317 ){
104318   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
104319   sqlite3_value *pVal;
104320   int rc;
104321
104322   assert( zFilename );
104323   assert( ppDb );
104324   *ppDb = 0;
104325 #ifndef SQLITE_OMIT_AUTOINIT
104326   rc = sqlite3_initialize();
104327   if( rc ) return rc;
104328 #endif
104329   pVal = sqlite3ValueNew(0);
104330   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
104331   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
104332   if( zFilename8 ){
104333     rc = openDatabase(zFilename8, ppDb,
104334                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
104335     assert( *ppDb || rc==SQLITE_NOMEM );
104336     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
104337       ENC(*ppDb) = SQLITE_UTF16NATIVE;
104338     }
104339   }else{
104340     rc = SQLITE_NOMEM;
104341   }
104342   sqlite3ValueFree(pVal);
104343
104344   return sqlite3ApiExit(0, rc);
104345 }
104346 #endif /* SQLITE_OMIT_UTF16 */
104347
104348 /*
104349 ** Register a new collation sequence with the database handle db.
104350 */
104351 SQLITE_API int sqlite3_create_collation(
104352   sqlite3* db, 
104353   const char *zName, 
104354   int enc, 
104355   void* pCtx,
104356   int(*xCompare)(void*,int,const void*,int,const void*)
104357 ){
104358   int rc;
104359   sqlite3_mutex_enter(db->mutex);
104360   assert( !db->mallocFailed );
104361   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104362   rc = sqlite3ApiExit(db, rc);
104363   sqlite3_mutex_leave(db->mutex);
104364   return rc;
104365 }
104366
104367 /*
104368 ** Register a new collation sequence with the database handle db.
104369 */
104370 SQLITE_API int sqlite3_create_collation_v2(
104371   sqlite3* db, 
104372   const char *zName, 
104373   int enc, 
104374   void* pCtx,
104375   int(*xCompare)(void*,int,const void*,int,const void*),
104376   void(*xDel)(void*)
104377 ){
104378   int rc;
104379   sqlite3_mutex_enter(db->mutex);
104380   assert( !db->mallocFailed );
104381   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
104382   rc = sqlite3ApiExit(db, rc);
104383   sqlite3_mutex_leave(db->mutex);
104384   return rc;
104385 }
104386
104387 #ifndef SQLITE_OMIT_UTF16
104388 /*
104389 ** Register a new collation sequence with the database handle db.
104390 */
104391 SQLITE_API int sqlite3_create_collation16(
104392   sqlite3* db, 
104393   const void *zName,
104394   int enc, 
104395   void* pCtx,
104396   int(*xCompare)(void*,int,const void*,int,const void*)
104397 ){
104398   int rc = SQLITE_OK;
104399   char *zName8;
104400   sqlite3_mutex_enter(db->mutex);
104401   assert( !db->mallocFailed );
104402   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
104403   if( zName8 ){
104404     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104405     sqlite3DbFree(db, zName8);
104406   }
104407   rc = sqlite3ApiExit(db, rc);
104408   sqlite3_mutex_leave(db->mutex);
104409   return rc;
104410 }
104411 #endif /* SQLITE_OMIT_UTF16 */
104412
104413 /*
104414 ** Register a collation sequence factory callback with the database handle
104415 ** db. Replace any previously installed collation sequence factory.
104416 */
104417 SQLITE_API int sqlite3_collation_needed(
104418   sqlite3 *db, 
104419   void *pCollNeededArg, 
104420   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
104421 ){
104422   sqlite3_mutex_enter(db->mutex);
104423   db->xCollNeeded = xCollNeeded;
104424   db->xCollNeeded16 = 0;
104425   db->pCollNeededArg = pCollNeededArg;
104426   sqlite3_mutex_leave(db->mutex);
104427   return SQLITE_OK;
104428 }
104429
104430 #ifndef SQLITE_OMIT_UTF16
104431 /*
104432 ** Register a collation sequence factory callback with the database handle
104433 ** db. Replace any previously installed collation sequence factory.
104434 */
104435 SQLITE_API int sqlite3_collation_needed16(
104436   sqlite3 *db, 
104437   void *pCollNeededArg, 
104438   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
104439 ){
104440   sqlite3_mutex_enter(db->mutex);
104441   db->xCollNeeded = 0;
104442   db->xCollNeeded16 = xCollNeeded16;
104443   db->pCollNeededArg = pCollNeededArg;
104444   sqlite3_mutex_leave(db->mutex);
104445   return SQLITE_OK;
104446 }
104447 #endif /* SQLITE_OMIT_UTF16 */
104448
104449 #ifndef SQLITE_OMIT_DEPRECATED
104450 /*
104451 ** This function is now an anachronism. It used to be used to recover from a
104452 ** malloc() failure, but SQLite now does this automatically.
104453 */
104454 SQLITE_API int sqlite3_global_recover(void){
104455   return SQLITE_OK;
104456 }
104457 #endif
104458
104459 /*
104460 ** Test to see whether or not the database connection is in autocommit
104461 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
104462 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
104463 ** by the next COMMIT or ROLLBACK.
104464 **
104465 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
104466 */
104467 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
104468   return db->autoCommit;
104469 }
104470
104471 /*
104472 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
104473 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
104474 ** constants.  They server two purposes:
104475 **
104476 **   1.  Serve as a convenient place to set a breakpoint in a debugger
104477 **       to detect when version error conditions occurs.
104478 **
104479 **   2.  Invoke sqlite3_log() to provide the source code location where
104480 **       a low-level error is first detected.
104481 */
104482 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
104483   testcase( sqlite3GlobalConfig.xLog!=0 );
104484   sqlite3_log(SQLITE_CORRUPT,
104485               "database corruption at line %d of [%.10s]",
104486               lineno, 20+sqlite3_sourceid());
104487   return SQLITE_CORRUPT;
104488 }
104489 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
104490   testcase( sqlite3GlobalConfig.xLog!=0 );
104491   sqlite3_log(SQLITE_MISUSE, 
104492               "misuse at line %d of [%.10s]",
104493               lineno, 20+sqlite3_sourceid());
104494   return SQLITE_MISUSE;
104495 }
104496 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
104497   testcase( sqlite3GlobalConfig.xLog!=0 );
104498   sqlite3_log(SQLITE_CANTOPEN, 
104499               "cannot open file at line %d of [%.10s]",
104500               lineno, 20+sqlite3_sourceid());
104501   return SQLITE_CANTOPEN;
104502 }
104503
104504
104505 #ifndef SQLITE_OMIT_DEPRECATED
104506 /*
104507 ** This is a convenience routine that makes sure that all thread-specific
104508 ** data for this thread has been deallocated.
104509 **
104510 ** SQLite no longer uses thread-specific data so this routine is now a
104511 ** no-op.  It is retained for historical compatibility.
104512 */
104513 SQLITE_API void sqlite3_thread_cleanup(void){
104514 }
104515 #endif
104516
104517 /*
104518 ** Return meta information about a specific column of a database table.
104519 ** See comment in sqlite3.h (sqlite.h.in) for details.
104520 */
104521 #ifdef SQLITE_ENABLE_COLUMN_METADATA
104522 SQLITE_API int sqlite3_table_column_metadata(
104523   sqlite3 *db,                /* Connection handle */
104524   const char *zDbName,        /* Database name or NULL */
104525   const char *zTableName,     /* Table name */
104526   const char *zColumnName,    /* Column name */
104527   char const **pzDataType,    /* OUTPUT: Declared data type */
104528   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
104529   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
104530   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
104531   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
104532 ){
104533   int rc;
104534   char *zErrMsg = 0;
104535   Table *pTab = 0;
104536   Column *pCol = 0;
104537   int iCol;
104538
104539   char const *zDataType = 0;
104540   char const *zCollSeq = 0;
104541   int notnull = 0;
104542   int primarykey = 0;
104543   int autoinc = 0;
104544
104545   /* Ensure the database schema has been loaded */
104546   sqlite3_mutex_enter(db->mutex);
104547   sqlite3BtreeEnterAll(db);
104548   rc = sqlite3Init(db, &zErrMsg);
104549   if( SQLITE_OK!=rc ){
104550     goto error_out;
104551   }
104552
104553   /* Locate the table in question */
104554   pTab = sqlite3FindTable(db, zTableName, zDbName);
104555   if( !pTab || pTab->pSelect ){
104556     pTab = 0;
104557     goto error_out;
104558   }
104559
104560   /* Find the column for which info is requested */
104561   if( sqlite3IsRowid(zColumnName) ){
104562     iCol = pTab->iPKey;
104563     if( iCol>=0 ){
104564       pCol = &pTab->aCol[iCol];
104565     }
104566   }else{
104567     for(iCol=0; iCol<pTab->nCol; iCol++){
104568       pCol = &pTab->aCol[iCol];
104569       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
104570         break;
104571       }
104572     }
104573     if( iCol==pTab->nCol ){
104574       pTab = 0;
104575       goto error_out;
104576     }
104577   }
104578
104579   /* The following block stores the meta information that will be returned
104580   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
104581   ** and autoinc. At this point there are two possibilities:
104582   ** 
104583   **     1. The specified column name was rowid", "oid" or "_rowid_" 
104584   **        and there is no explicitly declared IPK column. 
104585   **
104586   **     2. The table is not a view and the column name identified an 
104587   **        explicitly declared column. Copy meta information from *pCol.
104588   */ 
104589   if( pCol ){
104590     zDataType = pCol->zType;
104591     zCollSeq = pCol->zColl;
104592     notnull = pCol->notNull!=0;
104593     primarykey  = pCol->isPrimKey!=0;
104594     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
104595   }else{
104596     zDataType = "INTEGER";
104597     primarykey = 1;
104598   }
104599   if( !zCollSeq ){
104600     zCollSeq = "BINARY";
104601   }
104602
104603 error_out:
104604   sqlite3BtreeLeaveAll(db);
104605
104606   /* Whether the function call succeeded or failed, set the output parameters
104607   ** to whatever their local counterparts contain. If an error did occur,
104608   ** this has the effect of zeroing all output parameters.
104609   */
104610   if( pzDataType ) *pzDataType = zDataType;
104611   if( pzCollSeq ) *pzCollSeq = zCollSeq;
104612   if( pNotNull ) *pNotNull = notnull;
104613   if( pPrimaryKey ) *pPrimaryKey = primarykey;
104614   if( pAutoinc ) *pAutoinc = autoinc;
104615
104616   if( SQLITE_OK==rc && !pTab ){
104617     sqlite3DbFree(db, zErrMsg);
104618     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
104619         zColumnName);
104620     rc = SQLITE_ERROR;
104621   }
104622   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
104623   sqlite3DbFree(db, zErrMsg);
104624   rc = sqlite3ApiExit(db, rc);
104625   sqlite3_mutex_leave(db->mutex);
104626   return rc;
104627 }
104628 #endif
104629
104630 /*
104631 ** Sleep for a little while.  Return the amount of time slept.
104632 */
104633 SQLITE_API int sqlite3_sleep(int ms){
104634   sqlite3_vfs *pVfs;
104635   int rc;
104636   pVfs = sqlite3_vfs_find(0);
104637   if( pVfs==0 ) return 0;
104638
104639   /* This function works in milliseconds, but the underlying OsSleep() 
104640   ** API uses microseconds. Hence the 1000's.
104641   */
104642   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
104643   return rc;
104644 }
104645
104646 /*
104647 ** Enable or disable the extended result codes.
104648 */
104649 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
104650   sqlite3_mutex_enter(db->mutex);
104651   db->errMask = onoff ? 0xffffffff : 0xff;
104652   sqlite3_mutex_leave(db->mutex);
104653   return SQLITE_OK;
104654 }
104655
104656 /*
104657 ** Invoke the xFileControl method on a particular database.
104658 */
104659 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
104660   int rc = SQLITE_ERROR;
104661   int iDb;
104662   sqlite3_mutex_enter(db->mutex);
104663   if( zDbName==0 ){
104664     iDb = 0;
104665   }else{
104666     for(iDb=0; iDb<db->nDb; iDb++){
104667       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
104668     }
104669   }
104670   if( iDb<db->nDb ){
104671     Btree *pBtree = db->aDb[iDb].pBt;
104672     if( pBtree ){
104673       Pager *pPager;
104674       sqlite3_file *fd;
104675       sqlite3BtreeEnter(pBtree);
104676       pPager = sqlite3BtreePager(pBtree);
104677       assert( pPager!=0 );
104678       fd = sqlite3PagerFile(pPager);
104679       assert( fd!=0 );
104680       if( fd->pMethods ){
104681         rc = sqlite3OsFileControl(fd, op, pArg);
104682       }
104683       sqlite3BtreeLeave(pBtree);
104684     }
104685   }
104686   sqlite3_mutex_leave(db->mutex);
104687   return rc;   
104688 }
104689
104690 /*
104691 ** Interface to the testing logic.
104692 */
104693 SQLITE_API int sqlite3_test_control(int op, ...){
104694   int rc = 0;
104695 #ifndef SQLITE_OMIT_BUILTIN_TEST
104696   va_list ap;
104697   va_start(ap, op);
104698   switch( op ){
104699
104700     /*
104701     ** Save the current state of the PRNG.
104702     */
104703     case SQLITE_TESTCTRL_PRNG_SAVE: {
104704       sqlite3PrngSaveState();
104705       break;
104706     }
104707
104708     /*
104709     ** Restore the state of the PRNG to the last state saved using
104710     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
104711     ** this verb acts like PRNG_RESET.
104712     */
104713     case SQLITE_TESTCTRL_PRNG_RESTORE: {
104714       sqlite3PrngRestoreState();
104715       break;
104716     }
104717
104718     /*
104719     ** Reset the PRNG back to its uninitialized state.  The next call
104720     ** to sqlite3_randomness() will reseed the PRNG using a single call
104721     ** to the xRandomness method of the default VFS.
104722     */
104723     case SQLITE_TESTCTRL_PRNG_RESET: {
104724       sqlite3PrngResetState();
104725       break;
104726     }
104727
104728     /*
104729     **  sqlite3_test_control(BITVEC_TEST, size, program)
104730     **
104731     ** Run a test against a Bitvec object of size.  The program argument
104732     ** is an array of integers that defines the test.  Return -1 on a
104733     ** memory allocation error, 0 on success, or non-zero for an error.
104734     ** See the sqlite3BitvecBuiltinTest() for additional information.
104735     */
104736     case SQLITE_TESTCTRL_BITVEC_TEST: {
104737       int sz = va_arg(ap, int);
104738       int *aProg = va_arg(ap, int*);
104739       rc = sqlite3BitvecBuiltinTest(sz, aProg);
104740       break;
104741     }
104742
104743     /*
104744     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
104745     **
104746     ** Register hooks to call to indicate which malloc() failures 
104747     ** are benign.
104748     */
104749     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
104750       typedef void (*void_function)(void);
104751       void_function xBenignBegin;
104752       void_function xBenignEnd;
104753       xBenignBegin = va_arg(ap, void_function);
104754       xBenignEnd = va_arg(ap, void_function);
104755       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
104756       break;
104757     }
104758
104759     /*
104760     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
104761     **
104762     ** Set the PENDING byte to the value in the argument, if X>0.
104763     ** Make no changes if X==0.  Return the value of the pending byte
104764     ** as it existing before this routine was called.
104765     **
104766     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
104767     ** an incompatible database file format.  Changing the PENDING byte
104768     ** while any database connection is open results in undefined and
104769     ** dileterious behavior.
104770     */
104771     case SQLITE_TESTCTRL_PENDING_BYTE: {
104772       rc = PENDING_BYTE;
104773 #ifndef SQLITE_OMIT_WSD
104774       {
104775         unsigned int newVal = va_arg(ap, unsigned int);
104776         if( newVal ) sqlite3PendingByte = newVal;
104777       }
104778 #endif
104779       break;
104780     }
104781
104782     /*
104783     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
104784     **
104785     ** This action provides a run-time test to see whether or not
104786     ** assert() was enabled at compile-time.  If X is true and assert()
104787     ** is enabled, then the return value is true.  If X is true and
104788     ** assert() is disabled, then the return value is zero.  If X is
104789     ** false and assert() is enabled, then the assertion fires and the
104790     ** process aborts.  If X is false and assert() is disabled, then the
104791     ** return value is zero.
104792     */
104793     case SQLITE_TESTCTRL_ASSERT: {
104794       volatile int x = 0;
104795       assert( (x = va_arg(ap,int))!=0 );
104796       rc = x;
104797       break;
104798     }
104799
104800
104801     /*
104802     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
104803     **
104804     ** This action provides a run-time test to see how the ALWAYS and
104805     ** NEVER macros were defined at compile-time.
104806     **
104807     ** The return value is ALWAYS(X).  
104808     **
104809     ** The recommended test is X==2.  If the return value is 2, that means
104810     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
104811     ** default setting.  If the return value is 1, then ALWAYS() is either
104812     ** hard-coded to true or else it asserts if its argument is false.
104813     ** The first behavior (hard-coded to true) is the case if
104814     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
104815     ** behavior (assert if the argument to ALWAYS() is false) is the case if
104816     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
104817     **
104818     ** The run-time test procedure might look something like this:
104819     **
104820     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
104821     **      // ALWAYS() and NEVER() are no-op pass-through macros
104822     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
104823     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
104824     **    }else{
104825     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
104826     **    }
104827     */
104828     case SQLITE_TESTCTRL_ALWAYS: {
104829       int x = va_arg(ap,int);
104830       rc = ALWAYS(x);
104831       break;
104832     }
104833
104834     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
104835     **
104836     ** Set the nReserve size to N for the main database on the database
104837     ** connection db.
104838     */
104839     case SQLITE_TESTCTRL_RESERVE: {
104840       sqlite3 *db = va_arg(ap, sqlite3*);
104841       int x = va_arg(ap,int);
104842       sqlite3_mutex_enter(db->mutex);
104843       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
104844       sqlite3_mutex_leave(db->mutex);
104845       break;
104846     }
104847
104848     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
104849     **
104850     ** Enable or disable various optimizations for testing purposes.  The 
104851     ** argument N is a bitmask of optimizations to be disabled.  For normal
104852     ** operation N should be 0.  The idea is that a test program (like the
104853     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
104854     ** with various optimizations disabled to verify that the same answer
104855     ** is obtained in every case.
104856     */
104857     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
104858       sqlite3 *db = va_arg(ap, sqlite3*);
104859       int x = va_arg(ap,int);
104860       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
104861       break;
104862     }
104863
104864 #ifdef SQLITE_N_KEYWORD
104865     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
104866     **
104867     ** If zWord is a keyword recognized by the parser, then return the
104868     ** number of keywords.  Or if zWord is not a keyword, return 0.
104869     ** 
104870     ** This test feature is only available in the amalgamation since
104871     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
104872     ** is built using separate source files.
104873     */
104874     case SQLITE_TESTCTRL_ISKEYWORD: {
104875       const char *zWord = va_arg(ap, const char*);
104876       int n = sqlite3Strlen30(zWord);
104877       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
104878       break;
104879     }
104880 #endif 
104881
104882     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
104883     **
104884     ** Return the size of a pcache header in bytes.
104885     */
104886     case SQLITE_TESTCTRL_PGHDRSZ: {
104887       rc = sizeof(PgHdr);
104888       break;
104889     }
104890
104891   }
104892   va_end(ap);
104893 #endif /* SQLITE_OMIT_BUILTIN_TEST */
104894   return rc;
104895 }
104896
104897 /************** End of main.c ************************************************/
104898 /************** Begin file notify.c ******************************************/
104899 /*
104900 ** 2009 March 3
104901 **
104902 ** The author disclaims copyright to this source code.  In place of
104903 ** a legal notice, here is a blessing:
104904 **
104905 **    May you do good and not evil.
104906 **    May you find forgiveness for yourself and forgive others.
104907 **    May you share freely, never taking more than you give.
104908 **
104909 *************************************************************************
104910 **
104911 ** This file contains the implementation of the sqlite3_unlock_notify()
104912 ** API method and its associated functionality.
104913 */
104914
104915 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
104916 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
104917
104918 /*
104919 ** Public interfaces:
104920 **
104921 **   sqlite3ConnectionBlocked()
104922 **   sqlite3ConnectionUnlocked()
104923 **   sqlite3ConnectionClosed()
104924 **   sqlite3_unlock_notify()
104925 */
104926
104927 #define assertMutexHeld() \
104928   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
104929
104930 /*
104931 ** Head of a linked list of all sqlite3 objects created by this process
104932 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
104933 ** is not NULL. This variable may only accessed while the STATIC_MASTER
104934 ** mutex is held.
104935 */
104936 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
104937
104938 #ifndef NDEBUG
104939 /*
104940 ** This function is a complex assert() that verifies the following 
104941 ** properties of the blocked connections list:
104942 **
104943 **   1) Each entry in the list has a non-NULL value for either 
104944 **      pUnlockConnection or pBlockingConnection, or both.
104945 **
104946 **   2) All entries in the list that share a common value for 
104947 **      xUnlockNotify are grouped together.
104948 **
104949 **   3) If the argument db is not NULL, then none of the entries in the
104950 **      blocked connections list have pUnlockConnection or pBlockingConnection
104951 **      set to db. This is used when closing connection db.
104952 */
104953 static void checkListProperties(sqlite3 *db){
104954   sqlite3 *p;
104955   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
104956     int seen = 0;
104957     sqlite3 *p2;
104958
104959     /* Verify property (1) */
104960     assert( p->pUnlockConnection || p->pBlockingConnection );
104961
104962     /* Verify property (2) */
104963     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
104964       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
104965       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
104966       assert( db==0 || p->pUnlockConnection!=db );
104967       assert( db==0 || p->pBlockingConnection!=db );
104968     }
104969   }
104970 }
104971 #else
104972 # define checkListProperties(x)
104973 #endif
104974
104975 /*
104976 ** Remove connection db from the blocked connections list. If connection
104977 ** db is not currently a part of the list, this function is a no-op.
104978 */
104979 static void removeFromBlockedList(sqlite3 *db){
104980   sqlite3 **pp;
104981   assertMutexHeld();
104982   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
104983     if( *pp==db ){
104984       *pp = (*pp)->pNextBlocked;
104985       break;
104986     }
104987   }
104988 }
104989
104990 /*
104991 ** Add connection db to the blocked connections list. It is assumed
104992 ** that it is not already a part of the list.
104993 */
104994 static void addToBlockedList(sqlite3 *db){
104995   sqlite3 **pp;
104996   assertMutexHeld();
104997   for(
104998     pp=&sqlite3BlockedList; 
104999     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
105000     pp=&(*pp)->pNextBlocked
105001   );
105002   db->pNextBlocked = *pp;
105003   *pp = db;
105004 }
105005
105006 /*
105007 ** Obtain the STATIC_MASTER mutex.
105008 */
105009 static void enterMutex(void){
105010   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
105011   checkListProperties(0);
105012 }
105013
105014 /*
105015 ** Release the STATIC_MASTER mutex.
105016 */
105017 static void leaveMutex(void){
105018   assertMutexHeld();
105019   checkListProperties(0);
105020   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
105021 }
105022
105023 /*
105024 ** Register an unlock-notify callback.
105025 **
105026 ** This is called after connection "db" has attempted some operation
105027 ** but has received an SQLITE_LOCKED error because another connection
105028 ** (call it pOther) in the same process was busy using the same shared
105029 ** cache.  pOther is found by looking at db->pBlockingConnection.
105030 **
105031 ** If there is no blocking connection, the callback is invoked immediately,
105032 ** before this routine returns.
105033 **
105034 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
105035 ** a deadlock.
105036 **
105037 ** Otherwise, make arrangements to invoke xNotify when pOther drops
105038 ** its locks.
105039 **
105040 ** Each call to this routine overrides any prior callbacks registered
105041 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
105042 ** cancelled.
105043 */
105044 SQLITE_API int sqlite3_unlock_notify(
105045   sqlite3 *db,
105046   void (*xNotify)(void **, int),
105047   void *pArg
105048 ){
105049   int rc = SQLITE_OK;
105050
105051   sqlite3_mutex_enter(db->mutex);
105052   enterMutex();
105053
105054   if( xNotify==0 ){
105055     removeFromBlockedList(db);
105056     db->pBlockingConnection = 0;
105057     db->pUnlockConnection = 0;
105058     db->xUnlockNotify = 0;
105059     db->pUnlockArg = 0;
105060   }else if( 0==db->pBlockingConnection ){
105061     /* The blocking transaction has been concluded. Or there never was a 
105062     ** blocking transaction. In either case, invoke the notify callback
105063     ** immediately. 
105064     */
105065     xNotify(&pArg, 1);
105066   }else{
105067     sqlite3 *p;
105068
105069     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
105070     if( p ){
105071       rc = SQLITE_LOCKED;              /* Deadlock detected. */
105072     }else{
105073       db->pUnlockConnection = db->pBlockingConnection;
105074       db->xUnlockNotify = xNotify;
105075       db->pUnlockArg = pArg;
105076       removeFromBlockedList(db);
105077       addToBlockedList(db);
105078     }
105079   }
105080
105081   leaveMutex();
105082   assert( !db->mallocFailed );
105083   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
105084   sqlite3_mutex_leave(db->mutex);
105085   return rc;
105086 }
105087
105088 /*
105089 ** This function is called while stepping or preparing a statement 
105090 ** associated with connection db. The operation will return SQLITE_LOCKED
105091 ** to the user because it requires a lock that will not be available
105092 ** until connection pBlocker concludes its current transaction.
105093 */
105094 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
105095   enterMutex();
105096   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
105097     addToBlockedList(db);
105098   }
105099   db->pBlockingConnection = pBlocker;
105100   leaveMutex();
105101 }
105102
105103 /*
105104 ** This function is called when
105105 ** the transaction opened by database db has just finished. Locks held 
105106 ** by database connection db have been released.
105107 **
105108 ** This function loops through each entry in the blocked connections
105109 ** list and does the following:
105110 **
105111 **   1) If the sqlite3.pBlockingConnection member of a list entry is
105112 **      set to db, then set pBlockingConnection=0.
105113 **
105114 **   2) If the sqlite3.pUnlockConnection member of a list entry is
105115 **      set to db, then invoke the configured unlock-notify callback and
105116 **      set pUnlockConnection=0.
105117 **
105118 **   3) If the two steps above mean that pBlockingConnection==0 and
105119 **      pUnlockConnection==0, remove the entry from the blocked connections
105120 **      list.
105121 */
105122 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
105123   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
105124   int nArg = 0;                            /* Number of entries in aArg[] */
105125   sqlite3 **pp;                            /* Iterator variable */
105126   void **aArg;               /* Arguments to the unlock callback */
105127   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
105128   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
105129
105130   aArg = aStatic;
105131   enterMutex();         /* Enter STATIC_MASTER mutex */
105132
105133   /* This loop runs once for each entry in the blocked-connections list. */
105134   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
105135     sqlite3 *p = *pp;
105136
105137     /* Step 1. */
105138     if( p->pBlockingConnection==db ){
105139       p->pBlockingConnection = 0;
105140     }
105141
105142     /* Step 2. */
105143     if( p->pUnlockConnection==db ){
105144       assert( p->xUnlockNotify );
105145       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
105146         xUnlockNotify(aArg, nArg);
105147         nArg = 0;
105148       }
105149
105150       sqlite3BeginBenignMalloc();
105151       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
105152       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
105153       if( (!aDyn && nArg==(int)ArraySize(aStatic))
105154        || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
105155       ){
105156         /* The aArg[] array needs to grow. */
105157         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
105158         if( pNew ){
105159           memcpy(pNew, aArg, nArg*sizeof(void *));
105160           sqlite3_free(aDyn);
105161           aDyn = aArg = pNew;
105162         }else{
105163           /* This occurs when the array of context pointers that need to
105164           ** be passed to the unlock-notify callback is larger than the
105165           ** aStatic[] array allocated on the stack and the attempt to 
105166           ** allocate a larger array from the heap has failed.
105167           **
105168           ** This is a difficult situation to handle. Returning an error
105169           ** code to the caller is insufficient, as even if an error code
105170           ** is returned the transaction on connection db will still be
105171           ** closed and the unlock-notify callbacks on blocked connections
105172           ** will go unissued. This might cause the application to wait
105173           ** indefinitely for an unlock-notify callback that will never 
105174           ** arrive.
105175           **
105176           ** Instead, invoke the unlock-notify callback with the context
105177           ** array already accumulated. We can then clear the array and
105178           ** begin accumulating any further context pointers without 
105179           ** requiring any dynamic allocation. This is sub-optimal because
105180           ** it means that instead of one callback with a large array of
105181           ** context pointers the application will receive two or more
105182           ** callbacks with smaller arrays of context pointers, which will
105183           ** reduce the applications ability to prioritize multiple 
105184           ** connections. But it is the best that can be done under the
105185           ** circumstances.
105186           */
105187           xUnlockNotify(aArg, nArg);
105188           nArg = 0;
105189         }
105190       }
105191       sqlite3EndBenignMalloc();
105192
105193       aArg[nArg++] = p->pUnlockArg;
105194       xUnlockNotify = p->xUnlockNotify;
105195       p->pUnlockConnection = 0;
105196       p->xUnlockNotify = 0;
105197       p->pUnlockArg = 0;
105198     }
105199
105200     /* Step 3. */
105201     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
105202       /* Remove connection p from the blocked connections list. */
105203       *pp = p->pNextBlocked;
105204       p->pNextBlocked = 0;
105205     }else{
105206       pp = &p->pNextBlocked;
105207     }
105208   }
105209
105210   if( nArg!=0 ){
105211     xUnlockNotify(aArg, nArg);
105212   }
105213   sqlite3_free(aDyn);
105214   leaveMutex();         /* Leave STATIC_MASTER mutex */
105215 }
105216
105217 /*
105218 ** This is called when the database connection passed as an argument is 
105219 ** being closed. The connection is removed from the blocked list.
105220 */
105221 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
105222   sqlite3ConnectionUnlocked(db);
105223   enterMutex();
105224   removeFromBlockedList(db);
105225   checkListProperties(db);
105226   leaveMutex();
105227 }
105228 #endif
105229
105230 /************** End of notify.c **********************************************/
105231 /************** Begin file fts3.c ********************************************/
105232 /*
105233 ** 2006 Oct 10
105234 **
105235 ** The author disclaims copyright to this source code.  In place of
105236 ** a legal notice, here is a blessing:
105237 **
105238 **    May you do good and not evil.
105239 **    May you find forgiveness for yourself and forgive others.
105240 **    May you share freely, never taking more than you give.
105241 **
105242 ******************************************************************************
105243 **
105244 ** This is an SQLite module implementing full-text search.
105245 */
105246
105247 /*
105248 ** The code in this file is only compiled if:
105249 **
105250 **     * The FTS3 module is being built as an extension
105251 **       (in which case SQLITE_CORE is not defined), or
105252 **
105253 **     * The FTS3 module is being built into the core of
105254 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
105255 */
105256
105257 /* The full-text index is stored in a series of b+tree (-like)
105258 ** structures called segments which map terms to doclists.  The
105259 ** structures are like b+trees in layout, but are constructed from the
105260 ** bottom up in optimal fashion and are not updatable.  Since trees
105261 ** are built from the bottom up, things will be described from the
105262 ** bottom up.
105263 **
105264 **
105265 **** Varints ****
105266 ** The basic unit of encoding is a variable-length integer called a
105267 ** varint.  We encode variable-length integers in little-endian order
105268 ** using seven bits * per byte as follows:
105269 **
105270 ** KEY:
105271 **         A = 0xxxxxxx    7 bits of data and one flag bit
105272 **         B = 1xxxxxxx    7 bits of data and one flag bit
105273 **
105274 **  7 bits - A
105275 ** 14 bits - BA
105276 ** 21 bits - BBA
105277 ** and so on.
105278 **
105279 ** This is similar in concept to how sqlite encodes "varints" but
105280 ** the encoding is not the same.  SQLite varints are big-endian
105281 ** are are limited to 9 bytes in length whereas FTS3 varints are
105282 ** little-endian and can be up to 10 bytes in length (in theory).
105283 **
105284 ** Example encodings:
105285 **
105286 **     1:    0x01
105287 **   127:    0x7f
105288 **   128:    0x81 0x00
105289 **
105290 **
105291 **** Document lists ****
105292 ** A doclist (document list) holds a docid-sorted list of hits for a
105293 ** given term.  Doclists hold docids and associated token positions.
105294 ** A docid is the unique integer identifier for a single document.
105295 ** A position is the index of a word within the document.  The first 
105296 ** word of the document has a position of 0.
105297 **
105298 ** FTS3 used to optionally store character offsets using a compile-time
105299 ** option.  But that functionality is no longer supported.
105300 **
105301 ** A doclist is stored like this:
105302 **
105303 ** array {
105304 **   varint docid;
105305 **   array {                (position list for column 0)
105306 **     varint position;     (2 more than the delta from previous position)
105307 **   }
105308 **   array {
105309 **     varint POS_COLUMN;   (marks start of position list for new column)
105310 **     varint column;       (index of new column)
105311 **     array {
105312 **       varint position;   (2 more than the delta from previous position)
105313 **     }
105314 **   }
105315 **   varint POS_END;        (marks end of positions for this document.
105316 ** }
105317 **
105318 ** Here, array { X } means zero or more occurrences of X, adjacent in
105319 ** memory.  A "position" is an index of a token in the token stream
105320 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
105321 ** in the same logical place as the position element, and act as sentinals
105322 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
105323 ** The positions numbers are not stored literally but rather as two more
105324 ** than the difference from the prior position, or the just the position plus
105325 ** 2 for the first position.  Example:
105326 **
105327 **   label:       A B C D E  F  G H   I  J K
105328 **   value:     123 5 9 1 1 14 35 0 234 72 0
105329 **
105330 ** The 123 value is the first docid.  For column zero in this document
105331 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
105332 ** at D signals the start of a new column; the 1 at E indicates that the
105333 ** new column is column number 1.  There are two positions at 12 and 45
105334 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
105335 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
105336 ** terminates with the 0 at K.
105337 **
105338 ** A "position-list" is the list of positions for multiple columns for
105339 ** a single docid.  A "column-list" is the set of positions for a single
105340 ** column.  Hence, a position-list consists of one or more column-lists,
105341 ** a document record consists of a docid followed by a position-list and
105342 ** a doclist consists of one or more document records.
105343 **
105344 ** A bare doclist omits the position information, becoming an 
105345 ** array of varint-encoded docids.
105346 **
105347 **** Segment leaf nodes ****
105348 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
105349 ** nodes are written using LeafWriter, and read using LeafReader (to
105350 ** iterate through a single leaf node's data) and LeavesReader (to
105351 ** iterate through a segment's entire leaf layer).  Leaf nodes have
105352 ** the format:
105353 **
105354 ** varint iHeight;             (height from leaf level, always 0)
105355 ** varint nTerm;               (length of first term)
105356 ** char pTerm[nTerm];          (content of first term)
105357 ** varint nDoclist;            (length of term's associated doclist)
105358 ** char pDoclist[nDoclist];    (content of doclist)
105359 ** array {
105360 **                             (further terms are delta-encoded)
105361 **   varint nPrefix;           (length of prefix shared with previous term)
105362 **   varint nSuffix;           (length of unshared suffix)
105363 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
105364 **   varint nDoclist;          (length of term's associated doclist)
105365 **   char pDoclist[nDoclist];  (content of doclist)
105366 ** }
105367 **
105368 ** Here, array { X } means zero or more occurrences of X, adjacent in
105369 ** memory.
105370 **
105371 ** Leaf nodes are broken into blocks which are stored contiguously in
105372 ** the %_segments table in sorted order.  This means that when the end
105373 ** of a node is reached, the next term is in the node with the next
105374 ** greater node id.
105375 **
105376 ** New data is spilled to a new leaf node when the current node
105377 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
105378 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
105379 ** node (a leaf node with a single term and doclist).  The goal of
105380 ** these settings is to pack together groups of small doclists while
105381 ** making it efficient to directly access large doclists.  The
105382 ** assumption is that large doclists represent terms which are more
105383 ** likely to be query targets.
105384 **
105385 ** TODO(shess) It may be useful for blocking decisions to be more
105386 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
105387 ** node rather than splitting into 2k and .5k nodes.  My intuition is
105388 ** that this might extend through 2x or 4x the pagesize.
105389 **
105390 **
105391 **** Segment interior nodes ****
105392 ** Segment interior nodes store blockids for subtree nodes and terms
105393 ** to describe what data is stored by the each subtree.  Interior
105394 ** nodes are written using InteriorWriter, and read using
105395 ** InteriorReader.  InteriorWriters are created as needed when
105396 ** SegmentWriter creates new leaf nodes, or when an interior node
105397 ** itself grows too big and must be split.  The format of interior
105398 ** nodes:
105399 **
105400 ** varint iHeight;           (height from leaf level, always >0)
105401 ** varint iBlockid;          (block id of node's leftmost subtree)
105402 ** optional {
105403 **   varint nTerm;           (length of first term)
105404 **   char pTerm[nTerm];      (content of first term)
105405 **   array {
105406 **                                (further terms are delta-encoded)
105407 **     varint nPrefix;            (length of shared prefix with previous term)
105408 **     varint nSuffix;            (length of unshared suffix)
105409 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
105410 **   }
105411 ** }
105412 **
105413 ** Here, optional { X } means an optional element, while array { X }
105414 ** means zero or more occurrences of X, adjacent in memory.
105415 **
105416 ** An interior node encodes n terms separating n+1 subtrees.  The
105417 ** subtree blocks are contiguous, so only the first subtree's blockid
105418 ** is encoded.  The subtree at iBlockid will contain all terms less
105419 ** than the first term encoded (or all terms if no term is encoded).
105420 ** Otherwise, for terms greater than or equal to pTerm[i] but less
105421 ** than pTerm[i+1], the subtree for that term will be rooted at
105422 ** iBlockid+i.  Interior nodes only store enough term data to
105423 ** distinguish adjacent children (if the rightmost term of the left
105424 ** child is "something", and the leftmost term of the right child is
105425 ** "wicked", only "w" is stored).
105426 **
105427 ** New data is spilled to a new interior node at the same height when
105428 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
105429 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
105430 ** interior nodes and making the tree too skinny.  The interior nodes
105431 ** at a given height are naturally tracked by interior nodes at
105432 ** height+1, and so on.
105433 **
105434 **
105435 **** Segment directory ****
105436 ** The segment directory in table %_segdir stores meta-information for
105437 ** merging and deleting segments, and also the root node of the
105438 ** segment's tree.
105439 **
105440 ** The root node is the top node of the segment's tree after encoding
105441 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
105442 ** This could be either a leaf node or an interior node.  If the top
105443 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
105444 ** and a new root interior node is generated (which should always fit
105445 ** within ROOT_MAX because it only needs space for 2 varints, the
105446 ** height and the blockid of the previous root).
105447 **
105448 ** The meta-information in the segment directory is:
105449 **   level               - segment level (see below)
105450 **   idx                 - index within level
105451 **                       - (level,idx uniquely identify a segment)
105452 **   start_block         - first leaf node
105453 **   leaves_end_block    - last leaf node
105454 **   end_block           - last block (including interior nodes)
105455 **   root                - contents of root node
105456 **
105457 ** If the root node is a leaf node, then start_block,
105458 ** leaves_end_block, and end_block are all 0.
105459 **
105460 **
105461 **** Segment merging ****
105462 ** To amortize update costs, segments are grouped into levels and
105463 ** merged in batches.  Each increase in level represents exponentially
105464 ** more documents.
105465 **
105466 ** New documents (actually, document updates) are tokenized and
105467 ** written individually (using LeafWriter) to a level 0 segment, with
105468 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
105469 ** level 0 segments are merged into a single level 1 segment.  Level 1
105470 ** is populated like level 0, and eventually MERGE_COUNT level 1
105471 ** segments are merged to a single level 2 segment (representing
105472 ** MERGE_COUNT^2 updates), and so on.
105473 **
105474 ** A segment merge traverses all segments at a given level in
105475 ** parallel, performing a straightforward sorted merge.  Since segment
105476 ** leaf nodes are written in to the %_segments table in order, this
105477 ** merge traverses the underlying sqlite disk structures efficiently.
105478 ** After the merge, all segment blocks from the merged level are
105479 ** deleted.
105480 **
105481 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
105482 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
105483 ** very similar performance numbers to 16 on insertion, though they're
105484 ** a tiny bit slower (perhaps due to more overhead in merge-time
105485 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
105486 ** 16, 2 about 66% slower than 16.
105487 **
105488 ** At query time, high MERGE_COUNT increases the number of segments
105489 ** which need to be scanned and merged.  For instance, with 100k docs
105490 ** inserted:
105491 **
105492 **    MERGE_COUNT   segments
105493 **       16           25
105494 **        8           12
105495 **        4           10
105496 **        2            6
105497 **
105498 ** This appears to have only a moderate impact on queries for very
105499 ** frequent terms (which are somewhat dominated by segment merge
105500 ** costs), and infrequent and non-existent terms still seem to be fast
105501 ** even with many segments.
105502 **
105503 ** TODO(shess) That said, it would be nice to have a better query-side
105504 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
105505 ** optimizations to things like doclist merging will swing the sweet
105506 ** spot around.
105507 **
105508 **
105509 **
105510 **** Handling of deletions and updates ****
105511 ** Since we're using a segmented structure, with no docid-oriented
105512 ** index into the term index, we clearly cannot simply update the term
105513 ** index when a document is deleted or updated.  For deletions, we
105514 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
105515 ** we simply write the new doclist.  Segment merges overwrite older
105516 ** data for a particular docid with newer data, so deletes or updates
105517 ** will eventually overtake the earlier data and knock it out.  The
105518 ** query logic likewise merges doclists so that newer data knocks out
105519 ** older data.
105520 **
105521 ** TODO(shess) Provide a VACUUM type operation to clear out all
105522 ** deletions and duplications.  This would basically be a forced merge
105523 ** into a single segment.
105524 */
105525
105526 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105527
105528 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
105529 # define SQLITE_CORE 1
105530 #endif
105531
105532 /************** Include fts3Int.h in the middle of fts3.c ********************/
105533 /************** Begin file fts3Int.h *****************************************/
105534 /*
105535 ** 2009 Nov 12
105536 **
105537 ** The author disclaims copyright to this source code.  In place of
105538 ** a legal notice, here is a blessing:
105539 **
105540 **    May you do good and not evil.
105541 **    May you find forgiveness for yourself and forgive others.
105542 **    May you share freely, never taking more than you give.
105543 **
105544 ******************************************************************************
105545 **
105546 */
105547
105548 #ifndef _FTSINT_H
105549 #define _FTSINT_H
105550
105551 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
105552 # define NDEBUG 1
105553 #endif
105554
105555 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
105556 /************** Begin file fts3_tokenizer.h **********************************/
105557 /*
105558 ** 2006 July 10
105559 **
105560 ** The author disclaims copyright to this source code.
105561 **
105562 *************************************************************************
105563 ** Defines the interface to tokenizers used by fulltext-search.  There
105564 ** are three basic components:
105565 **
105566 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
105567 ** interface functions.  This is essentially the class structure for
105568 ** tokenizers.
105569 **
105570 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
105571 ** including customization information defined at creation time.
105572 **
105573 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
105574 ** tokens from a particular input.
105575 */
105576 #ifndef _FTS3_TOKENIZER_H_
105577 #define _FTS3_TOKENIZER_H_
105578
105579 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
105580 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
105581 ** we will need a way to register the API consistently.
105582 */
105583
105584 /*
105585 ** Structures used by the tokenizer interface. When a new tokenizer
105586 ** implementation is registered, the caller provides a pointer to
105587 ** an sqlite3_tokenizer_module containing pointers to the callback
105588 ** functions that make up an implementation.
105589 **
105590 ** When an fts3 table is created, it passes any arguments passed to
105591 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
105592 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
105593 ** implementation. The xCreate() function in turn returns an 
105594 ** sqlite3_tokenizer structure representing the specific tokenizer to
105595 ** be used for the fts3 table (customized by the tokenizer clause arguments).
105596 **
105597 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
105598 ** method is called. It returns an sqlite3_tokenizer_cursor object
105599 ** that may be used to tokenize a specific input buffer based on
105600 ** the tokenization rules supplied by a specific sqlite3_tokenizer
105601 ** object.
105602 */
105603 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
105604 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
105605 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
105606
105607 struct sqlite3_tokenizer_module {
105608
105609   /*
105610   ** Structure version. Should always be set to 0.
105611   */
105612   int iVersion;
105613
105614   /*
105615   ** Create a new tokenizer. The values in the argv[] array are the
105616   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
105617   ** TABLE statement that created the fts3 table. For example, if
105618   ** the following SQL is executed:
105619   **
105620   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
105621   **
105622   ** then argc is set to 2, and the argv[] array contains pointers
105623   ** to the strings "arg1" and "arg2".
105624   **
105625   ** This method should return either SQLITE_OK (0), or an SQLite error 
105626   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
105627   ** to point at the newly created tokenizer structure. The generic
105628   ** sqlite3_tokenizer.pModule variable should not be initialised by
105629   ** this callback. The caller will do so.
105630   */
105631   int (*xCreate)(
105632     int argc,                           /* Size of argv array */
105633     const char *const*argv,             /* Tokenizer argument strings */
105634     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
105635   );
105636
105637   /*
105638   ** Destroy an existing tokenizer. The fts3 module calls this method
105639   ** exactly once for each successful call to xCreate().
105640   */
105641   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
105642
105643   /*
105644   ** Create a tokenizer cursor to tokenize an input buffer. The caller
105645   ** is responsible for ensuring that the input buffer remains valid
105646   ** until the cursor is closed (using the xClose() method). 
105647   */
105648   int (*xOpen)(
105649     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
105650     const char *pInput, int nBytes,      /* Input buffer */
105651     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
105652   );
105653
105654   /*
105655   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
105656   ** method exactly once for each successful call to xOpen().
105657   */
105658   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
105659
105660   /*
105661   ** Retrieve the next token from the tokenizer cursor pCursor. This
105662   ** method should either return SQLITE_OK and set the values of the
105663   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
105664   ** the end of the buffer has been reached, or an SQLite error code.
105665   **
105666   ** *ppToken should be set to point at a buffer containing the 
105667   ** normalized version of the token (i.e. after any case-folding and/or
105668   ** stemming has been performed). *pnBytes should be set to the length
105669   ** of this buffer in bytes. The input text that generated the token is
105670   ** identified by the byte offsets returned in *piStartOffset and
105671   ** *piEndOffset. *piStartOffset should be set to the index of the first
105672   ** byte of the token in the input buffer. *piEndOffset should be set
105673   ** to the index of the first byte just past the end of the token in
105674   ** the input buffer.
105675   **
105676   ** The buffer *ppToken is set to point at is managed by the tokenizer
105677   ** implementation. It is only required to be valid until the next call
105678   ** to xNext() or xClose(). 
105679   */
105680   /* TODO(shess) current implementation requires pInput to be
105681   ** nul-terminated.  This should either be fixed, or pInput/nBytes
105682   ** should be converted to zInput.
105683   */
105684   int (*xNext)(
105685     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
105686     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
105687     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
105688     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
105689     int *piPosition      /* OUT: Number of tokens returned before this one */
105690   );
105691 };
105692
105693 struct sqlite3_tokenizer {
105694   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
105695   /* Tokenizer implementations will typically add additional fields */
105696 };
105697
105698 struct sqlite3_tokenizer_cursor {
105699   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
105700   /* Tokenizer implementations will typically add additional fields */
105701 };
105702
105703 int fts3_global_term_cnt(int iTerm, int iCol);
105704 int fts3_term_cnt(int iTerm, int iCol);
105705
105706
105707 #endif /* _FTS3_TOKENIZER_H_ */
105708
105709 /************** End of fts3_tokenizer.h **************************************/
105710 /************** Continuing where we left off in fts3Int.h ********************/
105711 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
105712 /************** Begin file fts3_hash.h ***************************************/
105713 /*
105714 ** 2001 September 22
105715 **
105716 ** The author disclaims copyright to this source code.  In place of
105717 ** a legal notice, here is a blessing:
105718 **
105719 **    May you do good and not evil.
105720 **    May you find forgiveness for yourself and forgive others.
105721 **    May you share freely, never taking more than you give.
105722 **
105723 *************************************************************************
105724 ** This is the header file for the generic hash-table implemenation
105725 ** used in SQLite.  We've modified it slightly to serve as a standalone
105726 ** hash table implementation for the full-text indexing module.
105727 **
105728 */
105729 #ifndef _FTS3_HASH_H_
105730 #define _FTS3_HASH_H_
105731
105732 /* Forward declarations of structures. */
105733 typedef struct Fts3Hash Fts3Hash;
105734 typedef struct Fts3HashElem Fts3HashElem;
105735
105736 /* A complete hash table is an instance of the following structure.
105737 ** The internals of this structure are intended to be opaque -- client
105738 ** code should not attempt to access or modify the fields of this structure
105739 ** directly.  Change this structure only by using the routines below.
105740 ** However, many of the "procedures" and "functions" for modifying and
105741 ** accessing this structure are really macros, so we can't really make
105742 ** this structure opaque.
105743 */
105744 struct Fts3Hash {
105745   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
105746   char copyKey;           /* True if copy of key made on insert */
105747   int count;              /* Number of entries in this table */
105748   Fts3HashElem *first;    /* The first element of the array */
105749   int htsize;             /* Number of buckets in the hash table */
105750   struct _fts3ht {        /* the hash table */
105751     int count;               /* Number of entries with this hash */
105752     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
105753   } *ht;
105754 };
105755
105756 /* Each element in the hash table is an instance of the following 
105757 ** structure.  All elements are stored on a single doubly-linked list.
105758 **
105759 ** Again, this structure is intended to be opaque, but it can't really
105760 ** be opaque because it is used by macros.
105761 */
105762 struct Fts3HashElem {
105763   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
105764   void *data;                /* Data associated with this element */
105765   void *pKey; int nKey;      /* Key associated with this element */
105766 };
105767
105768 /*
105769 ** There are 2 different modes of operation for a hash table:
105770 **
105771 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
105772 **                           (including the null-terminator, if any).  Case
105773 **                           is respected in comparisons.
105774 **
105775 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
105776 **                           memcmp() is used to compare keys.
105777 **
105778 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
105779 */
105780 #define FTS3_HASH_STRING    1
105781 #define FTS3_HASH_BINARY    2
105782
105783 /*
105784 ** Access routines.  To delete, insert a NULL pointer.
105785 */
105786 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
105787 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
105788 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
105789 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
105790 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
105791
105792 /*
105793 ** Shorthand for the functions above
105794 */
105795 #define fts3HashInit     sqlite3Fts3HashInit
105796 #define fts3HashInsert   sqlite3Fts3HashInsert
105797 #define fts3HashFind     sqlite3Fts3HashFind
105798 #define fts3HashClear    sqlite3Fts3HashClear
105799 #define fts3HashFindElem sqlite3Fts3HashFindElem
105800
105801 /*
105802 ** Macros for looping over all elements of a hash table.  The idiom is
105803 ** like this:
105804 **
105805 **   Fts3Hash h;
105806 **   Fts3HashElem *p;
105807 **   ...
105808 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
105809 **     SomeStructure *pData = fts3HashData(p);
105810 **     // do something with pData
105811 **   }
105812 */
105813 #define fts3HashFirst(H)  ((H)->first)
105814 #define fts3HashNext(E)   ((E)->next)
105815 #define fts3HashData(E)   ((E)->data)
105816 #define fts3HashKey(E)    ((E)->pKey)
105817 #define fts3HashKeysize(E) ((E)->nKey)
105818
105819 /*
105820 ** Number of entries in a hash table
105821 */
105822 #define fts3HashCount(H)  ((H)->count)
105823
105824 #endif /* _FTS3_HASH_H_ */
105825
105826 /************** End of fts3_hash.h *******************************************/
105827 /************** Continuing where we left off in fts3Int.h ********************/
105828
105829 /*
105830 ** This constant controls how often segments are merged. Once there are
105831 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
105832 ** segment of level N+1.
105833 */
105834 #define FTS3_MERGE_COUNT 16
105835
105836 /*
105837 ** This is the maximum amount of data (in bytes) to store in the 
105838 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
105839 ** populated as documents are inserted/updated/deleted in a transaction
105840 ** and used to create a new segment when the transaction is committed.
105841 ** However if this limit is reached midway through a transaction, a new 
105842 ** segment is created and the hash table cleared immediately.
105843 */
105844 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
105845
105846 /*
105847 ** Macro to return the number of elements in an array. SQLite has a
105848 ** similar macro called ArraySize(). Use a different name to avoid
105849 ** a collision when building an amalgamation with built-in FTS3.
105850 */
105851 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
105852
105853 /*
105854 ** Maximum length of a varint encoded integer. The varint format is different
105855 ** from that used by SQLite, so the maximum length is 10, not 9.
105856 */
105857 #define FTS3_VARINT_MAX 10
105858
105859 /*
105860 ** The testcase() macro is only used by the amalgamation.  If undefined,
105861 ** make it a no-op.
105862 */
105863 #ifndef testcase
105864 # define testcase(X)
105865 #endif
105866
105867 /*
105868 ** Terminator values for position-lists and column-lists.
105869 */
105870 #define POS_COLUMN  (1)     /* Column-list terminator */
105871 #define POS_END     (0)     /* Position-list terminator */ 
105872
105873 /*
105874 ** This section provides definitions to allow the
105875 ** FTS3 extension to be compiled outside of the 
105876 ** amalgamation.
105877 */
105878 #ifndef SQLITE_AMALGAMATION
105879 /*
105880 ** Macros indicating that conditional expressions are always true or
105881 ** false.
105882 */
105883 # define ALWAYS(x) (x)
105884 # define NEVER(X)  (x)
105885 /*
105886 ** Internal types used by SQLite.
105887 */
105888 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
105889 typedef short int i16;            /* 2-byte (or larger) signed integer */
105890 typedef unsigned int u32;         /* 4-byte unsigned integer */
105891 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
105892 /*
105893 ** Macro used to suppress compiler warnings for unused parameters.
105894 */
105895 #define UNUSED_PARAMETER(x) (void)(x)
105896 #endif
105897
105898 typedef struct Fts3Table Fts3Table;
105899 typedef struct Fts3Cursor Fts3Cursor;
105900 typedef struct Fts3Expr Fts3Expr;
105901 typedef struct Fts3Phrase Fts3Phrase;
105902 typedef struct Fts3SegReader Fts3SegReader;
105903 typedef struct Fts3SegFilter Fts3SegFilter;
105904
105905 /*
105906 ** A connection to a fulltext index is an instance of the following
105907 ** structure. The xCreate and xConnect methods create an instance
105908 ** of this structure and xDestroy and xDisconnect free that instance.
105909 ** All other methods receive a pointer to the structure as one of their
105910 ** arguments.
105911 */
105912 struct Fts3Table {
105913   sqlite3_vtab base;              /* Base class used by SQLite core */
105914   sqlite3 *db;                    /* The database connection */
105915   const char *zDb;                /* logical database name */
105916   const char *zName;              /* virtual table name */
105917   int nColumn;                    /* number of named columns in virtual table */
105918   char **azColumn;                /* column names.  malloced */
105919   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
105920
105921   /* Precompiled statements used by the implementation. Each of these 
105922   ** statements is run and reset within a single virtual table API call. 
105923   */
105924   sqlite3_stmt *aStmt[25];
105925
105926   /* Pointer to string containing the SQL:
105927   **
105928   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ? 
105929   **    ORDER BY blockid"
105930   */
105931   char *zSelectLeaves;
105932   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
105933   int nLeavesTotal;               /* Total number of prepared leaves stmts */
105934   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
105935   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
105936
105937   int nNodeSize;                  /* Soft limit for node size */
105938   u8 bHasContent;                 /* True if %_content table exists */
105939   u8 bHasDocsize;                 /* True if %_docsize table exists */
105940
105941   /* The following hash table is used to buffer pending index updates during
105942   ** transactions. Variable nPendingData estimates the memory size of the 
105943   ** pending data, including hash table overhead, but not malloc overhead. 
105944   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
105945   ** automatically. Variable iPrevDocid is the docid of the most recently
105946   ** inserted record.
105947   */
105948   int nMaxPendingData;
105949   int nPendingData;
105950   sqlite_int64 iPrevDocid;
105951   Fts3Hash pendingTerms;
105952 };
105953
105954 /*
105955 ** When the core wants to read from the virtual table, it creates a
105956 ** virtual table cursor (an instance of the following structure) using
105957 ** the xOpen method. Cursors are destroyed using the xClose method.
105958 */
105959 struct Fts3Cursor {
105960   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
105961   i16 eSearch;                    /* Search strategy (see below) */
105962   u8 isEof;                       /* True if at End Of Results */
105963   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
105964   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
105965   Fts3Expr *pExpr;                /* Parsed MATCH query string */
105966   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
105967   char *pNextId;                  /* Pointer into the body of aDoclist */
105968   char *aDoclist;                 /* List of docids for full-text queries */
105969   int nDoclist;                   /* Size of buffer at aDoclist */
105970   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
105971   u32 *aMatchinfo;                /* Information about most recent match */
105972 };
105973
105974 /*
105975 ** The Fts3Cursor.eSearch member is always set to one of the following.
105976 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
105977 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
105978 ** of the column to be searched.  For example, in
105979 **
105980 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
105981 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
105982 ** 
105983 ** Because the LHS of the MATCH operator is 2nd column "b",
105984 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
105985 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
105986 ** indicating that all columns should be searched,
105987 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
105988 */
105989 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
105990 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
105991 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
105992
105993 /*
105994 ** A "phrase" is a sequence of one or more tokens that must match in
105995 ** sequence.  A single token is the base case and the most common case.
105996 ** For a sequence of tokens contained in "...", nToken will be the number
105997 ** of tokens in the string.
105998 */
105999 struct Fts3Phrase {
106000   int nToken;                /* Number of tokens in the phrase */
106001   int iColumn;               /* Index of column this phrase must match */
106002   int isNot;                 /* Phrase prefixed by unary not (-) operator */
106003   struct PhraseToken {
106004     char *z;                 /* Text of the token */
106005     int n;                   /* Number of bytes in buffer pointed to by z */
106006     int isPrefix;            /* True if token ends in with a "*" character */
106007   } aToken[1];               /* One entry for each token in the phrase */
106008 };
106009
106010 /*
106011 ** A tree of these objects forms the RHS of a MATCH operator.
106012 **
106013 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
106014 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
106015 ** containing the results of the NEAR or phrase query in FTS3 doclist
106016 ** format. As usual, the initial "Length" field found in doclists stored
106017 ** on disk is omitted from this buffer.
106018 **
106019 ** Variable pCurrent always points to the start of a docid field within
106020 ** aDoclist. Since the doclist is usually scanned in docid order, this can
106021 ** be used to accelerate seeking to the required docid within the doclist.
106022 */
106023 struct Fts3Expr {
106024   int eType;                 /* One of the FTSQUERY_XXX values defined below */
106025   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
106026   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
106027   Fts3Expr *pLeft;           /* Left operand */
106028   Fts3Expr *pRight;          /* Right operand */
106029   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
106030
106031   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
106032   char *aDoclist;            /* Buffer containing doclist */
106033   int nDoclist;              /* Size of aDoclist in bytes */
106034
106035   sqlite3_int64 iCurrent;
106036   char *pCurrent;
106037 };
106038
106039 /*
106040 ** Candidate values for Fts3Query.eType. Note that the order of the first
106041 ** four values is in order of precedence when parsing expressions. For 
106042 ** example, the following:
106043 **
106044 **   "a OR b AND c NOT d NEAR e"
106045 **
106046 ** is equivalent to:
106047 **
106048 **   "a OR (b AND (c NOT (d NEAR e)))"
106049 */
106050 #define FTSQUERY_NEAR   1
106051 #define FTSQUERY_NOT    2
106052 #define FTSQUERY_AND    3
106053 #define FTSQUERY_OR     4
106054 #define FTSQUERY_PHRASE 5
106055
106056
106057 /* fts3_init.c */
106058 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
106059 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*, 
106060                         sqlite3_vtab **, char **);
106061
106062 /* fts3_write.c */
106063 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
106064 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
106065 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
106066 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
106067 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
106068   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
106069 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
106070 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
106071 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
106072   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
106073   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
106074 );
106075 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
106076 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
106077 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
106078 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
106079
106080 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
106081 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
106082 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
106083 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
106084 #define FTS3_SEGMENT_PREFIX        0x00000008
106085
106086 /* Type passed as 4th argument to SegmentReaderIterate() */
106087 struct Fts3SegFilter {
106088   const char *zTerm;
106089   int nTerm;
106090   int iCol;
106091   int flags;
106092 };
106093
106094 /* fts3.c */
106095 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
106096 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
106097 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
106098 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
106099 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
106100
106101 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
106102 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
106103 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
106104
106105 /* fts3_tokenizer.c */
106106 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
106107 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
106108 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, 
106109   const char *, sqlite3_tokenizer **, const char **, char **
106110 );
106111
106112 /* fts3_snippet.c */
106113 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
106114 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
106115   const char *, const char *, int, int
106116 );
106117 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
106118
106119 /* fts3_expr.c */
106120 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
106121   char **, int, int, const char *, int, Fts3Expr **
106122 );
106123 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
106124 #ifdef SQLITE_TEST
106125 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
106126 #endif
106127
106128 #endif /* _FTSINT_H */
106129
106130 /************** End of fts3Int.h *********************************************/
106131 /************** Continuing where we left off in fts3.c ***********************/
106132
106133
106134 #ifndef SQLITE_CORE 
106135   SQLITE_EXTENSION_INIT1
106136 #endif
106137
106138 /* 
106139 ** Write a 64-bit variable-length integer to memory starting at p[0].
106140 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
106141 ** The number of bytes written is returned.
106142 */
106143 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
106144   unsigned char *q = (unsigned char *) p;
106145   sqlite_uint64 vu = v;
106146   do{
106147     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
106148     vu >>= 7;
106149   }while( vu!=0 );
106150   q[-1] &= 0x7f;  /* turn off high bit in final byte */
106151   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
106152   return (int) (q - (unsigned char *)p);
106153 }
106154
106155 /* 
106156 ** Read a 64-bit variable-length integer from memory starting at p[0].
106157 ** Return the number of bytes read, or 0 on error.
106158 ** The value is stored in *v.
106159 */
106160 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
106161   const unsigned char *q = (const unsigned char *) p;
106162   sqlite_uint64 x = 0, y = 1;
106163   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
106164     x += y * (*q++ & 0x7f);
106165     y <<= 7;
106166   }
106167   x += y * (*q++);
106168   *v = (sqlite_int64) x;
106169   return (int) (q - (unsigned char *)p);
106170 }
106171
106172 /*
106173 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
106174 ** 32-bit integer before it is returned.
106175 */
106176 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
106177  sqlite_int64 i;
106178  int ret = sqlite3Fts3GetVarint(p, &i);
106179  *pi = (int) i;
106180  return ret;
106181 }
106182
106183 /*
106184 ** Return the number of bytes required to encode v as a varint
106185 */
106186 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
106187   int i = 0;
106188   do{
106189     i++;
106190     v >>= 7;
106191   }while( v!=0 );
106192   return i;
106193 }
106194
106195 /*
106196 ** Convert an SQL-style quoted string into a normal string by removing
106197 ** the quote characters.  The conversion is done in-place.  If the
106198 ** input does not begin with a quote character, then this routine
106199 ** is a no-op.
106200 **
106201 ** Examples:
106202 **
106203 **     "abc"   becomes   abc
106204 **     'xyz'   becomes   xyz
106205 **     [pqr]   becomes   pqr
106206 **     `mno`   becomes   mno
106207 **
106208 */
106209 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
106210   char quote;                     /* Quote character (if any ) */
106211
106212   quote = z[0];
106213   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
106214     int iIn = 1;                  /* Index of next byte to read from input */
106215     int iOut = 0;                 /* Index of next byte to write to output */
106216
106217     /* If the first byte was a '[', then the close-quote character is a ']' */
106218     if( quote=='[' ) quote = ']';  
106219
106220     while( ALWAYS(z[iIn]) ){
106221       if( z[iIn]==quote ){
106222         if( z[iIn+1]!=quote ) break;
106223         z[iOut++] = quote;
106224         iIn += 2;
106225       }else{
106226         z[iOut++] = z[iIn++];
106227       }
106228     }
106229     z[iOut] = '\0';
106230   }
106231 }
106232
106233 /*
106234 ** Read a single varint from the doclist at *pp and advance *pp to point
106235 ** to the first byte past the end of the varint.  Add the value of the varint
106236 ** to *pVal.
106237 */
106238 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
106239   sqlite3_int64 iVal;
106240   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
106241   *pVal += iVal;
106242 }
106243
106244 /*
106245 ** As long as *pp has not reached its end (pEnd), then do the same
106246 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
106247 ** But if we have reached the end of the varint, just set *pp=0 and
106248 ** leave *pVal unchanged.
106249 */
106250 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
106251   if( *pp>=pEnd ){
106252     *pp = 0;
106253   }else{
106254     fts3GetDeltaVarint(pp, pVal);
106255   }
106256 }
106257
106258 /*
106259 ** The xDisconnect() virtual table method.
106260 */
106261 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
106262   Fts3Table *p = (Fts3Table *)pVtab;
106263   int i;
106264
106265   assert( p->nPendingData==0 );
106266
106267   /* Free any prepared statements held */
106268   for(i=0; i<SizeofArray(p->aStmt); i++){
106269     sqlite3_finalize(p->aStmt[i]);
106270   }
106271   for(i=0; i<p->nLeavesStmt; i++){
106272     sqlite3_finalize(p->aLeavesStmt[i]);
106273   }
106274   sqlite3_free(p->zSelectLeaves);
106275   sqlite3_free(p->aLeavesStmt);
106276
106277   /* Invoke the tokenizer destructor to free the tokenizer. */
106278   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
106279
106280   sqlite3_free(p);
106281   return SQLITE_OK;
106282 }
106283
106284 /*
106285 ** Construct one or more SQL statements from the format string given
106286 ** and then evaluate those statements.  The success code is writting
106287 ** into *pRc.
106288 **
106289 ** If *pRc is initially non-zero then this routine is a no-op.
106290 */
106291 static void fts3DbExec(
106292   int *pRc,              /* Success code */
106293   sqlite3 *db,           /* Database in which to run SQL */
106294   const char *zFormat,   /* Format string for SQL */
106295   ...                    /* Arguments to the format string */
106296 ){
106297   va_list ap;
106298   char *zSql;
106299   if( *pRc ) return;
106300   va_start(ap, zFormat);
106301   zSql = sqlite3_vmprintf(zFormat, ap);
106302   va_end(ap);
106303   if( zSql==0 ){
106304     *pRc = SQLITE_NOMEM;
106305   }else{
106306     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
106307     sqlite3_free(zSql);
106308   }
106309 }
106310
106311 /*
106312 ** The xDestroy() virtual table method.
106313 */
106314 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
106315   int rc = SQLITE_OK;              /* Return code */
106316   Fts3Table *p = (Fts3Table *)pVtab;
106317   sqlite3 *db = p->db;
106318
106319   /* Drop the shadow tables */
106320   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
106321   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
106322   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
106323   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
106324   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
106325
106326   /* If everything has worked, invoke fts3DisconnectMethod() to free the
106327   ** memory associated with the Fts3Table structure and return SQLITE_OK.
106328   ** Otherwise, return an SQLite error code.
106329   */
106330   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
106331 }
106332
106333
106334 /*
106335 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
106336 ** passed as the first argument. This is done as part of the xConnect()
106337 ** and xCreate() methods.
106338 */
106339 static int fts3DeclareVtab(Fts3Table *p){
106340   int i;                          /* Iterator variable */
106341   int rc;                         /* Return code */
106342   char *zSql;                     /* SQL statement passed to declare_vtab() */
106343   char *zCols;                    /* List of user defined columns */
106344
106345   /* Create a list of user columns for the virtual table */
106346   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
106347   for(i=1; zCols && i<p->nColumn; i++){
106348     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
106349   }
106350
106351   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
106352   zSql = sqlite3_mprintf(
106353       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
106354   );
106355
106356   if( !zCols || !zSql ){
106357     rc = SQLITE_NOMEM;
106358   }else{
106359     rc = sqlite3_declare_vtab(p->db, zSql);
106360   }
106361
106362   sqlite3_free(zSql);
106363   sqlite3_free(zCols);
106364   return rc;
106365 }
106366
106367 /*
106368 ** Create the backing store tables (%_content, %_segments and %_segdir)
106369 ** required by the FTS3 table passed as the only argument. This is done
106370 ** as part of the vtab xCreate() method.
106371 **
106372 ** If the p->bHasDocsize boolean is true (indicating that this is an
106373 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
106374 ** %_stat tables required by FTS4.
106375 */
106376 static int fts3CreateTables(Fts3Table *p){
106377   int rc = SQLITE_OK;             /* Return code */
106378   int i;                          /* Iterator variable */
106379   char *zContentCols;             /* Columns of %_content table */
106380   sqlite3 *db = p->db;            /* The database connection */
106381
106382   /* Create a list of user columns for the content table */
106383   if( p->bHasContent ){
106384     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
106385     for(i=0; zContentCols && i<p->nColumn; i++){
106386       char *z = p->azColumn[i];
106387       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
106388     }
106389     if( zContentCols==0 ) rc = SQLITE_NOMEM;
106390
106391     /* Create the content table */
106392     fts3DbExec(&rc, db, 
106393        "CREATE TABLE %Q.'%q_content'(%s)",
106394        p->zDb, p->zName, zContentCols
106395     );
106396     sqlite3_free(zContentCols);
106397   }
106398   /* Create other tables */
106399   fts3DbExec(&rc, db, 
106400       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
106401       p->zDb, p->zName
106402   );
106403   fts3DbExec(&rc, db, 
106404       "CREATE TABLE %Q.'%q_segdir'("
106405         "level INTEGER,"
106406         "idx INTEGER,"
106407         "start_block INTEGER,"
106408         "leaves_end_block INTEGER,"
106409         "end_block INTEGER,"
106410         "root BLOB,"
106411         "PRIMARY KEY(level, idx)"
106412       ");",
106413       p->zDb, p->zName
106414   );
106415   if( p->bHasDocsize ){
106416     fts3DbExec(&rc, db, 
106417         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
106418         p->zDb, p->zName
106419     );
106420     fts3DbExec(&rc, db, 
106421         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
106422         p->zDb, p->zName
106423     );
106424   }
106425   return rc;
106426 }
106427
106428 /*
106429 ** An sqlite3_exec() callback for fts3TableExists.
106430 */
106431 static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
106432   UNUSED_PARAMETER(n);
106433   UNUSED_PARAMETER(pp1);
106434   UNUSED_PARAMETER(pp2);
106435   *(int*)pArg = 1;
106436   return 1;
106437 }
106438
106439 /*
106440 ** Determine if a table currently exists in the database.
106441 */
106442 static void fts3TableExists(
106443   int *pRc,             /* Success code */
106444   sqlite3 *db,          /* The database connection to test */
106445   const char *zDb,      /* ATTACHed database within the connection */
106446   const char *zName,    /* Name of the FTS3 table */
106447   const char *zSuffix,  /* Shadow table extension */
106448   u8 *pResult           /* Write results here */
106449 ){
106450   int rc = SQLITE_OK;
106451   int res = 0;
106452   char *zSql;
106453   if( *pRc ) return;
106454   zSql = sqlite3_mprintf(
106455     "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
106456     zDb, zName, zSuffix
106457   );    
106458   rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
106459   sqlite3_free(zSql);
106460   *pResult = (u8)(res & 0xff);
106461   if( rc!=SQLITE_ABORT ) *pRc = rc;
106462 }
106463
106464 /*
106465 ** This function is the implementation of both the xConnect and xCreate
106466 ** methods of the FTS3 virtual table.
106467 **
106468 ** The argv[] array contains the following:
106469 **
106470 **   argv[0]   -> module name  ("fts3" or "fts4")
106471 **   argv[1]   -> database name
106472 **   argv[2]   -> table name
106473 **   argv[...] -> "column name" and other module argument fields.
106474 */
106475 static int fts3InitVtab(
106476   int isCreate,                   /* True for xCreate, false for xConnect */
106477   sqlite3 *db,                    /* The SQLite database connection */
106478   void *pAux,                     /* Hash table containing tokenizers */
106479   int argc,                       /* Number of elements in argv array */
106480   const char * const *argv,       /* xCreate/xConnect argument array */
106481   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
106482   char **pzErr                    /* Write any error message here */
106483 ){
106484   Fts3Hash *pHash = (Fts3Hash *)pAux;
106485   Fts3Table *p;                   /* Pointer to allocated vtab */
106486   int rc;                         /* Return code */
106487   int i;                          /* Iterator variable */
106488   int nByte;                      /* Size of allocation used for *p */
106489   int iCol;                       /* Column index */
106490   int nString = 0;                /* Bytes required to hold all column names */
106491   int nCol = 0;                   /* Number of columns in the FTS table */
106492   char *zCsr;                     /* Space for holding column names */
106493   int nDb;                        /* Bytes required to hold database name */
106494   int nName;                      /* Bytes required to hold table name */
106495
106496   const char *zTokenizer = 0;               /* Name of tokenizer to use */
106497   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
106498
106499   nDb = (int)strlen(argv[1]) + 1;
106500   nName = (int)strlen(argv[2]) + 1;
106501   for(i=3; i<argc; i++){
106502     char const *z = argv[i];
106503     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
106504     if( rc!=SQLITE_OK ){
106505       return rc;
106506     }
106507     if( z!=zTokenizer ){
106508       nString += (int)(strlen(z) + 1);
106509     }
106510   }
106511   nCol = argc - 3 - (zTokenizer!=0);
106512   if( zTokenizer==0 ){
106513     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
106514     if( rc!=SQLITE_OK ){
106515       return rc;
106516     }
106517     assert( pTokenizer );
106518   }
106519
106520   if( nCol==0 ){
106521     nCol = 1;
106522   }
106523
106524   /* Allocate and populate the Fts3Table structure. */
106525   nByte = sizeof(Fts3Table) +              /* Fts3Table */
106526           nCol * sizeof(char *) +              /* azColumn */
106527           nName +                              /* zName */
106528           nDb +                                /* zDb */
106529           nString;                             /* Space for azColumn strings */
106530   p = (Fts3Table*)sqlite3_malloc(nByte);
106531   if( p==0 ){
106532     rc = SQLITE_NOMEM;
106533     goto fts3_init_out;
106534   }
106535   memset(p, 0, nByte);
106536
106537   p->db = db;
106538   p->nColumn = nCol;
106539   p->nPendingData = 0;
106540   p->azColumn = (char **)&p[1];
106541   p->pTokenizer = pTokenizer;
106542   p->nNodeSize = 1000;
106543   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
106544   zCsr = (char *)&p->azColumn[nCol];
106545
106546   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
106547
106548   /* Fill in the zName and zDb fields of the vtab structure. */
106549   p->zName = zCsr;
106550   memcpy(zCsr, argv[2], nName);
106551   zCsr += nName;
106552   p->zDb = zCsr;
106553   memcpy(zCsr, argv[1], nDb);
106554   zCsr += nDb;
106555
106556   /* Fill in the azColumn array */
106557   iCol = 0;
106558   for(i=3; i<argc; i++){
106559     if( argv[i]!=zTokenizer ){
106560       char *z; 
106561       int n;
106562       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
106563       memcpy(zCsr, z, n);
106564       zCsr[n] = '\0';
106565       sqlite3Fts3Dequote(zCsr);
106566       p->azColumn[iCol++] = zCsr;
106567       zCsr += n+1;
106568       assert( zCsr <= &((char *)p)[nByte] );
106569     }
106570   }
106571   if( iCol==0 ){
106572     assert( nCol==1 );
106573     p->azColumn[0] = "content";
106574   }
106575
106576   /* If this is an xCreate call, create the underlying tables in the 
106577   ** database. TODO: For xConnect(), it could verify that said tables exist.
106578   */
106579   if( isCreate ){
106580     p->bHasContent = 1;
106581     p->bHasDocsize = argv[0][3]=='4';
106582     rc = fts3CreateTables(p);
106583   }else{
106584     rc = SQLITE_OK;
106585     fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
106586     fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
106587   }
106588   if( rc!=SQLITE_OK ) goto fts3_init_out;
106589
106590   rc = fts3DeclareVtab(p);
106591   if( rc!=SQLITE_OK ) goto fts3_init_out;
106592
106593   *ppVTab = &p->base;
106594
106595 fts3_init_out:
106596   assert( p || (pTokenizer && rc!=SQLITE_OK) );
106597   if( rc!=SQLITE_OK ){
106598     if( p ){
106599       fts3DisconnectMethod((sqlite3_vtab *)p);
106600     }else{
106601       pTokenizer->pModule->xDestroy(pTokenizer);
106602     }
106603   }
106604   return rc;
106605 }
106606
106607 /*
106608 ** The xConnect() and xCreate() methods for the virtual table. All the
106609 ** work is done in function fts3InitVtab().
106610 */
106611 static int fts3ConnectMethod(
106612   sqlite3 *db,                    /* Database connection */
106613   void *pAux,                     /* Pointer to tokenizer hash table */
106614   int argc,                       /* Number of elements in argv array */
106615   const char * const *argv,       /* xCreate/xConnect argument array */
106616   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106617   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106618 ){
106619   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
106620 }
106621 static int fts3CreateMethod(
106622   sqlite3 *db,                    /* Database connection */
106623   void *pAux,                     /* Pointer to tokenizer hash table */
106624   int argc,                       /* Number of elements in argv array */
106625   const char * const *argv,       /* xCreate/xConnect argument array */
106626   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106627   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106628 ){
106629   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
106630 }
106631
106632 /* 
106633 ** Implementation of the xBestIndex method for FTS3 tables. There
106634 ** are three possible strategies, in order of preference:
106635 **
106636 **   1. Direct lookup by rowid or docid. 
106637 **   2. Full-text search using a MATCH operator on a non-docid column.
106638 **   3. Linear scan of %_content table.
106639 */
106640 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
106641   Fts3Table *p = (Fts3Table *)pVTab;
106642   int i;                          /* Iterator variable */
106643   int iCons = -1;                 /* Index of constraint to use */
106644
106645   /* By default use a full table scan. This is an expensive option,
106646   ** so search through the constraints to see if a more efficient 
106647   ** strategy is possible.
106648   */
106649   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
106650   pInfo->estimatedCost = 500000;
106651   for(i=0; i<pInfo->nConstraint; i++){
106652     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
106653     if( pCons->usable==0 ) continue;
106654
106655     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
106656     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
106657      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
106658     ){
106659       pInfo->idxNum = FTS3_DOCID_SEARCH;
106660       pInfo->estimatedCost = 1.0;
106661       iCons = i;
106662     }
106663
106664     /* A MATCH constraint. Use a full-text search.
106665     **
106666     ** If there is more than one MATCH constraint available, use the first
106667     ** one encountered. If there is both a MATCH constraint and a direct
106668     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
106669     ** though the rowid/docid lookup is faster than a MATCH query, selecting
106670     ** it would lead to an "unable to use function MATCH in the requested 
106671     ** context" error.
106672     */
106673     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
106674      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
106675     ){
106676       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
106677       pInfo->estimatedCost = 2.0;
106678       iCons = i;
106679       break;
106680     }
106681   }
106682
106683   if( iCons>=0 ){
106684     pInfo->aConstraintUsage[iCons].argvIndex = 1;
106685     pInfo->aConstraintUsage[iCons].omit = 1;
106686   } 
106687   return SQLITE_OK;
106688 }
106689
106690 /*
106691 ** Implementation of xOpen method.
106692 */
106693 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
106694   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
106695
106696   UNUSED_PARAMETER(pVTab);
106697
106698   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
106699   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
106700   ** if the allocation fails, return SQLITE_NOMEM.
106701   */
106702   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
106703   if( !pCsr ){
106704     return SQLITE_NOMEM;
106705   }
106706   memset(pCsr, 0, sizeof(Fts3Cursor));
106707   return SQLITE_OK;
106708 }
106709
106710 /*
106711 ** Close the cursor.  For additional information see the documentation
106712 ** on the xClose method of the virtual table interface.
106713 */
106714 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
106715   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106716   sqlite3_finalize(pCsr->pStmt);
106717   sqlite3Fts3ExprFree(pCsr->pExpr);
106718   sqlite3_free(pCsr->aDoclist);
106719   sqlite3_free(pCsr->aMatchinfo);
106720   sqlite3_free(pCsr);
106721   return SQLITE_OK;
106722 }
106723
106724 /*
106725 ** Position the pCsr->pStmt statement so that it is on the row
106726 ** of the %_content table that contains the last match.  Return
106727 ** SQLITE_OK on success.  
106728 */
106729 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
106730   if( pCsr->isRequireSeek ){
106731     pCsr->isRequireSeek = 0;
106732     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
106733     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
106734       return SQLITE_OK;
106735     }else{
106736       int rc = sqlite3_reset(pCsr->pStmt);
106737       if( rc==SQLITE_OK ){
106738         /* If no row was found and no error has occured, then the %_content
106739         ** table is missing a row that is present in the full-text index.
106740         ** The data structures are corrupt.
106741         */
106742         rc = SQLITE_CORRUPT;
106743       }
106744       pCsr->isEof = 1;
106745       if( pContext ){
106746         sqlite3_result_error_code(pContext, rc);
106747       }
106748       return rc;
106749     }
106750   }else{
106751     return SQLITE_OK;
106752   }
106753 }
106754
106755 /*
106756 ** Advance the cursor to the next row in the %_content table that
106757 ** matches the search criteria.  For a MATCH search, this will be
106758 ** the next row that matches.  For a full-table scan, this will be
106759 ** simply the next row in the %_content table.  For a docid lookup,
106760 ** this routine simply sets the EOF flag.
106761 **
106762 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
106763 ** even if we reach end-of-file.  The fts3EofMethod() will be called
106764 ** subsequently to determine whether or not an EOF was hit.
106765 */
106766 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
106767   int rc = SQLITE_OK;             /* Return code */
106768   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106769
106770   if( pCsr->aDoclist==0 ){
106771     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
106772       pCsr->isEof = 1;
106773       rc = sqlite3_reset(pCsr->pStmt);
106774     }
106775   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
106776     pCsr->isEof = 1;
106777   }else{
106778     sqlite3_reset(pCsr->pStmt);
106779     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
106780     pCsr->isRequireSeek = 1;
106781     pCsr->isMatchinfoNeeded = 1;
106782   }
106783   return rc;
106784 }
106785
106786
106787 /*
106788 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
106789 ** root node of a b-tree segment. The segment is guaranteed to be at least
106790 ** one level high (i.e. the root node is not also a leaf). If successful,
106791 ** this function locates the leaf node of the segment that may contain the 
106792 ** term specified by arguments zTerm and nTerm and writes its block number 
106793 ** to *piLeaf.
106794 **
106795 ** It is possible that the returned leaf node does not contain the specified
106796 ** term. However, if the segment does contain said term, it is stored on
106797 ** the identified leaf node. Because this function only inspects interior
106798 ** segment nodes (and never loads leaf nodes into memory), it is not possible
106799 ** to be sure.
106800 **
106801 ** If an error occurs, an error code other than SQLITE_OK is returned.
106802 */ 
106803 static int fts3SelectLeaf(
106804   Fts3Table *p,                   /* Virtual table handle */
106805   const char *zTerm,              /* Term to select leaves for */
106806   int nTerm,                      /* Size of term zTerm in bytes */
106807   const char *zNode,              /* Buffer containing segment interior node */
106808   int nNode,                      /* Size of buffer at zNode */
106809   sqlite3_int64 *piLeaf           /* Selected leaf node */
106810 ){
106811   int rc = SQLITE_OK;             /* Return code */
106812   const char *zCsr = zNode;       /* Cursor to iterate through node */
106813   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
106814   char *zBuffer = 0;              /* Buffer to load terms into */
106815   int nAlloc = 0;                 /* Size of allocated buffer */
106816
106817   while( 1 ){
106818     int isFirstTerm = 1;          /* True when processing first term on page */
106819     int iHeight;                  /* Height of this node in tree */
106820     sqlite3_int64 iChild;         /* Block id of child node to descend to */
106821     int nBlock;                   /* Size of child node in bytes */
106822
106823     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
106824     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
106825   
106826     while( zCsr<zEnd ){
106827       int cmp;                    /* memcmp() result */
106828       int nSuffix;                /* Size of term suffix */
106829       int nPrefix = 0;            /* Size of term prefix */
106830       int nBuffer;                /* Total term size */
106831   
106832       /* Load the next term on the node into zBuffer */
106833       if( !isFirstTerm ){
106834         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
106835       }
106836       isFirstTerm = 0;
106837       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
106838       if( nPrefix+nSuffix>nAlloc ){
106839         char *zNew;
106840         nAlloc = (nPrefix+nSuffix) * 2;
106841         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
106842         if( !zNew ){
106843           sqlite3_free(zBuffer);
106844           return SQLITE_NOMEM;
106845         }
106846         zBuffer = zNew;
106847       }
106848       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
106849       nBuffer = nPrefix + nSuffix;
106850       zCsr += nSuffix;
106851   
106852       /* Compare the term we are searching for with the term just loaded from
106853       ** the interior node. If the specified term is greater than or equal
106854       ** to the term from the interior node, then all terms on the sub-tree 
106855       ** headed by node iChild are smaller than zTerm. No need to search 
106856       ** iChild.
106857       **
106858       ** If the interior node term is larger than the specified term, then
106859       ** the tree headed by iChild may contain the specified term.
106860       */
106861       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
106862       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
106863       iChild++;
106864     };
106865
106866     /* If (iHeight==1), the children of this interior node are leaves. The
106867     ** specified term may be present on leaf node iChild.
106868     */
106869     if( iHeight==1 ){
106870       *piLeaf = iChild;
106871       break;
106872     }
106873
106874     /* Descend to interior node iChild. */
106875     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
106876     if( rc!=SQLITE_OK ) break;
106877     zEnd = &zCsr[nBlock];
106878   }
106879   sqlite3_free(zBuffer);
106880   return rc;
106881 }
106882
106883 /*
106884 ** This function is used to create delta-encoded serialized lists of FTS3 
106885 ** varints. Each call to this function appends a single varint to a list.
106886 */
106887 static void fts3PutDeltaVarint(
106888   char **pp,                      /* IN/OUT: Output pointer */
106889   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
106890   sqlite3_int64 iVal              /* Write this value to the list */
106891 ){
106892   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
106893   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
106894   *piPrev = iVal;
106895 }
106896
106897 /*
106898 ** When this function is called, *ppPoslist is assumed to point to the 
106899 ** start of a position-list. After it returns, *ppPoslist points to the
106900 ** first byte after the position-list.
106901 **
106902 ** A position list is list of positions (delta encoded) and columns for 
106903 ** a single document record of a doclist.  So, in other words, this
106904 ** routine advances *ppPoslist so that it points to the next docid in
106905 ** the doclist, or to the first byte past the end of the doclist.
106906 **
106907 ** If pp is not NULL, then the contents of the position list are copied
106908 ** to *pp. *pp is set to point to the first byte past the last byte copied
106909 ** before this function returns.
106910 */
106911 static void fts3PoslistCopy(char **pp, char **ppPoslist){
106912   char *pEnd = *ppPoslist;
106913   char c = 0;
106914
106915   /* The end of a position list is marked by a zero encoded as an FTS3 
106916   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
106917   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
106918   ** of some other, multi-byte, value.
106919   **
106920   ** The following while-loop moves pEnd to point to the first byte that is not 
106921   ** immediately preceded by a byte with the 0x80 bit set. Then increments
106922   ** pEnd once more so that it points to the byte immediately following the
106923   ** last byte in the position-list.
106924   */
106925   while( *pEnd | c ){
106926     c = *pEnd++ & 0x80;
106927     testcase( c!=0 && (*pEnd)==0 );
106928   }
106929   pEnd++;  /* Advance past the POS_END terminator byte */
106930
106931   if( pp ){
106932     int n = (int)(pEnd - *ppPoslist);
106933     char *p = *pp;
106934     memcpy(p, *ppPoslist, n);
106935     p += n;
106936     *pp = p;
106937   }
106938   *ppPoslist = pEnd;
106939 }
106940
106941 /*
106942 ** When this function is called, *ppPoslist is assumed to point to the 
106943 ** start of a column-list. After it returns, *ppPoslist points to the
106944 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
106945 **
106946 ** A column-list is list of delta-encoded positions for a single column
106947 ** within a single document within a doclist.
106948 **
106949 ** The column-list is terminated either by a POS_COLUMN varint (1) or
106950 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
106951 ** the POS_COLUMN or POS_END that terminates the column-list.
106952 **
106953 ** If pp is not NULL, then the contents of the column-list are copied
106954 ** to *pp. *pp is set to point to the first byte past the last byte copied
106955 ** before this function returns.  The POS_COLUMN or POS_END terminator
106956 ** is not copied into *pp.
106957 */
106958 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
106959   char *pEnd = *ppPoslist;
106960   char c = 0;
106961
106962   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
106963   ** not part of a multi-byte varint.
106964   */
106965   while( 0xFE & (*pEnd | c) ){
106966     c = *pEnd++ & 0x80;
106967     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
106968   }
106969   if( pp ){
106970     int n = (int)(pEnd - *ppPoslist);
106971     char *p = *pp;
106972     memcpy(p, *ppPoslist, n);
106973     p += n;
106974     *pp = p;
106975   }
106976   *ppPoslist = pEnd;
106977 }
106978
106979 /*
106980 ** Value used to signify the end of an position-list. This is safe because
106981 ** it is not possible to have a document with 2^31 terms.
106982 */
106983 #define POSITION_LIST_END 0x7fffffff
106984
106985 /*
106986 ** This function is used to help parse position-lists. When this function is
106987 ** called, *pp may point to the start of the next varint in the position-list
106988 ** being parsed, or it may point to 1 byte past the end of the position-list
106989 ** (in which case **pp will be a terminator bytes POS_END (0) or
106990 ** (1)).
106991 **
106992 ** If *pp points past the end of the current position-list, set *pi to 
106993 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
106994 ** increment the current value of *pi by the value read, and set *pp to
106995 ** point to the next value before returning.
106996 **
106997 ** Before calling this routine *pi must be initialized to the value of
106998 ** the previous position, or zero if we are reading the first position
106999 ** in the position-list.  Because positions are delta-encoded, the value
107000 ** of the previous position is needed in order to compute the value of
107001 ** the next position.
107002 */
107003 static void fts3ReadNextPos(
107004   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
107005   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
107006 ){
107007   if( (**pp)&0xFE ){
107008     fts3GetDeltaVarint(pp, pi);
107009     *pi -= 2;
107010   }else{
107011     *pi = POSITION_LIST_END;
107012   }
107013 }
107014
107015 /*
107016 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
107017 ** the value of iCol encoded as a varint to *pp.   This will start a new
107018 ** column list.
107019 **
107020 ** Set *pp to point to the byte just after the last byte written before 
107021 ** returning (do not modify it if iCol==0). Return the total number of bytes
107022 ** written (0 if iCol==0).
107023 */
107024 static int fts3PutColNumber(char **pp, int iCol){
107025   int n = 0;                      /* Number of bytes written */
107026   if( iCol ){
107027     char *p = *pp;                /* Output pointer */
107028     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
107029     *p = 0x01;
107030     *pp = &p[n];
107031   }
107032   return n;
107033 }
107034
107035 /*
107036 ** Compute the union of two position lists.  The output written
107037 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
107038 ** order and with any duplicates removed.  All pointers are
107039 ** updated appropriately.   The caller is responsible for insuring
107040 ** that there is enough space in *pp to hold the complete output.
107041 */
107042 static void fts3PoslistMerge(
107043   char **pp,                      /* Output buffer */
107044   char **pp1,                     /* Left input list */
107045   char **pp2                      /* Right input list */
107046 ){
107047   char *p = *pp;
107048   char *p1 = *pp1;
107049   char *p2 = *pp2;
107050
107051   while( *p1 || *p2 ){
107052     int iCol1;         /* The current column index in pp1 */
107053     int iCol2;         /* The current column index in pp2 */
107054
107055     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
107056     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
107057     else iCol1 = 0;
107058
107059     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
107060     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
107061     else iCol2 = 0;
107062
107063     if( iCol1==iCol2 ){
107064       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
107065       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
107066       sqlite3_int64 iPrev = 0;
107067       int n = fts3PutColNumber(&p, iCol1);
107068       p1 += n;
107069       p2 += n;
107070
107071       /* At this point, both p1 and p2 point to the start of column-lists
107072       ** for the same column (the column with index iCol1 and iCol2).
107073       ** A column-list is a list of non-negative delta-encoded varints, each 
107074       ** incremented by 2 before being stored. Each list is terminated by a
107075       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
107076       ** and writes the results to buffer p. p is left pointing to the byte
107077       ** after the list written. No terminator (POS_END or POS_COLUMN) is
107078       ** written to the output.
107079       */
107080       fts3GetDeltaVarint(&p1, &i1);
107081       fts3GetDeltaVarint(&p2, &i2);
107082       do {
107083         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
107084         iPrev -= 2;
107085         if( i1==i2 ){
107086           fts3ReadNextPos(&p1, &i1);
107087           fts3ReadNextPos(&p2, &i2);
107088         }else if( i1<i2 ){
107089           fts3ReadNextPos(&p1, &i1);
107090         }else{
107091           fts3ReadNextPos(&p2, &i2);
107092         }
107093       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
107094     }else if( iCol1<iCol2 ){
107095       p1 += fts3PutColNumber(&p, iCol1);
107096       fts3ColumnlistCopy(&p, &p1);
107097     }else{
107098       p2 += fts3PutColNumber(&p, iCol2);
107099       fts3ColumnlistCopy(&p, &p2);
107100     }
107101   }
107102
107103   *p++ = POS_END;
107104   *pp = p;
107105   *pp1 = p1 + 1;
107106   *pp2 = p2 + 1;
107107 }
107108
107109 /*
107110 ** nToken==1 searches for adjacent positions.
107111 */
107112 static int fts3PoslistPhraseMerge(
107113   char **pp,                      /* Output buffer */
107114   int nToken,                     /* Maximum difference in token positions */
107115   int isSaveLeft,                 /* Save the left position */
107116   char **pp1,                     /* Left input list */
107117   char **pp2                      /* Right input list */
107118 ){
107119   char *p = (pp ? *pp : 0);
107120   char *p1 = *pp1;
107121   char *p2 = *pp2;
107122
107123   int iCol1 = 0;
107124   int iCol2 = 0;
107125   assert( *p1!=0 && *p2!=0 );
107126   if( *p1==POS_COLUMN ){ 
107127     p1++;
107128     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107129   }
107130   if( *p2==POS_COLUMN ){ 
107131     p2++;
107132     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107133   }
107134
107135   while( 1 ){
107136     if( iCol1==iCol2 ){
107137       char *pSave = p;
107138       sqlite3_int64 iPrev = 0;
107139       sqlite3_int64 iPos1 = 0;
107140       sqlite3_int64 iPos2 = 0;
107141
107142       if( pp && iCol1 ){
107143         *p++ = POS_COLUMN;
107144         p += sqlite3Fts3PutVarint(p, iCol1);
107145       }
107146
107147       assert( *p1!=POS_END && *p1!=POS_COLUMN );
107148       assert( *p2!=POS_END && *p2!=POS_COLUMN );
107149       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
107150       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
107151
107152       while( 1 ){
107153         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
107154           sqlite3_int64 iSave;
107155           if( !pp ){
107156             fts3PoslistCopy(0, &p2);
107157             fts3PoslistCopy(0, &p1);
107158             *pp1 = p1;
107159             *pp2 = p2;
107160             return 1;
107161           }
107162           iSave = isSaveLeft ? iPos1 : iPos2;
107163           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
107164           pSave = 0;
107165         }
107166         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
107167           if( (*p2&0xFE)==0 ) break;
107168           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
107169         }else{
107170           if( (*p1&0xFE)==0 ) break;
107171           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
107172         }
107173       }
107174
107175       if( pSave ){
107176         assert( pp && p );
107177         p = pSave;
107178       }
107179
107180       fts3ColumnlistCopy(0, &p1);
107181       fts3ColumnlistCopy(0, &p2);
107182       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
107183       if( 0==*p1 || 0==*p2 ) break;
107184
107185       p1++;
107186       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107187       p2++;
107188       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107189     }
107190
107191     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
107192     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
107193     ** end of the position list, or the 0x01 that precedes the next 
107194     ** column-number in the position list. 
107195     */
107196     else if( iCol1<iCol2 ){
107197       fts3ColumnlistCopy(0, &p1);
107198       if( 0==*p1 ) break;
107199       p1++;
107200       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107201     }else{
107202       fts3ColumnlistCopy(0, &p2);
107203       if( 0==*p2 ) break;
107204       p2++;
107205       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107206     }
107207   }
107208
107209   fts3PoslistCopy(0, &p2);
107210   fts3PoslistCopy(0, &p1);
107211   *pp1 = p1;
107212   *pp2 = p2;
107213   if( !pp || *pp==p ){
107214     return 0;
107215   }
107216   *p++ = 0x00;
107217   *pp = p;
107218   return 1;
107219 }
107220
107221 /*
107222 ** Merge two position-lists as required by the NEAR operator.
107223 */
107224 static int fts3PoslistNearMerge(
107225   char **pp,                      /* Output buffer */
107226   char *aTmp,                     /* Temporary buffer space */
107227   int nRight,                     /* Maximum difference in token positions */
107228   int nLeft,                      /* Maximum difference in token positions */
107229   char **pp1,                     /* IN/OUT: Left input list */
107230   char **pp2                      /* IN/OUT: Right input list */
107231 ){
107232   char *p1 = *pp1;
107233   char *p2 = *pp2;
107234
107235   if( !pp ){
107236     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
107237     *pp1 = p1;
107238     *pp2 = p2;
107239     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
107240   }else{
107241     char *pTmp1 = aTmp;
107242     char *pTmp2;
107243     char *aTmp2;
107244     int res = 1;
107245
107246     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
107247     aTmp2 = pTmp2 = pTmp1;
107248     *pp1 = p1;
107249     *pp2 = p2;
107250     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
107251     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
107252       fts3PoslistMerge(pp, &aTmp, &aTmp2);
107253     }else if( pTmp1!=aTmp ){
107254       fts3PoslistCopy(pp, &aTmp);
107255     }else if( pTmp2!=aTmp2 ){
107256       fts3PoslistCopy(pp, &aTmp2);
107257     }else{
107258       res = 0;
107259     }
107260
107261     return res;
107262   }
107263 }
107264
107265 /*
107266 ** Values that may be used as the first parameter to fts3DoclistMerge().
107267 */
107268 #define MERGE_NOT        2        /* D + D -> D */
107269 #define MERGE_AND        3        /* D + D -> D */
107270 #define MERGE_OR         4        /* D + D -> D */
107271 #define MERGE_POS_OR     5        /* P + P -> P */
107272 #define MERGE_PHRASE     6        /* P + P -> D */
107273 #define MERGE_POS_PHRASE 7        /* P + P -> P */
107274 #define MERGE_NEAR       8        /* P + P -> D */
107275 #define MERGE_POS_NEAR   9        /* P + P -> P */
107276
107277 /*
107278 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
107279 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
107280 ** which is guaranteed to be large enough to hold the results. The number
107281 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
107282 **
107283 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
107284 ** occurs while allocating a temporary buffer as part of the merge operation,
107285 ** SQLITE_NOMEM is returned.
107286 */
107287 static int fts3DoclistMerge(
107288   int mergetype,                  /* One of the MERGE_XXX constants */
107289   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
107290   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
107291   char *aBuffer,                  /* Pre-allocated output buffer */
107292   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
107293   char *a1,                       /* Buffer containing first doclist */
107294   int n1,                         /* Size of buffer a1 */
107295   char *a2,                       /* Buffer containing second doclist */
107296   int n2                          /* Size of buffer a2 */
107297 ){
107298   sqlite3_int64 i1 = 0;
107299   sqlite3_int64 i2 = 0;
107300   sqlite3_int64 iPrev = 0;
107301
107302   char *p = aBuffer;
107303   char *p1 = a1;
107304   char *p2 = a2;
107305   char *pEnd1 = &a1[n1];
107306   char *pEnd2 = &a2[n2];
107307
107308   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
107309        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
107310        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
107311        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
107312   );
107313
107314   if( !aBuffer ){
107315     *pnBuffer = 0;
107316     return SQLITE_NOMEM;
107317   }
107318
107319   /* Read the first docid from each doclist */
107320   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107321   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107322
107323   switch( mergetype ){
107324     case MERGE_OR:
107325     case MERGE_POS_OR:
107326       while( p1 || p2 ){
107327         if( p2 && p1 && i1==i2 ){
107328           fts3PutDeltaVarint(&p, &iPrev, i1);
107329           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
107330           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107331           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107332         }else if( !p2 || (p1 && i1<i2) ){
107333           fts3PutDeltaVarint(&p, &iPrev, i1);
107334           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
107335           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107336         }else{
107337           fts3PutDeltaVarint(&p, &iPrev, i2);
107338           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
107339           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107340         }
107341       }
107342       break;
107343
107344     case MERGE_AND:
107345       while( p1 && p2 ){
107346         if( i1==i2 ){
107347           fts3PutDeltaVarint(&p, &iPrev, i1);
107348           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107349           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107350         }else if( i1<i2 ){
107351           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107352         }else{
107353           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107354         }
107355       }
107356       break;
107357
107358     case MERGE_NOT:
107359       while( p1 ){
107360         if( p2 && i1==i2 ){
107361           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107362           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107363         }else if( !p2 || i1<i2 ){
107364           fts3PutDeltaVarint(&p, &iPrev, i1);
107365           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107366         }else{
107367           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107368         }
107369       }
107370       break;
107371
107372     case MERGE_POS_PHRASE:
107373     case MERGE_PHRASE: {
107374       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
107375       while( p1 && p2 ){
107376         if( i1==i2 ){
107377           char *pSave = p;
107378           sqlite3_int64 iPrevSave = iPrev;
107379           fts3PutDeltaVarint(&p, &iPrev, i1);
107380           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
107381             p = pSave;
107382             iPrev = iPrevSave;
107383           }
107384           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107385           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107386         }else if( i1<i2 ){
107387           fts3PoslistCopy(0, &p1);
107388           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107389         }else{
107390           fts3PoslistCopy(0, &p2);
107391           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107392         }
107393       }
107394       break;
107395     }
107396
107397     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
107398       char *aTmp = 0;
107399       char **ppPos = 0;
107400
107401       if( mergetype==MERGE_POS_NEAR ){
107402         ppPos = &p;
107403         aTmp = sqlite3_malloc(2*(n1+n2+1));
107404         if( !aTmp ){
107405           return SQLITE_NOMEM;
107406         }
107407       }
107408
107409       while( p1 && p2 ){
107410         if( i1==i2 ){
107411           char *pSave = p;
107412           sqlite3_int64 iPrevSave = iPrev;
107413           fts3PutDeltaVarint(&p, &iPrev, i1);
107414
107415           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
107416             iPrev = iPrevSave;
107417             p = pSave;
107418           }
107419
107420           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107421           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107422         }else if( i1<i2 ){
107423           fts3PoslistCopy(0, &p1);
107424           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107425         }else{
107426           fts3PoslistCopy(0, &p2);
107427           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107428         }
107429       }
107430       sqlite3_free(aTmp);
107431       break;
107432     }
107433   }
107434
107435   *pnBuffer = (int)(p-aBuffer);
107436   return SQLITE_OK;
107437 }
107438
107439 /* 
107440 ** A pointer to an instance of this structure is used as the context 
107441 ** argument to sqlite3Fts3SegReaderIterate()
107442 */
107443 typedef struct TermSelect TermSelect;
107444 struct TermSelect {
107445   int isReqPos;
107446   char *aaOutput[16];             /* Malloc'd output buffer */
107447   int anOutput[16];               /* Size of output in bytes */
107448 };
107449
107450 /*
107451 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
107452 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
107453 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
107454 **
107455 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
107456 ** the responsibility of the caller to free any doclists left in the
107457 ** TermSelect.aaOutput[] array.
107458 */
107459 static int fts3TermSelectMerge(TermSelect *pTS){
107460   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
107461   char *aOut = 0;
107462   int nOut = 0;
107463   int i;
107464
107465   /* Loop through the doclists in the aaOutput[] array. Merge them all
107466   ** into a single doclist.
107467   */
107468   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
107469     if( pTS->aaOutput[i] ){
107470       if( !aOut ){
107471         aOut = pTS->aaOutput[i];
107472         nOut = pTS->anOutput[i];
107473         pTS->aaOutput[0] = 0;
107474       }else{
107475         int nNew = nOut + pTS->anOutput[i];
107476         char *aNew = sqlite3_malloc(nNew);
107477         if( !aNew ){
107478           sqlite3_free(aOut);
107479           return SQLITE_NOMEM;
107480         }
107481         fts3DoclistMerge(mergetype, 0, 0,
107482             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut
107483         );
107484         sqlite3_free(pTS->aaOutput[i]);
107485         sqlite3_free(aOut);
107486         pTS->aaOutput[i] = 0;
107487         aOut = aNew;
107488         nOut = nNew;
107489       }
107490     }
107491   }
107492
107493   pTS->aaOutput[0] = aOut;
107494   pTS->anOutput[0] = nOut;
107495   return SQLITE_OK;
107496 }
107497
107498 /*
107499 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
107500 ** querying the full-text index for a doclist associated with a term or
107501 ** term-prefix.
107502 */
107503 static int fts3TermSelectCb(
107504   Fts3Table *p,                   /* Virtual table object */
107505   void *pContext,                 /* Pointer to TermSelect structure */
107506   char *zTerm,
107507   int nTerm,
107508   char *aDoclist,
107509   int nDoclist
107510 ){
107511   TermSelect *pTS = (TermSelect *)pContext;
107512
107513   UNUSED_PARAMETER(p);
107514   UNUSED_PARAMETER(zTerm);
107515   UNUSED_PARAMETER(nTerm);
107516
107517   if( pTS->aaOutput[0]==0 ){
107518     /* If this is the first term selected, copy the doclist to the output
107519     ** buffer using memcpy(). TODO: Add a way to transfer control of the
107520     ** aDoclist buffer from the caller so as to avoid the memcpy().
107521     */
107522     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
107523     pTS->anOutput[0] = nDoclist;
107524     if( pTS->aaOutput[0] ){
107525       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
107526     }else{
107527       return SQLITE_NOMEM;
107528     }
107529   }else{
107530     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
107531     char *aMerge = aDoclist;
107532     int nMerge = nDoclist;
107533     int iOut;
107534
107535     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
107536       char *aNew;
107537       int nNew;
107538       if( pTS->aaOutput[iOut]==0 ){
107539         assert( iOut>0 );
107540         pTS->aaOutput[iOut] = aMerge;
107541         pTS->anOutput[iOut] = nMerge;
107542         break;
107543       }
107544
107545       nNew = nMerge + pTS->anOutput[iOut];
107546       aNew = sqlite3_malloc(nNew);
107547       if( !aNew ){
107548         if( aMerge!=aDoclist ){
107549           sqlite3_free(aMerge);
107550         }
107551         return SQLITE_NOMEM;
107552       }
107553       fts3DoclistMerge(mergetype, 0, 0,
107554           aNew, &nNew, pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge
107555       );
107556
107557       if( iOut>0 ) sqlite3_free(aMerge);
107558       sqlite3_free(pTS->aaOutput[iOut]);
107559       pTS->aaOutput[iOut] = 0;
107560
107561       aMerge = aNew;
107562       nMerge = nNew;
107563       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
107564         pTS->aaOutput[iOut] = aMerge;
107565         pTS->anOutput[iOut] = nMerge;
107566       }
107567     }
107568   }
107569   return SQLITE_OK;
107570 }
107571
107572 /*
107573 ** This function retreives the doclist for the specified term (or term
107574 ** prefix) from the database. 
107575 **
107576 ** The returned doclist may be in one of two formats, depending on the 
107577 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
107578 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
107579 ** is non-zero, then the returned list is in the same format as is stored 
107580 ** in the database without the found length specifier at the start of on-disk
107581 ** doclists.
107582 */
107583 static int fts3TermSelect(
107584   Fts3Table *p,                   /* Virtual table handle */
107585   int iColumn,                    /* Column to query (or -ve for all columns) */
107586   const char *zTerm,              /* Term to query for */
107587   int nTerm,                      /* Size of zTerm in bytes */
107588   int isPrefix,                   /* True for a prefix search */
107589   int isReqPos,                   /* True to include position lists in output */
107590   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
107591   char **ppOut                    /* OUT: Malloced result buffer */
107592 ){
107593   int i;
107594   TermSelect tsc;
107595   Fts3SegFilter filter;           /* Segment term filter configuration */
107596   Fts3SegReader **apSegment;      /* Array of segments to read data from */
107597   int nSegment = 0;               /* Size of apSegment array */
107598   int nAlloc = 16;                /* Allocated size of segment array */
107599   int rc;                         /* Return code */
107600   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
107601   int iAge = 0;                   /* Used to assign ages to segments */
107602
107603   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
107604   if( !apSegment ) return SQLITE_NOMEM;
107605   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
107606   if( rc!=SQLITE_OK ) goto finished;
107607   if( apSegment[0] ){
107608     nSegment = 1;
107609   }
107610
107611   /* Loop through the entire %_segdir table. For each segment, create a
107612   ** Fts3SegReader to iterate through the subset of the segment leaves
107613   ** that may contain a term that matches zTerm/nTerm. For non-prefix
107614   ** searches, this is always a single leaf. For prefix searches, this
107615   ** may be a contiguous block of leaves.
107616   **
107617   ** The code in this loop does not actually load any leaves into memory
107618   ** (unless the root node happens to be a leaf). It simply examines the
107619   ** b-tree structure to determine which leaves need to be inspected.
107620   */
107621   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
107622   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
107623     Fts3SegReader *pNew = 0;
107624     int nRoot = sqlite3_column_bytes(pStmt, 4);
107625     char const *zRoot = sqlite3_column_blob(pStmt, 4);
107626     if( sqlite3_column_int64(pStmt, 1)==0 ){
107627       /* The entire segment is stored on the root node (which must be a
107628       ** leaf). Do not bother inspecting any data in this case, just
107629       ** create a Fts3SegReader to scan the single leaf. 
107630       */
107631       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
107632     }else{
107633       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
107634       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
107635       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
107636       if( rc==SQLITE_OK ){
107637         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
107638         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
107639       }
107640
107641       /* The following call to ReadBlock() serves to reset the SQL statement
107642       ** used to retrieve blocks of data from the %_segments table. If it is
107643       ** not reset here, then it may remain classified as an active statement 
107644       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands 
107645       ** failing.
107646       */ 
107647       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
107648       if( rc==SQLITE_OK ){
107649         rc = rc2;
107650       }
107651     }
107652     iAge++;
107653
107654     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
107655     assert( pNew!=0 || rc!=SQLITE_OK );
107656     if( pNew ){
107657       if( nSegment==nAlloc ){
107658         Fts3SegReader **pArray;
107659         nAlloc += 16;
107660         pArray = (Fts3SegReader **)sqlite3_realloc(
107661             apSegment, nAlloc*sizeof(Fts3SegReader *)
107662         );
107663         if( !pArray ){
107664           sqlite3Fts3SegReaderFree(p, pNew);
107665           rc = SQLITE_NOMEM;
107666           goto finished;
107667         }
107668         apSegment = pArray;
107669       }
107670       apSegment[nSegment++] = pNew;
107671     }
107672   }
107673   if( rc!=SQLITE_DONE ){
107674     assert( rc!=SQLITE_OK );
107675     goto finished;
107676   }
107677
107678   memset(&tsc, 0, sizeof(TermSelect));
107679   tsc.isReqPos = isReqPos;
107680
107681   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
107682         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
107683         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
107684         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
107685   filter.iCol = iColumn;
107686   filter.zTerm = zTerm;
107687   filter.nTerm = nTerm;
107688
107689   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
107690       fts3TermSelectCb, (void *)&tsc
107691   );
107692   if( rc==SQLITE_OK ){
107693     rc = fts3TermSelectMerge(&tsc);
107694   }
107695
107696   if( rc==SQLITE_OK ){
107697     *ppOut = tsc.aaOutput[0];
107698     *pnOut = tsc.anOutput[0];
107699   }else{
107700     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
107701       sqlite3_free(tsc.aaOutput[i]);
107702     }
107703   }
107704
107705 finished:
107706   sqlite3_reset(pStmt);
107707   for(i=0; i<nSegment; i++){
107708     sqlite3Fts3SegReaderFree(p, apSegment[i]);
107709   }
107710   sqlite3_free(apSegment);
107711   return rc;
107712 }
107713
107714
107715 /* 
107716 ** Return a DocList corresponding to the phrase *pPhrase.
107717 */
107718 static int fts3PhraseSelect(
107719   Fts3Table *p,                   /* Virtual table handle */
107720   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
107721   int isReqPos,                   /* True if output should contain positions */
107722   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107723   int *pnOut                      /* OUT: Size of buffer at *paOut */
107724 ){
107725   char *pOut = 0;
107726   int nOut = 0;
107727   int rc = SQLITE_OK;
107728   int ii;
107729   int iCol = pPhrase->iColumn;
107730   int isTermPos = (pPhrase->nToken>1 || isReqPos);
107731
107732   for(ii=0; ii<pPhrase->nToken; ii++){
107733     struct PhraseToken *pTok = &pPhrase->aToken[ii];
107734     char *z = pTok->z;            /* Next token of the phrase */
107735     int n = pTok->n;              /* Size of z in bytes */
107736     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
107737     char *pList;                  /* Pointer to token doclist */
107738     int nList;                    /* Size of buffer at pList */
107739
107740     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
107741     if( rc!=SQLITE_OK ) break;
107742
107743     if( ii==0 ){
107744       pOut = pList;
107745       nOut = nList;
107746     }else{
107747       /* Merge the new term list and the current output. If this is the
107748       ** last term in the phrase, and positions are not required in the
107749       ** output of this function, the positions can be dropped as part
107750       ** of this merge. Either way, the result of this merge will be
107751       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
107752       ** so that it is safe to use pList as the output as well as an input
107753       ** in this case.
107754       */
107755       int mergetype = MERGE_POS_PHRASE;
107756       if( ii==pPhrase->nToken-1 && !isReqPos ){
107757         mergetype = MERGE_PHRASE;
107758       }
107759       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
107760       sqlite3_free(pOut);
107761       pOut = pList;
107762     }
107763     assert( nOut==0 || pOut!=0 );
107764   }
107765
107766   if( rc==SQLITE_OK ){
107767     *paOut = pOut;
107768     *pnOut = nOut;
107769   }else{
107770     sqlite3_free(pOut);
107771   }
107772   return rc;
107773 }
107774
107775 static int fts3NearMerge(
107776   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
107777   int nNear,                      /* Parameter to NEAR operator */
107778   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
107779   char *aLeft,                    /* Doclist for LHS (incl. positions) */
107780   int nLeft,                      /* Size of LHS doclist in bytes */
107781   int nTokenRight,                /* As nTokenLeft */
107782   char *aRight,                   /* As aLeft */
107783   int nRight,                     /* As nRight */
107784   char **paOut,                   /* OUT: Results of merge (malloced) */
107785   int *pnOut                      /* OUT: Sized of output buffer */
107786 ){
107787   char *aOut;
107788   int rc;
107789
107790   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
107791
107792   aOut = sqlite3_malloc(nLeft+nRight+1);
107793   if( aOut==0 ){
107794     rc = SQLITE_NOMEM;
107795   }else{
107796     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
107797       aOut, pnOut, aLeft, nLeft, aRight, nRight
107798     );
107799     if( rc!=SQLITE_OK ){
107800       sqlite3_free(aOut);
107801       aOut = 0;
107802     }
107803   }
107804
107805   *paOut = aOut;
107806   return rc;
107807 }
107808
107809 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
107810   int rc;
107811   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
107812     sqlite3_free(pLeft->aDoclist);
107813     sqlite3_free(pRight->aDoclist);
107814     pRight->aDoclist = 0;
107815     pLeft->aDoclist = 0;
107816     rc = SQLITE_OK;
107817   }else{
107818     char *aOut;
107819     int nOut;
107820
107821     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
107822         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107823         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107824         &aOut, &nOut
107825     );
107826     if( rc!=SQLITE_OK ) return rc;
107827     sqlite3_free(pRight->aDoclist);
107828     pRight->aDoclist = aOut;
107829     pRight->nDoclist = nOut;
107830
107831     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
107832         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107833         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107834         &aOut, &nOut
107835     );
107836     sqlite3_free(pLeft->aDoclist);
107837     pLeft->aDoclist = aOut;
107838     pLeft->nDoclist = nOut;
107839   }
107840   return rc;
107841 }
107842
107843 /*
107844 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
107845 ** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
107846 ** the space needed to store the output.  The caller is responsible for
107847 ** freeing the space when it has finished.
107848 */
107849 static int evalFts3Expr(
107850   Fts3Table *p,                   /* Virtual table handle */
107851   Fts3Expr *pExpr,                /* Parsed fts3 expression */
107852   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107853   int *pnOut,                     /* OUT: Size of buffer at *paOut */
107854   int isReqPos                    /* Require positions in output buffer */
107855 ){
107856   int rc = SQLITE_OK;             /* Return code */
107857
107858   /* Zero the output parameters. */
107859   *paOut = 0;
107860   *pnOut = 0;
107861
107862   if( pExpr ){
107863     assert( pExpr->eType==FTSQUERY_PHRASE 
107864          || pExpr->eType==FTSQUERY_NEAR 
107865          || isReqPos==0
107866     );
107867     if( pExpr->eType==FTSQUERY_PHRASE ){
107868       rc = fts3PhraseSelect(p, pExpr->pPhrase, 
107869           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
107870           paOut, pnOut
107871       );
107872     }else{
107873       char *aLeft;
107874       char *aRight;
107875       int nLeft;
107876       int nRight;
107877
107878       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
107879        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
107880       ){
107881         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR     
107882             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
107883         );
107884         switch( pExpr->eType ){
107885           case FTSQUERY_NEAR: {
107886             Fts3Expr *pLeft;
107887             Fts3Expr *pRight;
107888             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
107889            
107890             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
107891               mergetype = MERGE_POS_NEAR;
107892             }
107893             pLeft = pExpr->pLeft;
107894             while( pLeft->eType==FTSQUERY_NEAR ){ 
107895               pLeft=pLeft->pRight;
107896             }
107897             pRight = pExpr->pRight;
107898             assert( pRight->eType==FTSQUERY_PHRASE );
107899             assert( pLeft->eType==FTSQUERY_PHRASE );
107900
107901             rc = fts3NearMerge(mergetype, pExpr->nNear, 
107902                 pLeft->pPhrase->nToken, aLeft, nLeft,
107903                 pRight->pPhrase->nToken, aRight, nRight,
107904                 paOut, pnOut
107905             );
107906             sqlite3_free(aLeft);
107907             break;
107908           }
107909
107910           case FTSQUERY_OR: {
107911             /* Allocate a buffer for the output. The maximum size is the
107912             ** sum of the sizes of the two input buffers. The +1 term is
107913             ** so that a buffer of zero bytes is never allocated - this can
107914             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
107915             */
107916             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
107917             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
107918                 aLeft, nLeft, aRight, nRight
107919             );
107920             *paOut = aBuffer;
107921             sqlite3_free(aLeft);
107922             break;
107923           }
107924
107925           default: {
107926             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
107927             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
107928                 aLeft, nLeft, aRight, nRight
107929             );
107930             *paOut = aLeft;
107931             break;
107932           }
107933         }
107934       }
107935       sqlite3_free(aRight);
107936     }
107937   }
107938
107939   return rc;
107940 }
107941
107942 /*
107943 ** This is the xFilter interface for the virtual table.  See
107944 ** the virtual table xFilter method documentation for additional
107945 ** information.
107946 **
107947 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
107948 ** the %_content table.
107949 **
107950 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
107951 ** in the %_content table.
107952 **
107953 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
107954 ** column on the left-hand side of the MATCH operator is column
107955 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
107956 ** side of the MATCH operator.
107957 */
107958 /* TODO(shess) Upgrade the cursor initialization and destruction to
107959 ** account for fts3FilterMethod() being called multiple times on the
107960 ** same cursor. The current solution is very fragile. Apply fix to
107961 ** fts3 as appropriate.
107962 */
107963 static int fts3FilterMethod(
107964   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
107965   int idxNum,                     /* Strategy index */
107966   const char *idxStr,             /* Unused */
107967   int nVal,                       /* Number of elements in apVal */
107968   sqlite3_value **apVal           /* Arguments for the indexing scheme */
107969 ){
107970   const char *azSql[] = {
107971     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
107972     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
107973   };
107974   int rc;                         /* Return code */
107975   char *zSql;                     /* SQL statement used to access %_content */
107976   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
107977   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107978
107979   UNUSED_PARAMETER(idxStr);
107980   UNUSED_PARAMETER(nVal);
107981
107982   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
107983   assert( nVal==0 || nVal==1 );
107984   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
107985
107986   /* In case the cursor has been used before, clear it now. */
107987   sqlite3_finalize(pCsr->pStmt);
107988   sqlite3_free(pCsr->aDoclist);
107989   sqlite3Fts3ExprFree(pCsr->pExpr);
107990   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
107991
107992   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
107993   ** statement loops through all rows of the %_content table. For a
107994   ** full-text query or docid lookup, the statement retrieves a single
107995   ** row by docid.
107996   */
107997   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
107998   if( !zSql ){
107999     rc = SQLITE_NOMEM;
108000   }else{
108001     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
108002     sqlite3_free(zSql);
108003   }
108004   if( rc!=SQLITE_OK ) return rc;
108005   pCsr->eSearch = (i16)idxNum;
108006
108007   if( idxNum==FTS3_DOCID_SEARCH ){
108008     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
108009   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
108010     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
108011     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
108012
108013     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
108014       return SQLITE_NOMEM;
108015     }
108016
108017     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
108018         iCol, zQuery, -1, &pCsr->pExpr
108019     );
108020     if( rc!=SQLITE_OK ){
108021       if( rc==SQLITE_ERROR ){
108022         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
108023                                           zQuery);
108024       }
108025       return rc;
108026     }
108027
108028     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
108029     pCsr->pNextId = pCsr->aDoclist;
108030     pCsr->iPrevId = 0;
108031   }
108032
108033   if( rc!=SQLITE_OK ) return rc;
108034   return fts3NextMethod(pCursor);
108035 }
108036
108037 /* 
108038 ** This is the xEof method of the virtual table. SQLite calls this 
108039 ** routine to find out if it has reached the end of a result set.
108040 */
108041 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
108042   return ((Fts3Cursor *)pCursor)->isEof;
108043 }
108044
108045 /* 
108046 ** This is the xRowid method. The SQLite core calls this routine to
108047 ** retrieve the rowid for the current row of the result set. fts3
108048 ** exposes %_content.docid as the rowid for the virtual table. The
108049 ** rowid should be written to *pRowid.
108050 */
108051 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
108052   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
108053   if( pCsr->aDoclist ){
108054     *pRowid = pCsr->iPrevId;
108055   }else{
108056     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
108057   }
108058   return SQLITE_OK;
108059 }
108060
108061 /* 
108062 ** This is the xColumn method, called by SQLite to request a value from
108063 ** the row that the supplied cursor currently points to.
108064 */
108065 static int fts3ColumnMethod(
108066   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
108067   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
108068   int iCol                        /* Index of column to read value from */
108069 ){
108070   int rc;                         /* Return Code */
108071   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
108072   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
108073
108074   /* The column value supplied by SQLite must be in range. */
108075   assert( iCol>=0 && iCol<=p->nColumn+1 );
108076
108077   if( iCol==p->nColumn+1 ){
108078     /* This call is a request for the "docid" column. Since "docid" is an 
108079     ** alias for "rowid", use the xRowid() method to obtain the value.
108080     */
108081     sqlite3_int64 iRowid;
108082     rc = fts3RowidMethod(pCursor, &iRowid);
108083     sqlite3_result_int64(pContext, iRowid);
108084   }else if( iCol==p->nColumn ){
108085     /* The extra column whose name is the same as the table.
108086     ** Return a blob which is a pointer to the cursor.
108087     */
108088     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
108089     rc = SQLITE_OK;
108090   }else{
108091     rc = fts3CursorSeek(0, pCsr);
108092     if( rc==SQLITE_OK ){
108093       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
108094     }
108095   }
108096   return rc;
108097 }
108098
108099 /* 
108100 ** This function is the implementation of the xUpdate callback used by 
108101 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
108102 ** inserted, updated or deleted.
108103 */
108104 static int fts3UpdateMethod(
108105   sqlite3_vtab *pVtab,            /* Virtual table handle */
108106   int nArg,                       /* Size of argument array */
108107   sqlite3_value **apVal,          /* Array of arguments */
108108   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
108109 ){
108110   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
108111 }
108112
108113 /*
108114 ** Implementation of xSync() method. Flush the contents of the pending-terms
108115 ** hash-table to the database.
108116 */
108117 static int fts3SyncMethod(sqlite3_vtab *pVtab){
108118   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
108119 }
108120
108121 /*
108122 ** Implementation of xBegin() method. This is a no-op.
108123 */
108124 static int fts3BeginMethod(sqlite3_vtab *pVtab){
108125   UNUSED_PARAMETER(pVtab);
108126   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
108127   return SQLITE_OK;
108128 }
108129
108130 /*
108131 ** Implementation of xCommit() method. This is a no-op. The contents of
108132 ** the pending-terms hash-table have already been flushed into the database
108133 ** by fts3SyncMethod().
108134 */
108135 static int fts3CommitMethod(sqlite3_vtab *pVtab){
108136   UNUSED_PARAMETER(pVtab);
108137   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
108138   return SQLITE_OK;
108139 }
108140
108141 /*
108142 ** Implementation of xRollback(). Discard the contents of the pending-terms
108143 ** hash-table. Any changes made to the database are reverted by SQLite.
108144 */
108145 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
108146   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
108147   return SQLITE_OK;
108148 }
108149
108150 /*
108151 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
108152 ** The loaded doclist contains positions as well as the document ids.
108153 ** This is used by the matchinfo(), snippet() and offsets() auxillary
108154 ** functions.
108155 */
108156 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
108157   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
108158 }
108159
108160 /*
108161 ** After ExprLoadDoclist() (see above) has been called, this function is
108162 ** used to iterate/search through the position lists that make up the doclist
108163 ** stored in pExpr->aDoclist.
108164 */
108165 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
108166   Fts3Expr *pExpr,                /* Access this expressions doclist */
108167   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
108168   int iCol                        /* Column of requested pos-list */
108169 ){
108170   assert( pExpr->isLoaded );
108171   if( pExpr->aDoclist ){
108172     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
108173     char *pCsr = pExpr->pCurrent;
108174
108175     assert( pCsr );
108176     while( pCsr<pEnd ){
108177       if( pExpr->iCurrent<iDocid ){
108178         fts3PoslistCopy(0, &pCsr);
108179         if( pCsr<pEnd ){
108180           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
108181         }
108182         pExpr->pCurrent = pCsr;
108183       }else{
108184         if( pExpr->iCurrent==iDocid ){
108185           int iThis = 0;
108186           if( iCol<0 ){
108187             /* If iCol is negative, return a pointer to the start of the
108188             ** position-list (instead of a pointer to the start of a list
108189             ** of offsets associated with a specific column).
108190             */
108191             return pCsr;
108192           }
108193           while( iThis<iCol ){
108194             fts3ColumnlistCopy(0, &pCsr);
108195             if( *pCsr==0x00 ) return 0;
108196             pCsr++;
108197             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
108198           }
108199           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
108200         }
108201         return 0;
108202       }
108203     }
108204   }
108205
108206   return 0;
108207 }
108208
108209 /*
108210 ** Helper function used by the implementation of the overloaded snippet(),
108211 ** offsets() and optimize() SQL functions.
108212 **
108213 ** If the value passed as the third argument is a blob of size
108214 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
108215 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
108216 ** message is written to context pContext and SQLITE_ERROR returned. The
108217 ** string passed via zFunc is used as part of the error message.
108218 */
108219 static int fts3FunctionArg(
108220   sqlite3_context *pContext,      /* SQL function call context */
108221   const char *zFunc,              /* Function name */
108222   sqlite3_value *pVal,            /* argv[0] passed to function */
108223   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
108224 ){
108225   Fts3Cursor *pRet;
108226   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
108227    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
108228   ){
108229     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
108230     sqlite3_result_error(pContext, zErr, -1);
108231     sqlite3_free(zErr);
108232     return SQLITE_ERROR;
108233   }
108234   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
108235   *ppCsr = pRet;
108236   return SQLITE_OK;
108237 }
108238
108239 /*
108240 ** Implementation of the snippet() function for FTS3
108241 */
108242 static void fts3SnippetFunc(
108243   sqlite3_context *pContext,      /* SQLite function call context */
108244   int nVal,                       /* Size of apVal[] array */
108245   sqlite3_value **apVal           /* Array of arguments */
108246 ){
108247   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108248   const char *zStart = "<b>";
108249   const char *zEnd = "</b>";
108250   const char *zEllipsis = "<b>...</b>";
108251   int iCol = -1;
108252   int nToken = 15;                /* Default number of tokens in snippet */
108253
108254   /* There must be at least one argument passed to this function (otherwise
108255   ** the non-overloaded version would have been called instead of this one).
108256   */
108257   assert( nVal>=1 );
108258
108259   if( nVal>6 ){
108260     sqlite3_result_error(pContext, 
108261         "wrong number of arguments to function snippet()", -1);
108262     return;
108263   }
108264   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
108265
108266   switch( nVal ){
108267     case 6: nToken = sqlite3_value_int(apVal[5]);
108268     case 5: iCol = sqlite3_value_int(apVal[4]);
108269     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
108270     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
108271     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
108272   }
108273   if( !zEllipsis || !zEnd || !zStart ){
108274     sqlite3_result_error_nomem(pContext);
108275   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
108276     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
108277   }
108278 }
108279
108280 /*
108281 ** Implementation of the offsets() function for FTS3
108282 */
108283 static void fts3OffsetsFunc(
108284   sqlite3_context *pContext,      /* SQLite function call context */
108285   int nVal,                       /* Size of argument array */
108286   sqlite3_value **apVal           /* Array of arguments */
108287 ){
108288   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108289
108290   UNUSED_PARAMETER(nVal);
108291
108292   assert( nVal==1 );
108293   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
108294   assert( pCsr );
108295   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
108296     sqlite3Fts3Offsets(pContext, pCsr);
108297   }
108298 }
108299
108300 /* 
108301 ** Implementation of the special optimize() function for FTS3. This 
108302 ** function merges all segments in the database to a single segment.
108303 ** Example usage is:
108304 **
108305 **   SELECT optimize(t) FROM t LIMIT 1;
108306 **
108307 ** where 't' is the name of an FTS3 table.
108308 */
108309 static void fts3OptimizeFunc(
108310   sqlite3_context *pContext,      /* SQLite function call context */
108311   int nVal,                       /* Size of argument array */
108312   sqlite3_value **apVal           /* Array of arguments */
108313 ){
108314   int rc;                         /* Return code */
108315   Fts3Table *p;                   /* Virtual table handle */
108316   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
108317
108318   UNUSED_PARAMETER(nVal);
108319
108320   assert( nVal==1 );
108321   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
108322   p = (Fts3Table *)pCursor->base.pVtab;
108323   assert( p );
108324
108325   rc = sqlite3Fts3Optimize(p);
108326
108327   switch( rc ){
108328     case SQLITE_OK:
108329       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
108330       break;
108331     case SQLITE_DONE:
108332       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
108333       break;
108334     default:
108335       sqlite3_result_error_code(pContext, rc);
108336       break;
108337   }
108338 }
108339
108340 /*
108341 ** Implementation of the matchinfo() function for FTS3
108342 */
108343 static void fts3MatchinfoFunc(
108344   sqlite3_context *pContext,      /* SQLite function call context */
108345   int nVal,                       /* Size of argument array */
108346   sqlite3_value **apVal           /* Array of arguments */
108347 ){
108348   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108349
108350   if( nVal!=1 ){
108351     sqlite3_result_error(pContext,
108352         "wrong number of arguments to function matchinfo()", -1);
108353     return;
108354   }
108355
108356   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
108357     sqlite3Fts3Matchinfo(pContext, pCsr);
108358   }
108359 }
108360
108361 /*
108362 ** This routine implements the xFindFunction method for the FTS3
108363 ** virtual table.
108364 */
108365 static int fts3FindFunctionMethod(
108366   sqlite3_vtab *pVtab,            /* Virtual table handle */
108367   int nArg,                       /* Number of SQL function arguments */
108368   const char *zName,              /* Name of SQL function */
108369   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
108370   void **ppArg                    /* Unused */
108371 ){
108372   struct Overloaded {
108373     const char *zName;
108374     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
108375   } aOverload[] = {
108376     { "snippet", fts3SnippetFunc },
108377     { "offsets", fts3OffsetsFunc },
108378     { "optimize", fts3OptimizeFunc },
108379     { "matchinfo", fts3MatchinfoFunc },
108380   };
108381   int i;                          /* Iterator variable */
108382
108383   UNUSED_PARAMETER(pVtab);
108384   UNUSED_PARAMETER(nArg);
108385   UNUSED_PARAMETER(ppArg);
108386
108387   for(i=0; i<SizeofArray(aOverload); i++){
108388     if( strcmp(zName, aOverload[i].zName)==0 ){
108389       *pxFunc = aOverload[i].xFunc;
108390       return 1;
108391     }
108392   }
108393
108394   /* No function of the specified name was found. Return 0. */
108395   return 0;
108396 }
108397
108398 /*
108399 ** Implementation of FTS3 xRename method. Rename an fts3 table.
108400 */
108401 static int fts3RenameMethod(
108402   sqlite3_vtab *pVtab,            /* Virtual table handle */
108403   const char *zName               /* New name of table */
108404 ){
108405   Fts3Table *p = (Fts3Table *)pVtab;
108406   sqlite3 *db;                    /* Database connection */
108407   int rc;                         /* Return Code */
108408  
108409   db = p->db;
108410   rc = SQLITE_OK;
108411   fts3DbExec(&rc, db,
108412     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
108413     p->zDb, p->zName, zName
108414   );
108415   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
108416   if( p->bHasDocsize ){
108417     fts3DbExec(&rc, db,
108418       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
108419       p->zDb, p->zName, zName
108420     );
108421     fts3DbExec(&rc, db,
108422       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
108423       p->zDb, p->zName, zName
108424     );
108425   }
108426   fts3DbExec(&rc, db,
108427     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
108428     p->zDb, p->zName, zName
108429   );
108430   fts3DbExec(&rc, db,
108431     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
108432     p->zDb, p->zName, zName
108433   );
108434   return rc;
108435 }
108436
108437 static const sqlite3_module fts3Module = {
108438   /* iVersion      */ 0,
108439   /* xCreate       */ fts3CreateMethod,
108440   /* xConnect      */ fts3ConnectMethod,
108441   /* xBestIndex    */ fts3BestIndexMethod,
108442   /* xDisconnect   */ fts3DisconnectMethod,
108443   /* xDestroy      */ fts3DestroyMethod,
108444   /* xOpen         */ fts3OpenMethod,
108445   /* xClose        */ fulltextClose,
108446   /* xFilter       */ fts3FilterMethod,
108447   /* xNext         */ fts3NextMethod,
108448   /* xEof          */ fts3EofMethod,
108449   /* xColumn       */ fts3ColumnMethod,
108450   /* xRowid        */ fts3RowidMethod,
108451   /* xUpdate       */ fts3UpdateMethod,
108452   /* xBegin        */ fts3BeginMethod,
108453   /* xSync         */ fts3SyncMethod,
108454   /* xCommit       */ fts3CommitMethod,
108455   /* xRollback     */ fts3RollbackMethod,
108456   /* xFindFunction */ fts3FindFunctionMethod,
108457   /* xRename */       fts3RenameMethod,
108458 };
108459
108460 /*
108461 ** This function is registered as the module destructor (called when an
108462 ** FTS3 enabled database connection is closed). It frees the memory
108463 ** allocated for the tokenizer hash table.
108464 */
108465 static void hashDestroy(void *p){
108466   Fts3Hash *pHash = (Fts3Hash *)p;
108467   sqlite3Fts3HashClear(pHash);
108468   sqlite3_free(pHash);
108469 }
108470
108471 /*
108472 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
108473 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
108474 ** two forward declarations are for functions declared in these files
108475 ** used to retrieve the respective implementations.
108476 **
108477 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
108478 ** to by the argument to point a the "simple" tokenizer implementation.
108479 ** Function ...PorterTokenizerModule() sets *pModule to point to the
108480 ** porter tokenizer/stemmer implementation.
108481 */
108482 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108483 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108484 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108485
108486 /*
108487 ** Initialise the fts3 extension. If this extension is built as part
108488 ** of the sqlite library, then this function is called directly by
108489 ** SQLite. If fts3 is built as a dynamically loadable extension, this
108490 ** function is called by the sqlite3_extension_init() entry point.
108491 */
108492 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
108493   int rc = SQLITE_OK;
108494   Fts3Hash *pHash = 0;
108495   const sqlite3_tokenizer_module *pSimple = 0;
108496   const sqlite3_tokenizer_module *pPorter = 0;
108497
108498 #ifdef SQLITE_ENABLE_ICU
108499   const sqlite3_tokenizer_module *pIcu = 0;
108500   sqlite3Fts3IcuTokenizerModule(&pIcu);
108501 #endif
108502
108503   sqlite3Fts3SimpleTokenizerModule(&pSimple);
108504   sqlite3Fts3PorterTokenizerModule(&pPorter);
108505
108506   /* Allocate and initialise the hash-table used to store tokenizers. */
108507   pHash = sqlite3_malloc(sizeof(Fts3Hash));
108508   if( !pHash ){
108509     rc = SQLITE_NOMEM;
108510   }else{
108511     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
108512   }
108513
108514   /* Load the built-in tokenizers into the hash table */
108515   if( rc==SQLITE_OK ){
108516     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
108517      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
108518 #ifdef SQLITE_ENABLE_ICU
108519      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
108520 #endif
108521     ){
108522       rc = SQLITE_NOMEM;
108523     }
108524   }
108525
108526 #ifdef SQLITE_TEST
108527   if( rc==SQLITE_OK ){
108528     rc = sqlite3Fts3ExprInitTestInterface(db);
108529   }
108530 #endif
108531
108532   /* Create the virtual table wrapper around the hash-table and overload 
108533   ** the two scalar functions. If this is successful, register the
108534   ** module with sqlite.
108535   */
108536   if( SQLITE_OK==rc 
108537    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
108538    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
108539    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
108540    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
108541    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
108542   ){
108543     rc = sqlite3_create_module_v2(
108544         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
108545     );
108546     if( rc==SQLITE_OK ){
108547       rc = sqlite3_create_module_v2(
108548           db, "fts4", &fts3Module, (void *)pHash, 0
108549       );
108550     }
108551     return rc;
108552   }
108553
108554   /* An error has occurred. Delete the hash table and return the error code. */
108555   assert( rc!=SQLITE_OK );
108556   if( pHash ){
108557     sqlite3Fts3HashClear(pHash);
108558     sqlite3_free(pHash);
108559   }
108560   return rc;
108561 }
108562
108563 #if !SQLITE_CORE
108564 SQLITE_API int sqlite3_extension_init(
108565   sqlite3 *db, 
108566   char **pzErrMsg,
108567   const sqlite3_api_routines *pApi
108568 ){
108569   SQLITE_EXTENSION_INIT2(pApi)
108570   return sqlite3Fts3Init(db);
108571 }
108572 #endif
108573
108574 #endif
108575
108576 /************** End of fts3.c ************************************************/
108577 /************** Begin file fts3_expr.c ***************************************/
108578 /*
108579 ** 2008 Nov 28
108580 **
108581 ** The author disclaims copyright to this source code.  In place of
108582 ** a legal notice, here is a blessing:
108583 **
108584 **    May you do good and not evil.
108585 **    May you find forgiveness for yourself and forgive others.
108586 **    May you share freely, never taking more than you give.
108587 **
108588 ******************************************************************************
108589 **
108590 ** This module contains code that implements a parser for fts3 query strings
108591 ** (the right-hand argument to the MATCH operator). Because the supported 
108592 ** syntax is relatively simple, the whole tokenizer/parser system is
108593 ** hand-coded. 
108594 */
108595 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
108596
108597 /*
108598 ** By default, this module parses the legacy syntax that has been 
108599 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
108600 ** is defined, then it uses the new syntax. The differences between
108601 ** the new and the old syntaxes are:
108602 **
108603 **  a) The new syntax supports parenthesis. The old does not.
108604 **
108605 **  b) The new syntax supports the AND and NOT operators. The old does not.
108606 **
108607 **  c) The old syntax supports the "-" token qualifier. This is not 
108608 **     supported by the new syntax (it is replaced by the NOT operator).
108609 **
108610 **  d) When using the old syntax, the OR operator has a greater precedence
108611 **     than an implicit AND. When using the new, both implicity and explicit
108612 **     AND operators have a higher precedence than OR.
108613 **
108614 ** If compiled with SQLITE_TEST defined, then this module exports the
108615 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
108616 ** to zero causes the module to use the old syntax. If it is set to 
108617 ** non-zero the new syntax is activated. This is so both syntaxes can
108618 ** be tested using a single build of testfixture.
108619 **
108620 ** The following describes the syntax supported by the fts3 MATCH
108621 ** operator in a similar format to that used by the lemon parser
108622 ** generator. This module does not use actually lemon, it uses a
108623 ** custom parser.
108624 **
108625 **   query ::= andexpr (OR andexpr)*.
108626 **
108627 **   andexpr ::= notexpr (AND? notexpr)*.
108628 **
108629 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
108630 **   notexpr ::= LP query RP.
108631 **
108632 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
108633 **
108634 **   distance_opt ::= .
108635 **   distance_opt ::= / INTEGER.
108636 **
108637 **   phrase ::= TOKEN.
108638 **   phrase ::= COLUMN:TOKEN.
108639 **   phrase ::= "TOKEN TOKEN TOKEN...".
108640 */
108641
108642 #ifdef SQLITE_TEST
108643 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
108644 #else
108645 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
108646 #  define sqlite3_fts3_enable_parentheses 1
108647 # else
108648 #  define sqlite3_fts3_enable_parentheses 0
108649 # endif
108650 #endif
108651
108652 /*
108653 ** Default span for NEAR operators.
108654 */
108655 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
108656
108657
108658 typedef struct ParseContext ParseContext;
108659 struct ParseContext {
108660   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
108661   const char **azCol;                 /* Array of column names for fts3 table */
108662   int nCol;                           /* Number of entries in azCol[] */
108663   int iDefaultCol;                    /* Default column to query */
108664   sqlite3_context *pCtx;              /* Write error message here */
108665   int nNest;                          /* Number of nested brackets */
108666 };
108667
108668 /*
108669 ** This function is equivalent to the standard isspace() function. 
108670 **
108671 ** The standard isspace() can be awkward to use safely, because although it
108672 ** is defined to accept an argument of type int, its behaviour when passed
108673 ** an integer that falls outside of the range of the unsigned char type
108674 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
108675 ** is defined to accept an argument of type char, and always returns 0 for
108676 ** any values that fall outside of the range of the unsigned char type (i.e.
108677 ** negative values).
108678 */
108679 static int fts3isspace(char c){
108680   return (c&0x80)==0 ? isspace(c) : 0;
108681 }
108682
108683 /*
108684 ** Extract the next token from buffer z (length n) using the tokenizer
108685 ** and other information (column names etc.) in pParse. Create an Fts3Expr
108686 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
108687 ** single token and set *ppExpr to point to it. If the end of the buffer is
108688 ** reached before a token is found, set *ppExpr to zero. It is the
108689 ** responsibility of the caller to eventually deallocate the allocated 
108690 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
108691 **
108692 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
108693 ** fails.
108694 */
108695 static int getNextToken(
108696   ParseContext *pParse,                   /* fts3 query parse context */
108697   int iCol,                               /* Value for Fts3Phrase.iColumn */
108698   const char *z, int n,                   /* Input string */
108699   Fts3Expr **ppExpr,                      /* OUT: expression */
108700   int *pnConsumed                         /* OUT: Number of bytes consumed */
108701 ){
108702   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108703   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108704   int rc;
108705   sqlite3_tokenizer_cursor *pCursor;
108706   Fts3Expr *pRet = 0;
108707   int nConsumed = 0;
108708
108709   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
108710   if( rc==SQLITE_OK ){
108711     const char *zToken;
108712     int nToken, iStart, iEnd, iPosition;
108713     int nByte;                               /* total space to allocate */
108714
108715     pCursor->pTokenizer = pTokenizer;
108716     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
108717
108718     if( rc==SQLITE_OK ){
108719       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
108720       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
108721       if( !pRet ){
108722         rc = SQLITE_NOMEM;
108723       }else{
108724         memset(pRet, 0, nByte);
108725         pRet->eType = FTSQUERY_PHRASE;
108726         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
108727         pRet->pPhrase->nToken = 1;
108728         pRet->pPhrase->iColumn = iCol;
108729         pRet->pPhrase->aToken[0].n = nToken;
108730         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
108731         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
108732
108733         if( iEnd<n && z[iEnd]=='*' ){
108734           pRet->pPhrase->aToken[0].isPrefix = 1;
108735           iEnd++;
108736         }
108737         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
108738           pRet->pPhrase->isNot = 1;
108739         }
108740       }
108741       nConsumed = iEnd;
108742     }
108743
108744     pModule->xClose(pCursor);
108745   }
108746   
108747   *pnConsumed = nConsumed;
108748   *ppExpr = pRet;
108749   return rc;
108750 }
108751
108752
108753 /*
108754 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
108755 ** then free the old allocation.
108756 */
108757 static void *fts3ReallocOrFree(void *pOrig, int nNew){
108758   void *pRet = sqlite3_realloc(pOrig, nNew);
108759   if( !pRet ){
108760     sqlite3_free(pOrig);
108761   }
108762   return pRet;
108763 }
108764
108765 /*
108766 ** Buffer zInput, length nInput, contains the contents of a quoted string
108767 ** that appeared as part of an fts3 query expression. Neither quote character
108768 ** is included in the buffer. This function attempts to tokenize the entire
108769 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
108770 ** containing the results.
108771 **
108772 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
108773 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
108774 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
108775 ** to 0.
108776 */
108777 static int getNextString(
108778   ParseContext *pParse,                   /* fts3 query parse context */
108779   const char *zInput, int nInput,         /* Input string */
108780   Fts3Expr **ppExpr                       /* OUT: expression */
108781 ){
108782   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108783   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108784   int rc;
108785   Fts3Expr *p = 0;
108786   sqlite3_tokenizer_cursor *pCursor = 0;
108787   char *zTemp = 0;
108788   int nTemp = 0;
108789
108790   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
108791   if( rc==SQLITE_OK ){
108792     int ii;
108793     pCursor->pTokenizer = pTokenizer;
108794     for(ii=0; rc==SQLITE_OK; ii++){
108795       const char *zToken;
108796       int nToken, iBegin, iEnd, iPos;
108797       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
108798       if( rc==SQLITE_OK ){
108799         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108800         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
108801         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
108802         if( !p || !zTemp ){
108803           goto no_mem;
108804         }
108805         if( ii==0 ){
108806           memset(p, 0, nByte);
108807           p->pPhrase = (Fts3Phrase *)&p[1];
108808         }
108809         p->pPhrase = (Fts3Phrase *)&p[1];
108810         p->pPhrase->nToken = ii+1;
108811         p->pPhrase->aToken[ii].n = nToken;
108812         memcpy(&zTemp[nTemp], zToken, nToken);
108813         nTemp += nToken;
108814         if( iEnd<nInput && zInput[iEnd]=='*' ){
108815           p->pPhrase->aToken[ii].isPrefix = 1;
108816         }else{
108817           p->pPhrase->aToken[ii].isPrefix = 0;
108818         }
108819       }
108820     }
108821
108822     pModule->xClose(pCursor);
108823     pCursor = 0;
108824   }
108825
108826   if( rc==SQLITE_DONE ){
108827     int jj;
108828     char *zNew = NULL;
108829     int nNew = 0;
108830     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108831     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
108832     p = fts3ReallocOrFree(p, nByte + nTemp);
108833     if( !p ){
108834       goto no_mem;
108835     }
108836     if( zTemp ){
108837       zNew = &(((char *)p)[nByte]);
108838       memcpy(zNew, zTemp, nTemp);
108839     }else{
108840       memset(p, 0, nByte+nTemp);
108841     }
108842     p->pPhrase = (Fts3Phrase *)&p[1];
108843     for(jj=0; jj<p->pPhrase->nToken; jj++){
108844       p->pPhrase->aToken[jj].z = &zNew[nNew];
108845       nNew += p->pPhrase->aToken[jj].n;
108846     }
108847     sqlite3_free(zTemp);
108848     p->eType = FTSQUERY_PHRASE;
108849     p->pPhrase->iColumn = pParse->iDefaultCol;
108850     rc = SQLITE_OK;
108851   }
108852
108853   *ppExpr = p;
108854   return rc;
108855 no_mem:
108856
108857   if( pCursor ){
108858     pModule->xClose(pCursor);
108859   }
108860   sqlite3_free(zTemp);
108861   sqlite3_free(p);
108862   *ppExpr = 0;
108863   return SQLITE_NOMEM;
108864 }
108865
108866 /*
108867 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
108868 ** call fts3ExprParse(). So this forward declaration is required.
108869 */
108870 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
108871
108872 /*
108873 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
108874 ** structure, or set to 0 if the end of the input buffer is reached.
108875 **
108876 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
108877 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
108878 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
108879 */
108880 static int getNextNode(
108881   ParseContext *pParse,                   /* fts3 query parse context */
108882   const char *z, int n,                   /* Input string */
108883   Fts3Expr **ppExpr,                      /* OUT: expression */
108884   int *pnConsumed                         /* OUT: Number of bytes consumed */
108885 ){
108886   static const struct Fts3Keyword {
108887     char *z;                              /* Keyword text */
108888     unsigned char n;                      /* Length of the keyword */
108889     unsigned char parenOnly;              /* Only valid in paren mode */
108890     unsigned char eType;                  /* Keyword code */
108891   } aKeyword[] = {
108892     { "OR" ,  2, 0, FTSQUERY_OR   },
108893     { "AND",  3, 1, FTSQUERY_AND  },
108894     { "NOT",  3, 1, FTSQUERY_NOT  },
108895     { "NEAR", 4, 0, FTSQUERY_NEAR }
108896   };
108897   int ii;
108898   int iCol;
108899   int iColLen;
108900   int rc;
108901   Fts3Expr *pRet = 0;
108902
108903   const char *zInput = z;
108904   int nInput = n;
108905
108906   /* Skip over any whitespace before checking for a keyword, an open or
108907   ** close bracket, or a quoted string. 
108908   */
108909   while( nInput>0 && fts3isspace(*zInput) ){
108910     nInput--;
108911     zInput++;
108912   }
108913   if( nInput==0 ){
108914     return SQLITE_DONE;
108915   }
108916
108917   /* See if we are dealing with a keyword. */
108918   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
108919     const struct Fts3Keyword *pKey = &aKeyword[ii];
108920
108921     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
108922       continue;
108923     }
108924
108925     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
108926       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
108927       int nKey = pKey->n;
108928       char cNext;
108929
108930       /* If this is a "NEAR" keyword, check for an explicit nearness. */
108931       if( pKey->eType==FTSQUERY_NEAR ){
108932         assert( nKey==4 );
108933         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
108934           nNear = 0;
108935           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
108936             nNear = nNear * 10 + (zInput[nKey] - '0');
108937           }
108938         }
108939       }
108940
108941       /* At this point this is probably a keyword. But for that to be true,
108942       ** the next byte must contain either whitespace, an open or close
108943       ** parenthesis, a quote character, or EOF. 
108944       */
108945       cNext = zInput[nKey];
108946       if( fts3isspace(cNext) 
108947        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
108948       ){
108949         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
108950         if( !pRet ){
108951           return SQLITE_NOMEM;
108952         }
108953         memset(pRet, 0, sizeof(Fts3Expr));
108954         pRet->eType = pKey->eType;
108955         pRet->nNear = nNear;
108956         *ppExpr = pRet;
108957         *pnConsumed = (int)((zInput - z) + nKey);
108958         return SQLITE_OK;
108959       }
108960
108961       /* Turns out that wasn't a keyword after all. This happens if the
108962       ** user has supplied a token such as "ORacle". Continue.
108963       */
108964     }
108965   }
108966
108967   /* Check for an open bracket. */
108968   if( sqlite3_fts3_enable_parentheses ){
108969     if( *zInput=='(' ){
108970       int nConsumed;
108971       int rc;
108972       pParse->nNest++;
108973       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
108974       if( rc==SQLITE_OK && !*ppExpr ){
108975         rc = SQLITE_DONE;
108976       }
108977       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
108978       return rc;
108979     }
108980   
108981     /* Check for a close bracket. */
108982     if( *zInput==')' ){
108983       pParse->nNest--;
108984       *pnConsumed = (int)((zInput - z) + 1);
108985       return SQLITE_DONE;
108986     }
108987   }
108988
108989   /* See if we are dealing with a quoted phrase. If this is the case, then
108990   ** search for the closing quote and pass the whole string to getNextString()
108991   ** for processing. This is easy to do, as fts3 has no syntax for escaping
108992   ** a quote character embedded in a string.
108993   */
108994   if( *zInput=='"' ){
108995     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
108996     *pnConsumed = (int)((zInput - z) + ii + 1);
108997     if( ii==nInput ){
108998       return SQLITE_ERROR;
108999     }
109000     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
109001   }
109002
109003
109004   /* If control flows to this point, this must be a regular token, or 
109005   ** the end of the input. Read a regular token using the sqlite3_tokenizer
109006   ** interface. Before doing so, figure out if there is an explicit
109007   ** column specifier for the token. 
109008   **
109009   ** TODO: Strangely, it is not possible to associate a column specifier
109010   ** with a quoted phrase, only with a single token. Not sure if this was
109011   ** an implementation artifact or an intentional decision when fts3 was
109012   ** first implemented. Whichever it was, this module duplicates the 
109013   ** limitation.
109014   */
109015   iCol = pParse->iDefaultCol;
109016   iColLen = 0;
109017   for(ii=0; ii<pParse->nCol; ii++){
109018     const char *zStr = pParse->azCol[ii];
109019     int nStr = (int)strlen(zStr);
109020     if( nInput>nStr && zInput[nStr]==':' 
109021      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
109022     ){
109023       iCol = ii;
109024       iColLen = (int)((zInput - z) + nStr + 1);
109025       break;
109026     }
109027   }
109028   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
109029   *pnConsumed += iColLen;
109030   return rc;
109031 }
109032
109033 /*
109034 ** The argument is an Fts3Expr structure for a binary operator (any type
109035 ** except an FTSQUERY_PHRASE). Return an integer value representing the
109036 ** precedence of the operator. Lower values have a higher precedence (i.e.
109037 ** group more tightly). For example, in the C language, the == operator
109038 ** groups more tightly than ||, and would therefore have a higher precedence.
109039 **
109040 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
109041 ** is defined), the order of the operators in precedence from highest to
109042 ** lowest is:
109043 **
109044 **   NEAR
109045 **   NOT
109046 **   AND (including implicit ANDs)
109047 **   OR
109048 **
109049 ** Note that when using the old query syntax, the OR operator has a higher
109050 ** precedence than the AND operator.
109051 */
109052 static int opPrecedence(Fts3Expr *p){
109053   assert( p->eType!=FTSQUERY_PHRASE );
109054   if( sqlite3_fts3_enable_parentheses ){
109055     return p->eType;
109056   }else if( p->eType==FTSQUERY_NEAR ){
109057     return 1;
109058   }else if( p->eType==FTSQUERY_OR ){
109059     return 2;
109060   }
109061   assert( p->eType==FTSQUERY_AND );
109062   return 3;
109063 }
109064
109065 /*
109066 ** Argument ppHead contains a pointer to the current head of a query 
109067 ** expression tree being parsed. pPrev is the expression node most recently
109068 ** inserted into the tree. This function adds pNew, which is always a binary
109069 ** operator node, into the expression tree based on the relative precedence
109070 ** of pNew and the existing nodes of the tree. This may result in the head
109071 ** of the tree changing, in which case *ppHead is set to the new root node.
109072 */
109073 static void insertBinaryOperator(
109074   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
109075   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
109076   Fts3Expr *pNew           /* New binary node to insert into expression tree */
109077 ){
109078   Fts3Expr *pSplit = pPrev;
109079   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
109080     pSplit = pSplit->pParent;
109081   }
109082
109083   if( pSplit->pParent ){
109084     assert( pSplit->pParent->pRight==pSplit );
109085     pSplit->pParent->pRight = pNew;
109086     pNew->pParent = pSplit->pParent;
109087   }else{
109088     *ppHead = pNew;
109089   }
109090   pNew->pLeft = pSplit;
109091   pSplit->pParent = pNew;
109092 }
109093
109094 /*
109095 ** Parse the fts3 query expression found in buffer z, length n. This function
109096 ** returns either when the end of the buffer is reached or an unmatched 
109097 ** closing bracket - ')' - is encountered.
109098 **
109099 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
109100 ** parsed form of the expression and *pnConsumed is set to the number of
109101 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
109102 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
109103 */
109104 static int fts3ExprParse(
109105   ParseContext *pParse,                   /* fts3 query parse context */
109106   const char *z, int n,                   /* Text of MATCH query */
109107   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
109108   int *pnConsumed                         /* OUT: Number of bytes consumed */
109109 ){
109110   Fts3Expr *pRet = 0;
109111   Fts3Expr *pPrev = 0;
109112   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
109113   int nIn = n;
109114   const char *zIn = z;
109115   int rc = SQLITE_OK;
109116   int isRequirePhrase = 1;
109117
109118   while( rc==SQLITE_OK ){
109119     Fts3Expr *p = 0;
109120     int nByte = 0;
109121     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
109122     if( rc==SQLITE_OK ){
109123       int isPhrase;
109124
109125       if( !sqlite3_fts3_enable_parentheses 
109126        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
109127       ){
109128         /* Create an implicit NOT operator. */
109129         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
109130         if( !pNot ){
109131           sqlite3Fts3ExprFree(p);
109132           rc = SQLITE_NOMEM;
109133           goto exprparse_out;
109134         }
109135         memset(pNot, 0, sizeof(Fts3Expr));
109136         pNot->eType = FTSQUERY_NOT;
109137         pNot->pRight = p;
109138         if( pNotBranch ){
109139           pNot->pLeft = pNotBranch;
109140         }
109141         pNotBranch = pNot;
109142         p = pPrev;
109143       }else{
109144         int eType = p->eType;
109145         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
109146         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
109147
109148         /* The isRequirePhrase variable is set to true if a phrase or
109149         ** an expression contained in parenthesis is required. If a
109150         ** binary operator (AND, OR, NOT or NEAR) is encounted when
109151         ** isRequirePhrase is set, this is a syntax error.
109152         */
109153         if( !isPhrase && isRequirePhrase ){
109154           sqlite3Fts3ExprFree(p);
109155           rc = SQLITE_ERROR;
109156           goto exprparse_out;
109157         }
109158   
109159         if( isPhrase && !isRequirePhrase ){
109160           /* Insert an implicit AND operator. */
109161           Fts3Expr *pAnd;
109162           assert( pRet && pPrev );
109163           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
109164           if( !pAnd ){
109165             sqlite3Fts3ExprFree(p);
109166             rc = SQLITE_NOMEM;
109167             goto exprparse_out;
109168           }
109169           memset(pAnd, 0, sizeof(Fts3Expr));
109170           pAnd->eType = FTSQUERY_AND;
109171           insertBinaryOperator(&pRet, pPrev, pAnd);
109172           pPrev = pAnd;
109173         }
109174
109175         /* This test catches attempts to make either operand of a NEAR
109176         ** operator something other than a phrase. For example, either of
109177         ** the following:
109178         **
109179         **    (bracketed expression) NEAR phrase
109180         **    phrase NEAR (bracketed expression)
109181         **
109182         ** Return an error in either case.
109183         */
109184         if( pPrev && (
109185             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
109186          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
109187         )){
109188           sqlite3Fts3ExprFree(p);
109189           rc = SQLITE_ERROR;
109190           goto exprparse_out;
109191         }
109192   
109193         if( isPhrase ){
109194           if( pRet ){
109195             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
109196             pPrev->pRight = p;
109197             p->pParent = pPrev;
109198           }else{
109199             pRet = p;
109200           }
109201         }else{
109202           insertBinaryOperator(&pRet, pPrev, p);
109203         }
109204         isRequirePhrase = !isPhrase;
109205       }
109206       assert( nByte>0 );
109207     }
109208     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
109209     nIn -= nByte;
109210     zIn += nByte;
109211     pPrev = p;
109212   }
109213
109214   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
109215     rc = SQLITE_ERROR;
109216   }
109217
109218   if( rc==SQLITE_DONE ){
109219     rc = SQLITE_OK;
109220     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
109221       if( !pRet ){
109222         rc = SQLITE_ERROR;
109223       }else{
109224         Fts3Expr *pIter = pNotBranch;
109225         while( pIter->pLeft ){
109226           pIter = pIter->pLeft;
109227         }
109228         pIter->pLeft = pRet;
109229         pRet = pNotBranch;
109230       }
109231     }
109232   }
109233   *pnConsumed = n - nIn;
109234
109235 exprparse_out:
109236   if( rc!=SQLITE_OK ){
109237     sqlite3Fts3ExprFree(pRet);
109238     sqlite3Fts3ExprFree(pNotBranch);
109239     pRet = 0;
109240   }
109241   *ppExpr = pRet;
109242   return rc;
109243 }
109244
109245 /*
109246 ** Parameters z and n contain a pointer to and length of a buffer containing
109247 ** an fts3 query expression, respectively. This function attempts to parse the
109248 ** query expression and create a tree of Fts3Expr structures representing the
109249 ** parsed expression. If successful, *ppExpr is set to point to the head
109250 ** of the parsed expression tree and SQLITE_OK is returned. If an error
109251 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
109252 ** error) is returned and *ppExpr is set to 0.
109253 **
109254 ** If parameter n is a negative number, then z is assumed to point to a
109255 ** nul-terminated string and the length is determined using strlen().
109256 **
109257 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
109258 ** use to normalize query tokens while parsing the expression. The azCol[]
109259 ** array, which is assumed to contain nCol entries, should contain the names
109260 ** of each column in the target fts3 table, in order from left to right. 
109261 ** Column names must be nul-terminated strings.
109262 **
109263 ** The iDefaultCol parameter should be passed the index of the table column
109264 ** that appears on the left-hand-side of the MATCH operator (the default
109265 ** column to match against for tokens for which a column name is not explicitly
109266 ** specified as part of the query string), or -1 if tokens may by default
109267 ** match any table column.
109268 */
109269 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
109270   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
109271   char **azCol,                       /* Array of column names for fts3 table */
109272   int nCol,                           /* Number of entries in azCol[] */
109273   int iDefaultCol,                    /* Default column to query */
109274   const char *z, int n,               /* Text of MATCH query */
109275   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
109276 ){
109277   int nParsed;
109278   int rc;
109279   ParseContext sParse;
109280   sParse.pTokenizer = pTokenizer;
109281   sParse.azCol = (const char **)azCol;
109282   sParse.nCol = nCol;
109283   sParse.iDefaultCol = iDefaultCol;
109284   sParse.nNest = 0;
109285   if( z==0 ){
109286     *ppExpr = 0;
109287     return SQLITE_OK;
109288   }
109289   if( n<0 ){
109290     n = (int)strlen(z);
109291   }
109292   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
109293
109294   /* Check for mismatched parenthesis */
109295   if( rc==SQLITE_OK && sParse.nNest ){
109296     rc = SQLITE_ERROR;
109297     sqlite3Fts3ExprFree(*ppExpr);
109298     *ppExpr = 0;
109299   }
109300
109301   return rc;
109302 }
109303
109304 /*
109305 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
109306 */
109307 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
109308   if( p ){
109309     sqlite3Fts3ExprFree(p->pLeft);
109310     sqlite3Fts3ExprFree(p->pRight);
109311     sqlite3_free(p->aDoclist);
109312     sqlite3_free(p);
109313   }
109314 }
109315
109316 /****************************************************************************
109317 *****************************************************************************
109318 ** Everything after this point is just test code.
109319 */
109320
109321 #ifdef SQLITE_TEST
109322
109323
109324 /*
109325 ** Function to query the hash-table of tokenizers (see README.tokenizers).
109326 */
109327 static int queryTestTokenizer(
109328   sqlite3 *db, 
109329   const char *zName,  
109330   const sqlite3_tokenizer_module **pp
109331 ){
109332   int rc;
109333   sqlite3_stmt *pStmt;
109334   const char zSql[] = "SELECT fts3_tokenizer(?)";
109335
109336   *pp = 0;
109337   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
109338   if( rc!=SQLITE_OK ){
109339     return rc;
109340   }
109341
109342   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
109343   if( SQLITE_ROW==sqlite3_step(pStmt) ){
109344     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
109345       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
109346     }
109347   }
109348
109349   return sqlite3_finalize(pStmt);
109350 }
109351
109352 /*
109353 ** This function is part of the test interface for the query parser. It
109354 ** writes a text representation of the query expression pExpr into the
109355 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
109356 ** enough to store the required text representation.
109357 */
109358 static void exprToString(Fts3Expr *pExpr, char *zBuf){
109359   switch( pExpr->eType ){
109360     case FTSQUERY_PHRASE: {
109361       Fts3Phrase *pPhrase = pExpr->pPhrase;
109362       int i;
109363       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
109364       for(i=0; i<pPhrase->nToken; i++){
109365         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
109366         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
109367       }
109368       return;
109369     }
109370
109371     case FTSQUERY_NEAR:
109372       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
109373       break;
109374     case FTSQUERY_NOT:
109375       zBuf += sprintf(zBuf, "NOT ");
109376       break;
109377     case FTSQUERY_AND:
109378       zBuf += sprintf(zBuf, "AND ");
109379       break;
109380     case FTSQUERY_OR:
109381       zBuf += sprintf(zBuf, "OR ");
109382       break;
109383   }
109384
109385   zBuf += sprintf(zBuf, "{");
109386   exprToString(pExpr->pLeft, zBuf);
109387   zBuf += strlen(zBuf);
109388   zBuf += sprintf(zBuf, "} ");
109389
109390   zBuf += sprintf(zBuf, "{");
109391   exprToString(pExpr->pRight, zBuf);
109392   zBuf += strlen(zBuf);
109393   zBuf += sprintf(zBuf, "}");
109394 }
109395
109396 /*
109397 ** This is the implementation of a scalar SQL function used to test the 
109398 ** expression parser. It should be called as follows:
109399 **
109400 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
109401 **
109402 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
109403 ** to parse the query expression (see README.tokenizers). The second argument
109404 ** is the query expression to parse. Each subsequent argument is the name
109405 ** of a column of the fts3 table that the query expression may refer to.
109406 ** For example:
109407 **
109408 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
109409 */
109410 static void fts3ExprTest(
109411   sqlite3_context *context,
109412   int argc,
109413   sqlite3_value **argv
109414 ){
109415   sqlite3_tokenizer_module const *pModule = 0;
109416   sqlite3_tokenizer *pTokenizer = 0;
109417   int rc;
109418   char **azCol = 0;
109419   const char *zExpr;
109420   int nExpr;
109421   int nCol;
109422   int ii;
109423   Fts3Expr *pExpr;
109424   sqlite3 *db = sqlite3_context_db_handle(context);
109425
109426   if( argc<3 ){
109427     sqlite3_result_error(context, 
109428         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
109429     );
109430     return;
109431   }
109432
109433   rc = queryTestTokenizer(db,
109434                           (const char *)sqlite3_value_text(argv[0]), &pModule);
109435   if( rc==SQLITE_NOMEM ){
109436     sqlite3_result_error_nomem(context);
109437     goto exprtest_out;
109438   }else if( !pModule ){
109439     sqlite3_result_error(context, "No such tokenizer module", -1);
109440     goto exprtest_out;
109441   }
109442
109443   rc = pModule->xCreate(0, 0, &pTokenizer);
109444   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
109445   if( rc==SQLITE_NOMEM ){
109446     sqlite3_result_error_nomem(context);
109447     goto exprtest_out;
109448   }
109449   pTokenizer->pModule = pModule;
109450
109451   zExpr = (const char *)sqlite3_value_text(argv[1]);
109452   nExpr = sqlite3_value_bytes(argv[1]);
109453   nCol = argc-2;
109454   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
109455   if( !azCol ){
109456     sqlite3_result_error_nomem(context);
109457     goto exprtest_out;
109458   }
109459   for(ii=0; ii<nCol; ii++){
109460     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
109461   }
109462
109463   rc = sqlite3Fts3ExprParse(
109464       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
109465   );
109466   if( rc==SQLITE_NOMEM ){
109467     sqlite3_result_error_nomem(context);
109468     goto exprtest_out;
109469   }else if( rc==SQLITE_OK ){
109470     char zBuf[4096];
109471     exprToString(pExpr, zBuf);
109472     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
109473     sqlite3Fts3ExprFree(pExpr);
109474   }else{
109475     sqlite3_result_error(context, "Error parsing expression", -1);
109476   }
109477
109478 exprtest_out:
109479   if( pModule && pTokenizer ){
109480     rc = pModule->xDestroy(pTokenizer);
109481   }
109482   sqlite3_free(azCol);
109483 }
109484
109485 /*
109486 ** Register the query expression parser test function fts3_exprtest() 
109487 ** with database connection db. 
109488 */
109489 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
109490   return sqlite3_create_function(
109491       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
109492   );
109493 }
109494
109495 #endif
109496 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109497
109498 /************** End of fts3_expr.c *******************************************/
109499 /************** Begin file fts3_hash.c ***************************************/
109500 /*
109501 ** 2001 September 22
109502 **
109503 ** The author disclaims copyright to this source code.  In place of
109504 ** a legal notice, here is a blessing:
109505 **
109506 **    May you do good and not evil.
109507 **    May you find forgiveness for yourself and forgive others.
109508 **    May you share freely, never taking more than you give.
109509 **
109510 *************************************************************************
109511 ** This is the implementation of generic hash-tables used in SQLite.
109512 ** We've modified it slightly to serve as a standalone hash table
109513 ** implementation for the full-text indexing module.
109514 */
109515
109516 /*
109517 ** The code in this file is only compiled if:
109518 **
109519 **     * The FTS3 module is being built as an extension
109520 **       (in which case SQLITE_CORE is not defined), or
109521 **
109522 **     * The FTS3 module is being built into the core of
109523 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109524 */
109525 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109526
109527
109528
109529 /*
109530 ** Malloc and Free functions
109531 */
109532 static void *fts3HashMalloc(int n){
109533   void *p = sqlite3_malloc(n);
109534   if( p ){
109535     memset(p, 0, n);
109536   }
109537   return p;
109538 }
109539 static void fts3HashFree(void *p){
109540   sqlite3_free(p);
109541 }
109542
109543 /* Turn bulk memory into a hash table object by initializing the
109544 ** fields of the Hash structure.
109545 **
109546 ** "pNew" is a pointer to the hash table that is to be initialized.
109547 ** keyClass is one of the constants 
109548 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
109549 ** determines what kind of key the hash table will use.  "copyKey" is
109550 ** true if the hash table should make its own private copy of keys and
109551 ** false if it should just use the supplied pointer.
109552 */
109553 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
109554   assert( pNew!=0 );
109555   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
109556   pNew->keyClass = keyClass;
109557   pNew->copyKey = copyKey;
109558   pNew->first = 0;
109559   pNew->count = 0;
109560   pNew->htsize = 0;
109561   pNew->ht = 0;
109562 }
109563
109564 /* Remove all entries from a hash table.  Reclaim all memory.
109565 ** Call this routine to delete a hash table or to reset a hash table
109566 ** to the empty state.
109567 */
109568 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
109569   Fts3HashElem *elem;         /* For looping over all elements of the table */
109570
109571   assert( pH!=0 );
109572   elem = pH->first;
109573   pH->first = 0;
109574   fts3HashFree(pH->ht);
109575   pH->ht = 0;
109576   pH->htsize = 0;
109577   while( elem ){
109578     Fts3HashElem *next_elem = elem->next;
109579     if( pH->copyKey && elem->pKey ){
109580       fts3HashFree(elem->pKey);
109581     }
109582     fts3HashFree(elem);
109583     elem = next_elem;
109584   }
109585   pH->count = 0;
109586 }
109587
109588 /*
109589 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
109590 */
109591 static int fts3StrHash(const void *pKey, int nKey){
109592   const char *z = (const char *)pKey;
109593   int h = 0;
109594   if( nKey<=0 ) nKey = (int) strlen(z);
109595   while( nKey > 0  ){
109596     h = (h<<3) ^ h ^ *z++;
109597     nKey--;
109598   }
109599   return h & 0x7fffffff;
109600 }
109601 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109602   if( n1!=n2 ) return 1;
109603   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
109604 }
109605
109606 /*
109607 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
109608 */
109609 static int fts3BinHash(const void *pKey, int nKey){
109610   int h = 0;
109611   const char *z = (const char *)pKey;
109612   while( nKey-- > 0 ){
109613     h = (h<<3) ^ h ^ *(z++);
109614   }
109615   return h & 0x7fffffff;
109616 }
109617 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109618   if( n1!=n2 ) return 1;
109619   return memcmp(pKey1,pKey2,n1);
109620 }
109621
109622 /*
109623 ** Return a pointer to the appropriate hash function given the key class.
109624 **
109625 ** The C syntax in this function definition may be unfamilar to some 
109626 ** programmers, so we provide the following additional explanation:
109627 **
109628 ** The name of the function is "ftsHashFunction".  The function takes a
109629 ** single parameter "keyClass".  The return value of ftsHashFunction()
109630 ** is a pointer to another function.  Specifically, the return value
109631 ** of ftsHashFunction() is a pointer to a function that takes two parameters
109632 ** with types "const void*" and "int" and returns an "int".
109633 */
109634 static int (*ftsHashFunction(int keyClass))(const void*,int){
109635   if( keyClass==FTS3_HASH_STRING ){
109636     return &fts3StrHash;
109637   }else{
109638     assert( keyClass==FTS3_HASH_BINARY );
109639     return &fts3BinHash;
109640   }
109641 }
109642
109643 /*
109644 ** Return a pointer to the appropriate hash function given the key class.
109645 **
109646 ** For help in interpreted the obscure C code in the function definition,
109647 ** see the header comment on the previous function.
109648 */
109649 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
109650   if( keyClass==FTS3_HASH_STRING ){
109651     return &fts3StrCompare;
109652   }else{
109653     assert( keyClass==FTS3_HASH_BINARY );
109654     return &fts3BinCompare;
109655   }
109656 }
109657
109658 /* Link an element into the hash table
109659 */
109660 static void fts3HashInsertElement(
109661   Fts3Hash *pH,            /* The complete hash table */
109662   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
109663   Fts3HashElem *pNew       /* The element to be inserted */
109664 ){
109665   Fts3HashElem *pHead;     /* First element already in pEntry */
109666   pHead = pEntry->chain;
109667   if( pHead ){
109668     pNew->next = pHead;
109669     pNew->prev = pHead->prev;
109670     if( pHead->prev ){ pHead->prev->next = pNew; }
109671     else             { pH->first = pNew; }
109672     pHead->prev = pNew;
109673   }else{
109674     pNew->next = pH->first;
109675     if( pH->first ){ pH->first->prev = pNew; }
109676     pNew->prev = 0;
109677     pH->first = pNew;
109678   }
109679   pEntry->count++;
109680   pEntry->chain = pNew;
109681 }
109682
109683
109684 /* Resize the hash table so that it cantains "new_size" buckets.
109685 ** "new_size" must be a power of 2.  The hash table might fail 
109686 ** to resize if sqliteMalloc() fails.
109687 **
109688 ** Return non-zero if a memory allocation error occurs.
109689 */
109690 static int fts3Rehash(Fts3Hash *pH, int new_size){
109691   struct _fts3ht *new_ht;          /* The new hash table */
109692   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
109693   int (*xHash)(const void*,int);   /* The hash function */
109694
109695   assert( (new_size & (new_size-1))==0 );
109696   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
109697   if( new_ht==0 ) return 1;
109698   fts3HashFree(pH->ht);
109699   pH->ht = new_ht;
109700   pH->htsize = new_size;
109701   xHash = ftsHashFunction(pH->keyClass);
109702   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
109703     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
109704     next_elem = elem->next;
109705     fts3HashInsertElement(pH, &new_ht[h], elem);
109706   }
109707   return 0;
109708 }
109709
109710 /* This function (for internal use only) locates an element in an
109711 ** hash table that matches the given key.  The hash for this key has
109712 ** already been computed and is passed as the 4th parameter.
109713 */
109714 static Fts3HashElem *fts3FindElementByHash(
109715   const Fts3Hash *pH, /* The pH to be searched */
109716   const void *pKey,   /* The key we are searching for */
109717   int nKey,
109718   int h               /* The hash for this key. */
109719 ){
109720   Fts3HashElem *elem;            /* Used to loop thru the element list */
109721   int count;                     /* Number of elements left to test */
109722   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
109723
109724   if( pH->ht ){
109725     struct _fts3ht *pEntry = &pH->ht[h];
109726     elem = pEntry->chain;
109727     count = pEntry->count;
109728     xCompare = ftsCompareFunction(pH->keyClass);
109729     while( count-- && elem ){
109730       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
109731         return elem;
109732       }
109733       elem = elem->next;
109734     }
109735   }
109736   return 0;
109737 }
109738
109739 /* Remove a single entry from the hash table given a pointer to that
109740 ** element and a hash on the element's key.
109741 */
109742 static void fts3RemoveElementByHash(
109743   Fts3Hash *pH,         /* The pH containing "elem" */
109744   Fts3HashElem* elem,   /* The element to be removed from the pH */
109745   int h                 /* Hash value for the element */
109746 ){
109747   struct _fts3ht *pEntry;
109748   if( elem->prev ){
109749     elem->prev->next = elem->next; 
109750   }else{
109751     pH->first = elem->next;
109752   }
109753   if( elem->next ){
109754     elem->next->prev = elem->prev;
109755   }
109756   pEntry = &pH->ht[h];
109757   if( pEntry->chain==elem ){
109758     pEntry->chain = elem->next;
109759   }
109760   pEntry->count--;
109761   if( pEntry->count<=0 ){
109762     pEntry->chain = 0;
109763   }
109764   if( pH->copyKey && elem->pKey ){
109765     fts3HashFree(elem->pKey);
109766   }
109767   fts3HashFree( elem );
109768   pH->count--;
109769   if( pH->count<=0 ){
109770     assert( pH->first==0 );
109771     assert( pH->count==0 );
109772     fts3HashClear(pH);
109773   }
109774 }
109775
109776 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
109777   const Fts3Hash *pH, 
109778   const void *pKey, 
109779   int nKey
109780 ){
109781   int h;                          /* A hash on key */
109782   int (*xHash)(const void*,int);  /* The hash function */
109783
109784   if( pH==0 || pH->ht==0 ) return 0;
109785   xHash = ftsHashFunction(pH->keyClass);
109786   assert( xHash!=0 );
109787   h = (*xHash)(pKey,nKey);
109788   assert( (pH->htsize & (pH->htsize-1))==0 );
109789   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
109790 }
109791
109792 /* 
109793 ** Attempt to locate an element of the hash table pH with a key
109794 ** that matches pKey,nKey.  Return the data for this element if it is
109795 ** found, or NULL if there is no match.
109796 */
109797 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
109798   Fts3HashElem *pElem;            /* The element that matches key (if any) */
109799
109800   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
109801   return pElem ? pElem->data : 0;
109802 }
109803
109804 /* Insert an element into the hash table pH.  The key is pKey,nKey
109805 ** and the data is "data".
109806 **
109807 ** If no element exists with a matching key, then a new
109808 ** element is created.  A copy of the key is made if the copyKey
109809 ** flag is set.  NULL is returned.
109810 **
109811 ** If another element already exists with the same key, then the
109812 ** new data replaces the old data and the old data is returned.
109813 ** The key is not copied in this instance.  If a malloc fails, then
109814 ** the new data is returned and the hash table is unchanged.
109815 **
109816 ** If the "data" parameter to this function is NULL, then the
109817 ** element corresponding to "key" is removed from the hash table.
109818 */
109819 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
109820   Fts3Hash *pH,        /* The hash table to insert into */
109821   const void *pKey,    /* The key */
109822   int nKey,            /* Number of bytes in the key */
109823   void *data           /* The data */
109824 ){
109825   int hraw;                 /* Raw hash value of the key */
109826   int h;                    /* the hash of the key modulo hash table size */
109827   Fts3HashElem *elem;       /* Used to loop thru the element list */
109828   Fts3HashElem *new_elem;   /* New element added to the pH */
109829   int (*xHash)(const void*,int);  /* The hash function */
109830
109831   assert( pH!=0 );
109832   xHash = ftsHashFunction(pH->keyClass);
109833   assert( xHash!=0 );
109834   hraw = (*xHash)(pKey, nKey);
109835   assert( (pH->htsize & (pH->htsize-1))==0 );
109836   h = hraw & (pH->htsize-1);
109837   elem = fts3FindElementByHash(pH,pKey,nKey,h);
109838   if( elem ){
109839     void *old_data = elem->data;
109840     if( data==0 ){
109841       fts3RemoveElementByHash(pH,elem,h);
109842     }else{
109843       elem->data = data;
109844     }
109845     return old_data;
109846   }
109847   if( data==0 ) return 0;
109848   if( (pH->htsize==0 && fts3Rehash(pH,8))
109849    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
109850   ){
109851     pH->count = 0;
109852     return data;
109853   }
109854   assert( pH->htsize>0 );
109855   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
109856   if( new_elem==0 ) return data;
109857   if( pH->copyKey && pKey!=0 ){
109858     new_elem->pKey = fts3HashMalloc( nKey );
109859     if( new_elem->pKey==0 ){
109860       fts3HashFree(new_elem);
109861       return data;
109862     }
109863     memcpy((void*)new_elem->pKey, pKey, nKey);
109864   }else{
109865     new_elem->pKey = (void*)pKey;
109866   }
109867   new_elem->nKey = nKey;
109868   pH->count++;
109869   assert( pH->htsize>0 );
109870   assert( (pH->htsize & (pH->htsize-1))==0 );
109871   h = hraw & (pH->htsize-1);
109872   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
109873   new_elem->data = data;
109874   return 0;
109875 }
109876
109877 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109878
109879 /************** End of fts3_hash.c *******************************************/
109880 /************** Begin file fts3_porter.c *************************************/
109881 /*
109882 ** 2006 September 30
109883 **
109884 ** The author disclaims copyright to this source code.  In place of
109885 ** a legal notice, here is a blessing:
109886 **
109887 **    May you do good and not evil.
109888 **    May you find forgiveness for yourself and forgive others.
109889 **    May you share freely, never taking more than you give.
109890 **
109891 *************************************************************************
109892 ** Implementation of the full-text-search tokenizer that implements
109893 ** a Porter stemmer.
109894 */
109895
109896 /*
109897 ** The code in this file is only compiled if:
109898 **
109899 **     * The FTS3 module is being built as an extension
109900 **       (in which case SQLITE_CORE is not defined), or
109901 **
109902 **     * The FTS3 module is being built into the core of
109903 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109904 */
109905 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109906
109907
109908
109909
109910 /*
109911 ** Class derived from sqlite3_tokenizer
109912 */
109913 typedef struct porter_tokenizer {
109914   sqlite3_tokenizer base;      /* Base class */
109915 } porter_tokenizer;
109916
109917 /*
109918 ** Class derived from sqlit3_tokenizer_cursor
109919 */
109920 typedef struct porter_tokenizer_cursor {
109921   sqlite3_tokenizer_cursor base;
109922   const char *zInput;          /* input we are tokenizing */
109923   int nInput;                  /* size of the input */
109924   int iOffset;                 /* current position in zInput */
109925   int iToken;                  /* index of next token to be returned */
109926   char *zToken;                /* storage for current token */
109927   int nAllocated;              /* space allocated to zToken buffer */
109928 } porter_tokenizer_cursor;
109929
109930
109931 /*
109932 ** Create a new tokenizer instance.
109933 */
109934 static int porterCreate(
109935   int argc, const char * const *argv,
109936   sqlite3_tokenizer **ppTokenizer
109937 ){
109938   porter_tokenizer *t;
109939
109940   UNUSED_PARAMETER(argc);
109941   UNUSED_PARAMETER(argv);
109942
109943   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
109944   if( t==NULL ) return SQLITE_NOMEM;
109945   memset(t, 0, sizeof(*t));
109946   *ppTokenizer = &t->base;
109947   return SQLITE_OK;
109948 }
109949
109950 /*
109951 ** Destroy a tokenizer
109952 */
109953 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
109954   sqlite3_free(pTokenizer);
109955   return SQLITE_OK;
109956 }
109957
109958 /*
109959 ** Prepare to begin tokenizing a particular string.  The input
109960 ** string to be tokenized is zInput[0..nInput-1].  A cursor
109961 ** used to incrementally tokenize this string is returned in 
109962 ** *ppCursor.
109963 */
109964 static int porterOpen(
109965   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
109966   const char *zInput, int nInput,        /* String to be tokenized */
109967   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
109968 ){
109969   porter_tokenizer_cursor *c;
109970
109971   UNUSED_PARAMETER(pTokenizer);
109972
109973   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
109974   if( c==NULL ) return SQLITE_NOMEM;
109975
109976   c->zInput = zInput;
109977   if( zInput==0 ){
109978     c->nInput = 0;
109979   }else if( nInput<0 ){
109980     c->nInput = (int)strlen(zInput);
109981   }else{
109982     c->nInput = nInput;
109983   }
109984   c->iOffset = 0;                 /* start tokenizing at the beginning */
109985   c->iToken = 0;
109986   c->zToken = NULL;               /* no space allocated, yet. */
109987   c->nAllocated = 0;
109988
109989   *ppCursor = &c->base;
109990   return SQLITE_OK;
109991 }
109992
109993 /*
109994 ** Close a tokenization cursor previously opened by a call to
109995 ** porterOpen() above.
109996 */
109997 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
109998   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
109999   sqlite3_free(c->zToken);
110000   sqlite3_free(c);
110001   return SQLITE_OK;
110002 }
110003 /*
110004 ** Vowel or consonant
110005 */
110006 static const char cType[] = {
110007    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
110008    1, 1, 1, 2, 1
110009 };
110010
110011 /*
110012 ** isConsonant() and isVowel() determine if their first character in
110013 ** the string they point to is a consonant or a vowel, according
110014 ** to Porter ruls.  
110015 **
110016 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
110017 ** 'Y' is a consonant unless it follows another consonant,
110018 ** in which case it is a vowel.
110019 **
110020 ** In these routine, the letters are in reverse order.  So the 'y' rule
110021 ** is that 'y' is a consonant unless it is followed by another
110022 ** consonent.
110023 */
110024 static int isVowel(const char*);
110025 static int isConsonant(const char *z){
110026   int j;
110027   char x = *z;
110028   if( x==0 ) return 0;
110029   assert( x>='a' && x<='z' );
110030   j = cType[x-'a'];
110031   if( j<2 ) return j;
110032   return z[1]==0 || isVowel(z + 1);
110033 }
110034 static int isVowel(const char *z){
110035   int j;
110036   char x = *z;
110037   if( x==0 ) return 0;
110038   assert( x>='a' && x<='z' );
110039   j = cType[x-'a'];
110040   if( j<2 ) return 1-j;
110041   return isConsonant(z + 1);
110042 }
110043
110044 /*
110045 ** Let any sequence of one or more vowels be represented by V and let
110046 ** C be sequence of one or more consonants.  Then every word can be
110047 ** represented as:
110048 **
110049 **           [C] (VC){m} [V]
110050 **
110051 ** In prose:  A word is an optional consonant followed by zero or
110052 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
110053 ** number of vowel consonant pairs.  This routine computes the value
110054 ** of m for the first i bytes of a word.
110055 **
110056 ** Return true if the m-value for z is 1 or more.  In other words,
110057 ** return true if z contains at least one vowel that is followed
110058 ** by a consonant.
110059 **
110060 ** In this routine z[] is in reverse order.  So we are really looking
110061 ** for an instance of of a consonant followed by a vowel.
110062 */
110063 static int m_gt_0(const char *z){
110064   while( isVowel(z) ){ z++; }
110065   if( *z==0 ) return 0;
110066   while( isConsonant(z) ){ z++; }
110067   return *z!=0;
110068 }
110069
110070 /* Like mgt0 above except we are looking for a value of m which is
110071 ** exactly 1
110072 */
110073 static int m_eq_1(const char *z){
110074   while( isVowel(z) ){ z++; }
110075   if( *z==0 ) return 0;
110076   while( isConsonant(z) ){ z++; }
110077   if( *z==0 ) return 0;
110078   while( isVowel(z) ){ z++; }
110079   if( *z==0 ) return 1;
110080   while( isConsonant(z) ){ z++; }
110081   return *z==0;
110082 }
110083
110084 /* Like mgt0 above except we are looking for a value of m>1 instead
110085 ** or m>0
110086 */
110087 static int m_gt_1(const char *z){
110088   while( isVowel(z) ){ z++; }
110089   if( *z==0 ) return 0;
110090   while( isConsonant(z) ){ z++; }
110091   if( *z==0 ) return 0;
110092   while( isVowel(z) ){ z++; }
110093   if( *z==0 ) return 0;
110094   while( isConsonant(z) ){ z++; }
110095   return *z!=0;
110096 }
110097
110098 /*
110099 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
110100 */
110101 static int hasVowel(const char *z){
110102   while( isConsonant(z) ){ z++; }
110103   return *z!=0;
110104 }
110105
110106 /*
110107 ** Return TRUE if the word ends in a double consonant.
110108 **
110109 ** The text is reversed here. So we are really looking at
110110 ** the first two characters of z[].
110111 */
110112 static int doubleConsonant(const char *z){
110113   return isConsonant(z) && z[0]==z[1];
110114 }
110115
110116 /*
110117 ** Return TRUE if the word ends with three letters which
110118 ** are consonant-vowel-consonent and where the final consonant
110119 ** is not 'w', 'x', or 'y'.
110120 **
110121 ** The word is reversed here.  So we are really checking the
110122 ** first three letters and the first one cannot be in [wxy].
110123 */
110124 static int star_oh(const char *z){
110125   return
110126     isConsonant(z) &&
110127     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
110128     isVowel(z+1) &&
110129     isConsonant(z+2);
110130 }
110131
110132 /*
110133 ** If the word ends with zFrom and xCond() is true for the stem
110134 ** of the word that preceeds the zFrom ending, then change the 
110135 ** ending to zTo.
110136 **
110137 ** The input word *pz and zFrom are both in reverse order.  zTo
110138 ** is in normal order. 
110139 **
110140 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
110141 ** match.  Not that TRUE is returned even if xCond() fails and
110142 ** no substitution occurs.
110143 */
110144 static int stem(
110145   char **pz,             /* The word being stemmed (Reversed) */
110146   const char *zFrom,     /* If the ending matches this... (Reversed) */
110147   const char *zTo,       /* ... change the ending to this (not reversed) */
110148   int (*xCond)(const char*)   /* Condition that must be true */
110149 ){
110150   char *z = *pz;
110151   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
110152   if( *zFrom!=0 ) return 0;
110153   if( xCond && !xCond(z) ) return 1;
110154   while( *zTo ){
110155     *(--z) = *(zTo++);
110156   }
110157   *pz = z;
110158   return 1;
110159 }
110160
110161 /*
110162 ** This is the fallback stemmer used when the porter stemmer is
110163 ** inappropriate.  The input word is copied into the output with
110164 ** US-ASCII case folding.  If the input word is too long (more
110165 ** than 20 bytes if it contains no digits or more than 6 bytes if
110166 ** it contains digits) then word is truncated to 20 or 6 bytes
110167 ** by taking 10 or 3 bytes from the beginning and end.
110168 */
110169 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
110170   int i, mx, j;
110171   int hasDigit = 0;
110172   for(i=0; i<nIn; i++){
110173     char c = zIn[i];
110174     if( c>='A' && c<='Z' ){
110175       zOut[i] = c - 'A' + 'a';
110176     }else{
110177       if( c>='0' && c<='9' ) hasDigit = 1;
110178       zOut[i] = c;
110179     }
110180   }
110181   mx = hasDigit ? 3 : 10;
110182   if( nIn>mx*2 ){
110183     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
110184       zOut[j] = zOut[i];
110185     }
110186     i = j;
110187   }
110188   zOut[i] = 0;
110189   *pnOut = i;
110190 }
110191
110192
110193 /*
110194 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
110195 ** zOut is at least big enough to hold nIn bytes.  Write the actual
110196 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
110197 **
110198 ** Any upper-case characters in the US-ASCII character set ([A-Z])
110199 ** are converted to lower case.  Upper-case UTF characters are
110200 ** unchanged.
110201 **
110202 ** Words that are longer than about 20 bytes are stemmed by retaining
110203 ** a few bytes from the beginning and the end of the word.  If the
110204 ** word contains digits, 3 bytes are taken from the beginning and
110205 ** 3 bytes from the end.  For long words without digits, 10 bytes
110206 ** are taken from each end.  US-ASCII case folding still applies.
110207 ** 
110208 ** If the input word contains not digits but does characters not 
110209 ** in [a-zA-Z] then no stemming is attempted and this routine just 
110210 ** copies the input into the input into the output with US-ASCII
110211 ** case folding.
110212 **
110213 ** Stemming never increases the length of the word.  So there is
110214 ** no chance of overflowing the zOut buffer.
110215 */
110216 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
110217   int i, j;
110218   char zReverse[28];
110219   char *z, *z2;
110220   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
110221     /* The word is too big or too small for the porter stemmer.
110222     ** Fallback to the copy stemmer */
110223     copy_stemmer(zIn, nIn, zOut, pnOut);
110224     return;
110225   }
110226   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
110227     char c = zIn[i];
110228     if( c>='A' && c<='Z' ){
110229       zReverse[j] = c + 'a' - 'A';
110230     }else if( c>='a' && c<='z' ){
110231       zReverse[j] = c;
110232     }else{
110233       /* The use of a character not in [a-zA-Z] means that we fallback
110234       ** to the copy stemmer */
110235       copy_stemmer(zIn, nIn, zOut, pnOut);
110236       return;
110237     }
110238   }
110239   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
110240   z = &zReverse[j+1];
110241
110242
110243   /* Step 1a */
110244   if( z[0]=='s' ){
110245     if(
110246      !stem(&z, "sess", "ss", 0) &&
110247      !stem(&z, "sei", "i", 0)  &&
110248      !stem(&z, "ss", "ss", 0)
110249     ){
110250       z++;
110251     }
110252   }
110253
110254   /* Step 1b */  
110255   z2 = z;
110256   if( stem(&z, "dee", "ee", m_gt_0) ){
110257     /* Do nothing.  The work was all in the test */
110258   }else if( 
110259      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
110260       && z!=z2
110261   ){
110262      if( stem(&z, "ta", "ate", 0) ||
110263          stem(&z, "lb", "ble", 0) ||
110264          stem(&z, "zi", "ize", 0) ){
110265        /* Do nothing.  The work was all in the test */
110266      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
110267        z++;
110268      }else if( m_eq_1(z) && star_oh(z) ){
110269        *(--z) = 'e';
110270      }
110271   }
110272
110273   /* Step 1c */
110274   if( z[0]=='y' && hasVowel(z+1) ){
110275     z[0] = 'i';
110276   }
110277
110278   /* Step 2 */
110279   switch( z[1] ){
110280    case 'a':
110281      stem(&z, "lanoita", "ate", m_gt_0) ||
110282      stem(&z, "lanoit", "tion", m_gt_0);
110283      break;
110284    case 'c':
110285      stem(&z, "icne", "ence", m_gt_0) ||
110286      stem(&z, "icna", "ance", m_gt_0);
110287      break;
110288    case 'e':
110289      stem(&z, "rezi", "ize", m_gt_0);
110290      break;
110291    case 'g':
110292      stem(&z, "igol", "log", m_gt_0);
110293      break;
110294    case 'l':
110295      stem(&z, "ilb", "ble", m_gt_0) ||
110296      stem(&z, "illa", "al", m_gt_0) ||
110297      stem(&z, "iltne", "ent", m_gt_0) ||
110298      stem(&z, "ile", "e", m_gt_0) ||
110299      stem(&z, "ilsuo", "ous", m_gt_0);
110300      break;
110301    case 'o':
110302      stem(&z, "noitazi", "ize", m_gt_0) ||
110303      stem(&z, "noita", "ate", m_gt_0) ||
110304      stem(&z, "rota", "ate", m_gt_0);
110305      break;
110306    case 's':
110307      stem(&z, "msila", "al", m_gt_0) ||
110308      stem(&z, "ssenevi", "ive", m_gt_0) ||
110309      stem(&z, "ssenluf", "ful", m_gt_0) ||
110310      stem(&z, "ssensuo", "ous", m_gt_0);
110311      break;
110312    case 't':
110313      stem(&z, "itila", "al", m_gt_0) ||
110314      stem(&z, "itivi", "ive", m_gt_0) ||
110315      stem(&z, "itilib", "ble", m_gt_0);
110316      break;
110317   }
110318
110319   /* Step 3 */
110320   switch( z[0] ){
110321    case 'e':
110322      stem(&z, "etaci", "ic", m_gt_0) ||
110323      stem(&z, "evita", "", m_gt_0)   ||
110324      stem(&z, "ezila", "al", m_gt_0);
110325      break;
110326    case 'i':
110327      stem(&z, "itici", "ic", m_gt_0);
110328      break;
110329    case 'l':
110330      stem(&z, "laci", "ic", m_gt_0) ||
110331      stem(&z, "luf", "", m_gt_0);
110332      break;
110333    case 's':
110334      stem(&z, "ssen", "", m_gt_0);
110335      break;
110336   }
110337
110338   /* Step 4 */
110339   switch( z[1] ){
110340    case 'a':
110341      if( z[0]=='l' && m_gt_1(z+2) ){
110342        z += 2;
110343      }
110344      break;
110345    case 'c':
110346      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
110347        z += 4;
110348      }
110349      break;
110350    case 'e':
110351      if( z[0]=='r' && m_gt_1(z+2) ){
110352        z += 2;
110353      }
110354      break;
110355    case 'i':
110356      if( z[0]=='c' && m_gt_1(z+2) ){
110357        z += 2;
110358      }
110359      break;
110360    case 'l':
110361      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
110362        z += 4;
110363      }
110364      break;
110365    case 'n':
110366      if( z[0]=='t' ){
110367        if( z[2]=='a' ){
110368          if( m_gt_1(z+3) ){
110369            z += 3;
110370          }
110371        }else if( z[2]=='e' ){
110372          stem(&z, "tneme", "", m_gt_1) ||
110373          stem(&z, "tnem", "", m_gt_1) ||
110374          stem(&z, "tne", "", m_gt_1);
110375        }
110376      }
110377      break;
110378    case 'o':
110379      if( z[0]=='u' ){
110380        if( m_gt_1(z+2) ){
110381          z += 2;
110382        }
110383      }else if( z[3]=='s' || z[3]=='t' ){
110384        stem(&z, "noi", "", m_gt_1);
110385      }
110386      break;
110387    case 's':
110388      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
110389        z += 3;
110390      }
110391      break;
110392    case 't':
110393      stem(&z, "eta", "", m_gt_1) ||
110394      stem(&z, "iti", "", m_gt_1);
110395      break;
110396    case 'u':
110397      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
110398        z += 3;
110399      }
110400      break;
110401    case 'v':
110402    case 'z':
110403      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
110404        z += 3;
110405      }
110406      break;
110407   }
110408
110409   /* Step 5a */
110410   if( z[0]=='e' ){
110411     if( m_gt_1(z+1) ){
110412       z++;
110413     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
110414       z++;
110415     }
110416   }
110417
110418   /* Step 5b */
110419   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
110420     z++;
110421   }
110422
110423   /* z[] is now the stemmed word in reverse order.  Flip it back
110424   ** around into forward order and return.
110425   */
110426   *pnOut = i = (int)strlen(z);
110427   zOut[i] = 0;
110428   while( *z ){
110429     zOut[--i] = *(z++);
110430   }
110431 }
110432
110433 /*
110434 ** Characters that can be part of a token.  We assume any character
110435 ** whose value is greater than 0x80 (any UTF character) can be
110436 ** part of a token.  In other words, delimiters all must have
110437 ** values of 0x7f or lower.
110438 */
110439 static const char porterIdChar[] = {
110440 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
110441     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110442     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110443     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110444     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110445     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110446 };
110447 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
110448
110449 /*
110450 ** Extract the next token from a tokenization cursor.  The cursor must
110451 ** have been opened by a prior call to porterOpen().
110452 */
110453 static int porterNext(
110454   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
110455   const char **pzToken,               /* OUT: *pzToken is the token text */
110456   int *pnBytes,                       /* OUT: Number of bytes in token */
110457   int *piStartOffset,                 /* OUT: Starting offset of token */
110458   int *piEndOffset,                   /* OUT: Ending offset of token */
110459   int *piPosition                     /* OUT: Position integer of token */
110460 ){
110461   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
110462   const char *z = c->zInput;
110463
110464   while( c->iOffset<c->nInput ){
110465     int iStartOffset, ch;
110466
110467     /* Scan past delimiter characters */
110468     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
110469       c->iOffset++;
110470     }
110471
110472     /* Count non-delimiter characters. */
110473     iStartOffset = c->iOffset;
110474     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
110475       c->iOffset++;
110476     }
110477
110478     if( c->iOffset>iStartOffset ){
110479       int n = c->iOffset-iStartOffset;
110480       if( n>c->nAllocated ){
110481         char *pNew;
110482         c->nAllocated = n+20;
110483         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
110484         if( !pNew ) return SQLITE_NOMEM;
110485         c->zToken = pNew;
110486       }
110487       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
110488       *pzToken = c->zToken;
110489       *piStartOffset = iStartOffset;
110490       *piEndOffset = c->iOffset;
110491       *piPosition = c->iToken++;
110492       return SQLITE_OK;
110493     }
110494   }
110495   return SQLITE_DONE;
110496 }
110497
110498 /*
110499 ** The set of routines that implement the porter-stemmer tokenizer
110500 */
110501 static const sqlite3_tokenizer_module porterTokenizerModule = {
110502   0,
110503   porterCreate,
110504   porterDestroy,
110505   porterOpen,
110506   porterClose,
110507   porterNext,
110508 };
110509
110510 /*
110511 ** Allocate a new porter tokenizer.  Return a pointer to the new
110512 ** tokenizer in *ppModule
110513 */
110514 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
110515   sqlite3_tokenizer_module const**ppModule
110516 ){
110517   *ppModule = &porterTokenizerModule;
110518 }
110519
110520 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110521
110522 /************** End of fts3_porter.c *****************************************/
110523 /************** Begin file fts3_tokenizer.c **********************************/
110524 /*
110525 ** 2007 June 22
110526 **
110527 ** The author disclaims copyright to this source code.  In place of
110528 ** a legal notice, here is a blessing:
110529 **
110530 **    May you do good and not evil.
110531 **    May you find forgiveness for yourself and forgive others.
110532 **    May you share freely, never taking more than you give.
110533 **
110534 ******************************************************************************
110535 **
110536 ** This is part of an SQLite module implementing full-text search.
110537 ** This particular file implements the generic tokenizer interface.
110538 */
110539
110540 /*
110541 ** The code in this file is only compiled if:
110542 **
110543 **     * The FTS3 module is being built as an extension
110544 **       (in which case SQLITE_CORE is not defined), or
110545 **
110546 **     * The FTS3 module is being built into the core of
110547 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110548 */
110549 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110550
110551 #ifndef SQLITE_CORE
110552   SQLITE_EXTENSION_INIT1
110553 #endif
110554
110555
110556 /*
110557 ** Implementation of the SQL scalar function for accessing the underlying 
110558 ** hash table. This function may be called as follows:
110559 **
110560 **   SELECT <function-name>(<key-name>);
110561 **   SELECT <function-name>(<key-name>, <pointer>);
110562 **
110563 ** where <function-name> is the name passed as the second argument
110564 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
110565 **
110566 ** If the <pointer> argument is specified, it must be a blob value
110567 ** containing a pointer to be stored as the hash data corresponding
110568 ** to the string <key-name>. If <pointer> is not specified, then
110569 ** the string <key-name> must already exist in the has table. Otherwise,
110570 ** an error is returned.
110571 **
110572 ** Whether or not the <pointer> argument is specified, the value returned
110573 ** is a blob containing the pointer stored as the hash data corresponding
110574 ** to string <key-name> (after the hash-table is updated, if applicable).
110575 */
110576 static void scalarFunc(
110577   sqlite3_context *context,
110578   int argc,
110579   sqlite3_value **argv
110580 ){
110581   Fts3Hash *pHash;
110582   void *pPtr = 0;
110583   const unsigned char *zName;
110584   int nName;
110585
110586   assert( argc==1 || argc==2 );
110587
110588   pHash = (Fts3Hash *)sqlite3_user_data(context);
110589
110590   zName = sqlite3_value_text(argv[0]);
110591   nName = sqlite3_value_bytes(argv[0])+1;
110592
110593   if( argc==2 ){
110594     void *pOld;
110595     int n = sqlite3_value_bytes(argv[1]);
110596     if( n!=sizeof(pPtr) ){
110597       sqlite3_result_error(context, "argument type mismatch", -1);
110598       return;
110599     }
110600     pPtr = *(void **)sqlite3_value_blob(argv[1]);
110601     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
110602     if( pOld==pPtr ){
110603       sqlite3_result_error(context, "out of memory", -1);
110604       return;
110605     }
110606   }else{
110607     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
110608     if( !pPtr ){
110609       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110610       sqlite3_result_error(context, zErr, -1);
110611       sqlite3_free(zErr);
110612       return;
110613     }
110614   }
110615
110616   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
110617 }
110618
110619 static int fts3IsIdChar(char c){
110620   static const char isFtsIdChar[] = {
110621       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
110622       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
110623       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
110624       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110625       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110626       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110627       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110628       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110629   };
110630   return (c&0x80 || isFtsIdChar[(int)(c)]);
110631 }
110632
110633 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
110634   const char *z1;
110635   const char *z2 = 0;
110636
110637   /* Find the start of the next token. */
110638   z1 = zStr;
110639   while( z2==0 ){
110640     char c = *z1;
110641     switch( c ){
110642       case '\0': return 0;        /* No more tokens here */
110643       case '\'':
110644       case '"':
110645       case '`': {
110646         z2 = z1;
110647         while( *++z2 && (*z2!=c || *++z2==c) );
110648         break;
110649       }
110650       case '[':
110651         z2 = &z1[1];
110652         while( *z2 && z2[0]!=']' ) z2++;
110653         if( *z2 ) z2++;
110654         break;
110655
110656       default:
110657         if( fts3IsIdChar(*z1) ){
110658           z2 = &z1[1];
110659           while( fts3IsIdChar(*z2) ) z2++;
110660         }else{
110661           z1++;
110662         }
110663     }
110664   }
110665
110666   *pn = (int)(z2-z1);
110667   return z1;
110668 }
110669
110670 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
110671   Fts3Hash *pHash,                /* Tokenizer hash table */
110672   const char *zArg,               /* Possible tokenizer specification */
110673   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
110674   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
110675   char **pzErr                    /* OUT: Set to malloced error message */
110676 ){
110677   int rc;
110678   char *z = (char *)zArg;
110679   int n;
110680   char *zCopy;
110681   char *zEnd;                     /* Pointer to nul-term of zCopy */
110682   sqlite3_tokenizer_module *m;
110683
110684   if( !z ){
110685     zCopy = sqlite3_mprintf("simple");
110686   }else{
110687     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
110688       return SQLITE_OK;
110689     }
110690     zCopy = sqlite3_mprintf("%s", &z[8]);
110691     *pzTokenizer = zArg;
110692   }
110693   if( !zCopy ){
110694     return SQLITE_NOMEM;
110695   }
110696
110697   zEnd = &zCopy[strlen(zCopy)];
110698
110699   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
110700   z[n] = '\0';
110701   sqlite3Fts3Dequote(z);
110702
110703   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
110704   if( !m ){
110705     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
110706     rc = SQLITE_ERROR;
110707   }else{
110708     char const **aArg = 0;
110709     int iArg = 0;
110710     z = &z[n+1];
110711     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
110712       int nNew = sizeof(char *)*(iArg+1);
110713       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
110714       if( !aNew ){
110715         sqlite3_free(zCopy);
110716         sqlite3_free((void *)aArg);
110717         return SQLITE_NOMEM;
110718       }
110719       aArg = aNew;
110720       aArg[iArg++] = z;
110721       z[n] = '\0';
110722       sqlite3Fts3Dequote(z);
110723       z = &z[n+1];
110724     }
110725     rc = m->xCreate(iArg, aArg, ppTok);
110726     assert( rc!=SQLITE_OK || *ppTok );
110727     if( rc!=SQLITE_OK ){
110728       *pzErr = sqlite3_mprintf("unknown tokenizer");
110729     }else{
110730       (*ppTok)->pModule = m; 
110731     }
110732     sqlite3_free((void *)aArg);
110733   }
110734
110735   sqlite3_free(zCopy);
110736   return rc;
110737 }
110738
110739
110740 #ifdef SQLITE_TEST
110741
110742
110743 /*
110744 ** Implementation of a special SQL scalar function for testing tokenizers 
110745 ** designed to be used in concert with the Tcl testing framework. This
110746 ** function must be called with two arguments:
110747 **
110748 **   SELECT <function-name>(<key-name>, <input-string>);
110749 **   SELECT <function-name>(<key-name>, <pointer>);
110750 **
110751 ** where <function-name> is the name passed as the second argument
110752 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
110753 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
110754 **
110755 ** The return value is a string that may be interpreted as a Tcl
110756 ** list. For each token in the <input-string>, three elements are
110757 ** added to the returned list. The first is the token position, the 
110758 ** second is the token text (folded, stemmed, etc.) and the third is the
110759 ** substring of <input-string> associated with the token. For example, 
110760 ** using the built-in "simple" tokenizer:
110761 **
110762 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
110763 **
110764 ** will return the string:
110765 **
110766 **   "{0 i I 1 dont don't 2 see see 3 how how}"
110767 **   
110768 */
110769 static void testFunc(
110770   sqlite3_context *context,
110771   int argc,
110772   sqlite3_value **argv
110773 ){
110774   Fts3Hash *pHash;
110775   sqlite3_tokenizer_module *p;
110776   sqlite3_tokenizer *pTokenizer = 0;
110777   sqlite3_tokenizer_cursor *pCsr = 0;
110778
110779   const char *zErr = 0;
110780
110781   const char *zName;
110782   int nName;
110783   const char *zInput;
110784   int nInput;
110785
110786   const char *zArg = 0;
110787
110788   const char *zToken;
110789   int nToken;
110790   int iStart;
110791   int iEnd;
110792   int iPos;
110793
110794   Tcl_Obj *pRet;
110795
110796   assert( argc==2 || argc==3 );
110797
110798   nName = sqlite3_value_bytes(argv[0]);
110799   zName = (const char *)sqlite3_value_text(argv[0]);
110800   nInput = sqlite3_value_bytes(argv[argc-1]);
110801   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
110802
110803   if( argc==3 ){
110804     zArg = (const char *)sqlite3_value_text(argv[1]);
110805   }
110806
110807   pHash = (Fts3Hash *)sqlite3_user_data(context);
110808   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
110809
110810   if( !p ){
110811     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110812     sqlite3_result_error(context, zErr, -1);
110813     sqlite3_free(zErr);
110814     return;
110815   }
110816
110817   pRet = Tcl_NewObj();
110818   Tcl_IncrRefCount(pRet);
110819
110820   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
110821     zErr = "error in xCreate()";
110822     goto finish;
110823   }
110824   pTokenizer->pModule = p;
110825   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
110826     zErr = "error in xOpen()";
110827     goto finish;
110828   }
110829   pCsr->pTokenizer = pTokenizer;
110830
110831   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
110832     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
110833     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110834     zToken = &zInput[iStart];
110835     nToken = iEnd-iStart;
110836     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110837   }
110838
110839   if( SQLITE_OK!=p->xClose(pCsr) ){
110840     zErr = "error in xClose()";
110841     goto finish;
110842   }
110843   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
110844     zErr = "error in xDestroy()";
110845     goto finish;
110846   }
110847
110848 finish:
110849   if( zErr ){
110850     sqlite3_result_error(context, zErr, -1);
110851   }else{
110852     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
110853   }
110854   Tcl_DecrRefCount(pRet);
110855 }
110856
110857 static
110858 int registerTokenizer(
110859   sqlite3 *db, 
110860   char *zName, 
110861   const sqlite3_tokenizer_module *p
110862 ){
110863   int rc;
110864   sqlite3_stmt *pStmt;
110865   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
110866
110867   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110868   if( rc!=SQLITE_OK ){
110869     return rc;
110870   }
110871
110872   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110873   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
110874   sqlite3_step(pStmt);
110875
110876   return sqlite3_finalize(pStmt);
110877 }
110878
110879 static
110880 int queryTokenizer(
110881   sqlite3 *db, 
110882   char *zName,  
110883   const sqlite3_tokenizer_module **pp
110884 ){
110885   int rc;
110886   sqlite3_stmt *pStmt;
110887   const char zSql[] = "SELECT fts3_tokenizer(?)";
110888
110889   *pp = 0;
110890   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110891   if( rc!=SQLITE_OK ){
110892     return rc;
110893   }
110894
110895   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110896   if( SQLITE_ROW==sqlite3_step(pStmt) ){
110897     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
110898       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
110899     }
110900   }
110901
110902   return sqlite3_finalize(pStmt);
110903 }
110904
110905 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110906
110907 /*
110908 ** Implementation of the scalar function fts3_tokenizer_internal_test().
110909 ** This function is used for testing only, it is not included in the
110910 ** build unless SQLITE_TEST is defined.
110911 **
110912 ** The purpose of this is to test that the fts3_tokenizer() function
110913 ** can be used as designed by the C-code in the queryTokenizer and
110914 ** registerTokenizer() functions above. These two functions are repeated
110915 ** in the README.tokenizer file as an example, so it is important to
110916 ** test them.
110917 **
110918 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
110919 ** function with no arguments. An assert() will fail if a problem is
110920 ** detected. i.e.:
110921 **
110922 **     SELECT fts3_tokenizer_internal_test();
110923 **
110924 */
110925 static void intTestFunc(
110926   sqlite3_context *context,
110927   int argc,
110928   sqlite3_value **argv
110929 ){
110930   int rc;
110931   const sqlite3_tokenizer_module *p1;
110932   const sqlite3_tokenizer_module *p2;
110933   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
110934
110935   UNUSED_PARAMETER(argc);
110936   UNUSED_PARAMETER(argv);
110937
110938   /* Test the query function */
110939   sqlite3Fts3SimpleTokenizerModule(&p1);
110940   rc = queryTokenizer(db, "simple", &p2);
110941   assert( rc==SQLITE_OK );
110942   assert( p1==p2 );
110943   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110944   assert( rc==SQLITE_ERROR );
110945   assert( p2==0 );
110946   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
110947
110948   /* Test the storage function */
110949   rc = registerTokenizer(db, "nosuchtokenizer", p1);
110950   assert( rc==SQLITE_OK );
110951   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110952   assert( rc==SQLITE_OK );
110953   assert( p2==p1 );
110954
110955   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
110956 }
110957
110958 #endif
110959
110960 /*
110961 ** Set up SQL objects in database db used to access the contents of
110962 ** the hash table pointed to by argument pHash. The hash table must
110963 ** been initialised to use string keys, and to take a private copy 
110964 ** of the key when a value is inserted. i.e. by a call similar to:
110965 **
110966 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
110967 **
110968 ** This function adds a scalar function (see header comment above
110969 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
110970 ** defined at compilation time, a temporary virtual table (see header 
110971 ** comment above struct HashTableVtab) to the database schema. Both 
110972 ** provide read/write access to the contents of *pHash.
110973 **
110974 ** The third argument to this function, zName, is used as the name
110975 ** of both the scalar and, if created, the virtual table.
110976 */
110977 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
110978   sqlite3 *db, 
110979   Fts3Hash *pHash, 
110980   const char *zName
110981 ){
110982   int rc = SQLITE_OK;
110983   void *p = (void *)pHash;
110984   const int any = SQLITE_ANY;
110985
110986 #ifdef SQLITE_TEST
110987   char *zTest = 0;
110988   char *zTest2 = 0;
110989   void *pdb = (void *)db;
110990   zTest = sqlite3_mprintf("%s_test", zName);
110991   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
110992   if( !zTest || !zTest2 ){
110993     rc = SQLITE_NOMEM;
110994   }
110995 #endif
110996
110997   if( SQLITE_OK!=rc
110998    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
110999    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
111000 #ifdef SQLITE_TEST
111001    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
111002    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
111003    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
111004 #endif
111005    );
111006
111007 #ifdef SQLITE_TEST
111008   sqlite3_free(zTest);
111009   sqlite3_free(zTest2);
111010 #endif
111011
111012   return rc;
111013 }
111014
111015 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111016
111017 /************** End of fts3_tokenizer.c **************************************/
111018 /************** Begin file fts3_tokenizer1.c *********************************/
111019 /*
111020 ** 2006 Oct 10
111021 **
111022 ** The author disclaims copyright to this source code.  In place of
111023 ** a legal notice, here is a blessing:
111024 **
111025 **    May you do good and not evil.
111026 **    May you find forgiveness for yourself and forgive others.
111027 **    May you share freely, never taking more than you give.
111028 **
111029 ******************************************************************************
111030 **
111031 ** Implementation of the "simple" full-text-search tokenizer.
111032 */
111033
111034 /*
111035 ** The code in this file is only compiled if:
111036 **
111037 **     * The FTS3 module is being built as an extension
111038 **       (in which case SQLITE_CORE is not defined), or
111039 **
111040 **     * The FTS3 module is being built into the core of
111041 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111042 */
111043 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111044
111045
111046
111047
111048 typedef struct simple_tokenizer {
111049   sqlite3_tokenizer base;
111050   char delim[128];             /* flag ASCII delimiters */
111051 } simple_tokenizer;
111052
111053 typedef struct simple_tokenizer_cursor {
111054   sqlite3_tokenizer_cursor base;
111055   const char *pInput;          /* input we are tokenizing */
111056   int nBytes;                  /* size of the input */
111057   int iOffset;                 /* current position in pInput */
111058   int iToken;                  /* index of next token to be returned */
111059   char *pToken;                /* storage for current token */
111060   int nTokenAllocated;         /* space allocated to zToken buffer */
111061 } simple_tokenizer_cursor;
111062
111063
111064 static int simpleDelim(simple_tokenizer *t, unsigned char c){
111065   return c<0x80 && t->delim[c];
111066 }
111067
111068 /*
111069 ** Create a new tokenizer instance.
111070 */
111071 static int simpleCreate(
111072   int argc, const char * const *argv,
111073   sqlite3_tokenizer **ppTokenizer
111074 ){
111075   simple_tokenizer *t;
111076
111077   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
111078   if( t==NULL ) return SQLITE_NOMEM;
111079   memset(t, 0, sizeof(*t));
111080
111081   /* TODO(shess) Delimiters need to remain the same from run to run,
111082   ** else we need to reindex.  One solution would be a meta-table to
111083   ** track such information in the database, then we'd only want this
111084   ** information on the initial create.
111085   */
111086   if( argc>1 ){
111087     int i, n = (int)strlen(argv[1]);
111088     for(i=0; i<n; i++){
111089       unsigned char ch = argv[1][i];
111090       /* We explicitly don't support UTF-8 delimiters for now. */
111091       if( ch>=0x80 ){
111092         sqlite3_free(t);
111093         return SQLITE_ERROR;
111094       }
111095       t->delim[ch] = 1;
111096     }
111097   } else {
111098     /* Mark non-alphanumeric ASCII characters as delimiters */
111099     int i;
111100     for(i=1; i<0x80; i++){
111101       t->delim[i] = !isalnum(i) ? -1 : 0;
111102     }
111103   }
111104
111105   *ppTokenizer = &t->base;
111106   return SQLITE_OK;
111107 }
111108
111109 /*
111110 ** Destroy a tokenizer
111111 */
111112 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
111113   sqlite3_free(pTokenizer);
111114   return SQLITE_OK;
111115 }
111116
111117 /*
111118 ** Prepare to begin tokenizing a particular string.  The input
111119 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
111120 ** used to incrementally tokenize this string is returned in 
111121 ** *ppCursor.
111122 */
111123 static int simpleOpen(
111124   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
111125   const char *pInput, int nBytes,        /* String to be tokenized */
111126   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
111127 ){
111128   simple_tokenizer_cursor *c;
111129
111130   UNUSED_PARAMETER(pTokenizer);
111131
111132   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
111133   if( c==NULL ) return SQLITE_NOMEM;
111134
111135   c->pInput = pInput;
111136   if( pInput==0 ){
111137     c->nBytes = 0;
111138   }else if( nBytes<0 ){
111139     c->nBytes = (int)strlen(pInput);
111140   }else{
111141     c->nBytes = nBytes;
111142   }
111143   c->iOffset = 0;                 /* start tokenizing at the beginning */
111144   c->iToken = 0;
111145   c->pToken = NULL;               /* no space allocated, yet. */
111146   c->nTokenAllocated = 0;
111147
111148   *ppCursor = &c->base;
111149   return SQLITE_OK;
111150 }
111151
111152 /*
111153 ** Close a tokenization cursor previously opened by a call to
111154 ** simpleOpen() above.
111155 */
111156 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
111157   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
111158   sqlite3_free(c->pToken);
111159   sqlite3_free(c);
111160   return SQLITE_OK;
111161 }
111162
111163 /*
111164 ** Extract the next token from a tokenization cursor.  The cursor must
111165 ** have been opened by a prior call to simpleOpen().
111166 */
111167 static int simpleNext(
111168   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
111169   const char **ppToken,               /* OUT: *ppToken is the token text */
111170   int *pnBytes,                       /* OUT: Number of bytes in token */
111171   int *piStartOffset,                 /* OUT: Starting offset of token */
111172   int *piEndOffset,                   /* OUT: Ending offset of token */
111173   int *piPosition                     /* OUT: Position integer of token */
111174 ){
111175   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
111176   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
111177   unsigned char *p = (unsigned char *)c->pInput;
111178
111179   while( c->iOffset<c->nBytes ){
111180     int iStartOffset;
111181
111182     /* Scan past delimiter characters */
111183     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
111184       c->iOffset++;
111185     }
111186
111187     /* Count non-delimiter characters. */
111188     iStartOffset = c->iOffset;
111189     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
111190       c->iOffset++;
111191     }
111192
111193     if( c->iOffset>iStartOffset ){
111194       int i, n = c->iOffset-iStartOffset;
111195       if( n>c->nTokenAllocated ){
111196         char *pNew;
111197         c->nTokenAllocated = n+20;
111198         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
111199         if( !pNew ) return SQLITE_NOMEM;
111200         c->pToken = pNew;
111201       }
111202       for(i=0; i<n; i++){
111203         /* TODO(shess) This needs expansion to handle UTF-8
111204         ** case-insensitivity.
111205         */
111206         unsigned char ch = p[iStartOffset+i];
111207         c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
111208       }
111209       *ppToken = c->pToken;
111210       *pnBytes = n;
111211       *piStartOffset = iStartOffset;
111212       *piEndOffset = c->iOffset;
111213       *piPosition = c->iToken++;
111214
111215       return SQLITE_OK;
111216     }
111217   }
111218   return SQLITE_DONE;
111219 }
111220
111221 /*
111222 ** The set of routines that implement the simple tokenizer
111223 */
111224 static const sqlite3_tokenizer_module simpleTokenizerModule = {
111225   0,
111226   simpleCreate,
111227   simpleDestroy,
111228   simpleOpen,
111229   simpleClose,
111230   simpleNext,
111231 };
111232
111233 /*
111234 ** Allocate a new simple tokenizer.  Return a pointer to the new
111235 ** tokenizer in *ppModule
111236 */
111237 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
111238   sqlite3_tokenizer_module const**ppModule
111239 ){
111240   *ppModule = &simpleTokenizerModule;
111241 }
111242
111243 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111244
111245 /************** End of fts3_tokenizer1.c *************************************/
111246 /************** Begin file fts3_write.c **************************************/
111247 /*
111248 ** 2009 Oct 23
111249 **
111250 ** The author disclaims copyright to this source code.  In place of
111251 ** a legal notice, here is a blessing:
111252 **
111253 **    May you do good and not evil.
111254 **    May you find forgiveness for yourself and forgive others.
111255 **    May you share freely, never taking more than you give.
111256 **
111257 ******************************************************************************
111258 **
111259 ** This file is part of the SQLite FTS3 extension module. Specifically,
111260 ** this file contains code to insert, update and delete rows from FTS3
111261 ** tables. It also contains code to merge FTS3 b-tree segments. Some
111262 ** of the sub-routines used to merge segments are also used by the query 
111263 ** code in fts3.c.
111264 */
111265
111266 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111267
111268
111269 typedef struct PendingList PendingList;
111270 typedef struct SegmentNode SegmentNode;
111271 typedef struct SegmentWriter SegmentWriter;
111272
111273 /*
111274 ** Data structure used while accumulating terms in the pending-terms hash
111275 ** table. The hash table entry maps from term (a string) to a malloc'd
111276 ** instance of this structure.
111277 */
111278 struct PendingList {
111279   int nData;
111280   char *aData;
111281   int nSpace;
111282   sqlite3_int64 iLastDocid;
111283   sqlite3_int64 iLastCol;
111284   sqlite3_int64 iLastPos;
111285 };
111286
111287 /*
111288 ** An instance of this structure is used to iterate through the terms on
111289 ** a contiguous set of segment b-tree leaf nodes. Although the details of
111290 ** this structure are only manipulated by code in this file, opaque handles
111291 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
111292 ** terms when querying the full-text index. See functions:
111293 **
111294 **   sqlite3Fts3SegReaderNew()
111295 **   sqlite3Fts3SegReaderFree()
111296 **   sqlite3Fts3SegReaderIterate()
111297 **
111298 ** Methods used to manipulate Fts3SegReader structures:
111299 **
111300 **   fts3SegReaderNext()
111301 **   fts3SegReaderFirstDocid()
111302 **   fts3SegReaderNextDocid()
111303 */
111304 struct Fts3SegReader {
111305   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
111306   sqlite3_int64 iStartBlock;
111307   sqlite3_int64 iEndBlock;
111308   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
111309   char *aNode;                    /* Pointer to node data (or NULL) */
111310   int nNode;                      /* Size of buffer at aNode (or 0) */
111311   int nTermAlloc;                 /* Allocated size of zTerm buffer */
111312   Fts3HashElem **ppNextElem;
111313
111314   /* Variables set by fts3SegReaderNext(). These may be read directly
111315   ** by the caller. They are valid from the time SegmentReaderNew() returns
111316   ** until SegmentReaderNext() returns something other than SQLITE_OK
111317   ** (i.e. SQLITE_DONE).
111318   */
111319   int nTerm;                      /* Number of bytes in current term */
111320   char *zTerm;                    /* Pointer to current term */
111321   char *aDoclist;                 /* Pointer to doclist of current entry */
111322   int nDoclist;                   /* Size of doclist in current entry */
111323
111324   /* The following variables are used to iterate through the current doclist */
111325   char *pOffsetList;
111326   sqlite3_int64 iDocid;
111327 };
111328
111329 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
111330
111331 /*
111332 ** An instance of this structure is used to create a segment b-tree in the
111333 ** database. The internal details of this type are only accessed by the
111334 ** following functions:
111335 **
111336 **   fts3SegWriterAdd()
111337 **   fts3SegWriterFlush()
111338 **   fts3SegWriterFree()
111339 */
111340 struct SegmentWriter {
111341   SegmentNode *pTree;             /* Pointer to interior tree structure */
111342   sqlite3_int64 iFirst;           /* First slot in %_segments written */
111343   sqlite3_int64 iFree;            /* Next free slot in %_segments */
111344   char *zTerm;                    /* Pointer to previous term buffer */
111345   int nTerm;                      /* Number of bytes in zTerm */
111346   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
111347   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
111348   int nSize;                      /* Size of allocation at aData */
111349   int nData;                      /* Bytes of data in aData */
111350   char *aData;                    /* Pointer to block from malloc() */
111351 };
111352
111353 /*
111354 ** Type SegmentNode is used by the following three functions to create
111355 ** the interior part of the segment b+-tree structures (everything except
111356 ** the leaf nodes). These functions and type are only ever used by code
111357 ** within the fts3SegWriterXXX() family of functions described above.
111358 **
111359 **   fts3NodeAddTerm()
111360 **   fts3NodeWrite()
111361 **   fts3NodeFree()
111362 */
111363 struct SegmentNode {
111364   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
111365   SegmentNode *pRight;            /* Pointer to right-sibling */
111366   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
111367   int nEntry;                     /* Number of terms written to node so far */
111368   char *zTerm;                    /* Pointer to previous term buffer */
111369   int nTerm;                      /* Number of bytes in zTerm */
111370   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
111371   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
111372   int nData;                      /* Bytes of valid data so far */
111373   char *aData;                    /* Node data */
111374 };
111375
111376 /*
111377 ** Valid values for the second argument to fts3SqlStmt().
111378 */
111379 #define SQL_DELETE_CONTENT             0
111380 #define SQL_IS_EMPTY                   1
111381 #define SQL_DELETE_ALL_CONTENT         2 
111382 #define SQL_DELETE_ALL_SEGMENTS        3
111383 #define SQL_DELETE_ALL_SEGDIR          4
111384 #define SQL_DELETE_ALL_DOCSIZE         5
111385 #define SQL_DELETE_ALL_STAT            6
111386 #define SQL_SELECT_CONTENT_BY_ROWID    7
111387 #define SQL_NEXT_SEGMENT_INDEX         8
111388 #define SQL_INSERT_SEGMENTS            9
111389 #define SQL_NEXT_SEGMENTS_ID          10
111390 #define SQL_INSERT_SEGDIR             11
111391 #define SQL_SELECT_LEVEL              12
111392 #define SQL_SELECT_ALL_LEVEL          13
111393 #define SQL_SELECT_LEVEL_COUNT        14
111394 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
111395 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
111396 #define SQL_DELETE_SEGMENTS_RANGE     17
111397 #define SQL_CONTENT_INSERT            18
111398 #define SQL_GET_BLOCK                 19
111399 #define SQL_DELETE_DOCSIZE            20
111400 #define SQL_REPLACE_DOCSIZE           21
111401 #define SQL_SELECT_DOCSIZE            22
111402 #define SQL_SELECT_DOCTOTAL           23
111403 #define SQL_REPLACE_DOCTOTAL          24
111404
111405 /*
111406 ** This function is used to obtain an SQLite prepared statement handle
111407 ** for the statement identified by the second argument. If successful,
111408 ** *pp is set to the requested statement handle and SQLITE_OK returned.
111409 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
111410 **
111411 ** If argument apVal is not NULL, then it must point to an array with
111412 ** at least as many entries as the requested statement has bound 
111413 ** parameters. The values are bound to the statements parameters before
111414 ** returning.
111415 */
111416 static int fts3SqlStmt(
111417   Fts3Table *p,                   /* Virtual table handle */
111418   int eStmt,                      /* One of the SQL_XXX constants above */
111419   sqlite3_stmt **pp,              /* OUT: Statement handle */
111420   sqlite3_value **apVal           /* Values to bind to statement */
111421 ){
111422   const char *azSql[] = {
111423 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
111424 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
111425 /* 2  */  "DELETE FROM %Q.'%q_content'",
111426 /* 3  */  "DELETE FROM %Q.'%q_segments'",
111427 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
111428 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
111429 /* 6  */  "DELETE FROM %Q.'%q_stat'",
111430 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
111431 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
111432 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
111433 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
111434 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
111435
111436           /* Return segments in order from oldest to newest.*/ 
111437 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111438             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
111439 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111440             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
111441
111442 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
111443 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
111444
111445 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
111446 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
111447 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
111448 /* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
111449 /* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
111450 /* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
111451 /* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
111452 /* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
111453 /* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
111454   };
111455   int rc = SQLITE_OK;
111456   sqlite3_stmt *pStmt;
111457
111458   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
111459   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
111460   
111461   pStmt = p->aStmt[eStmt];
111462   if( !pStmt ){
111463     char *zSql;
111464     if( eStmt==SQL_CONTENT_INSERT ){
111465       int i;                      /* Iterator variable */  
111466       char *zVarlist;             /* The "?, ?, ..." string */
111467       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
111468       if( !zVarlist ){
111469         *pp = 0;
111470         return SQLITE_NOMEM;
111471       }
111472       zVarlist[0] = '?';
111473       zVarlist[p->nColumn*2+1] = '\0';
111474       for(i=1; i<=p->nColumn; i++){
111475         zVarlist[i*2-1] = ',';
111476         zVarlist[i*2] = '?';
111477       }
111478       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
111479     }else{
111480       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
111481     }
111482     if( !zSql ){
111483       rc = SQLITE_NOMEM;
111484     }else{
111485       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
111486       sqlite3_free(zSql);
111487       assert( rc==SQLITE_OK || pStmt==0 );
111488       p->aStmt[eStmt] = pStmt;
111489     }
111490   }
111491   if( apVal ){
111492     int i;
111493     int nParam = sqlite3_bind_parameter_count(pStmt);
111494     for(i=0; rc==SQLITE_OK && i<nParam; i++){
111495       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
111496     }
111497   }
111498   *pp = pStmt;
111499   return rc;
111500 }
111501
111502 /*
111503 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
111504 ** array apVal[] to the SQL statement identified by eStmt, the statement
111505 ** is executed.
111506 **
111507 ** Returns SQLITE_OK if the statement is successfully executed, or an
111508 ** SQLite error code otherwise.
111509 */
111510 static void fts3SqlExec(
111511   int *pRC,                /* Result code */
111512   Fts3Table *p,            /* The FTS3 table */
111513   int eStmt,               /* Index of statement to evaluate */
111514   sqlite3_value **apVal    /* Parameters to bind */
111515 ){
111516   sqlite3_stmt *pStmt;
111517   int rc;
111518   if( *pRC ) return;
111519   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
111520   if( rc==SQLITE_OK ){
111521     sqlite3_step(pStmt);
111522     rc = sqlite3_reset(pStmt);
111523   }
111524   *pRC = rc;
111525 }
111526
111527
111528 /*
111529 ** Read a single block from the %_segments table. If the specified block
111530 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO 
111531 ** etc.) occurs, return the appropriate SQLite error code.
111532 **
111533 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
111534 ** the block read from the database, and *pnBlock to the size of the read
111535 ** block in bytes.
111536 **
111537 ** WARNING: The returned buffer is only valid until the next call to 
111538 ** sqlite3Fts3ReadBlock().
111539 */
111540 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
111541   Fts3Table *p,
111542   sqlite3_int64 iBlock,
111543   char const **pzBlock,
111544   int *pnBlock
111545 ){
111546   sqlite3_stmt *pStmt;
111547   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
111548   if( rc!=SQLITE_OK ) return rc;
111549   sqlite3_reset(pStmt);
111550
111551   if( pzBlock ){
111552     sqlite3_bind_int64(pStmt, 1, iBlock);
111553     rc = sqlite3_step(pStmt); 
111554     if( rc!=SQLITE_ROW ){
111555       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
111556     }
111557   
111558     *pnBlock = sqlite3_column_bytes(pStmt, 0);
111559     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
111560     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
111561       return SQLITE_CORRUPT;
111562     }
111563   }
111564   return SQLITE_OK;
111565 }
111566
111567 /*
111568 ** Set *ppStmt to a statement handle that may be used to iterate through
111569 ** all rows in the %_segdir table, from oldest to newest. If successful,
111570 ** return SQLITE_OK. If an error occurs while preparing the statement, 
111571 ** return an SQLite error code.
111572 **
111573 ** There is only ever one instance of this SQL statement compiled for
111574 ** each FTS3 table.
111575 **
111576 ** The statement returns the following columns from the %_segdir table:
111577 **
111578 **   0: idx
111579 **   1: start_block
111580 **   2: leaves_end_block
111581 **   3: end_block
111582 **   4: root
111583 */
111584 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
111585   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
111586 }
111587
111588
111589 /*
111590 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
111591 ** if successful, or an SQLite error code otherwise.
111592 **
111593 ** This function also serves to allocate the PendingList structure itself.
111594 ** For example, to create a new PendingList structure containing two
111595 ** varints:
111596 **
111597 **   PendingList *p = 0;
111598 **   fts3PendingListAppendVarint(&p, 1);
111599 **   fts3PendingListAppendVarint(&p, 2);
111600 */
111601 static int fts3PendingListAppendVarint(
111602   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
111603   sqlite3_int64 i                 /* Value to append to data */
111604 ){
111605   PendingList *p = *pp;
111606
111607   /* Allocate or grow the PendingList as required. */
111608   if( !p ){
111609     p = sqlite3_malloc(sizeof(*p) + 100);
111610     if( !p ){
111611       return SQLITE_NOMEM;
111612     }
111613     p->nSpace = 100;
111614     p->aData = (char *)&p[1];
111615     p->nData = 0;
111616   }
111617   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
111618     int nNew = p->nSpace * 2;
111619     p = sqlite3_realloc(p, sizeof(*p) + nNew);
111620     if( !p ){
111621       sqlite3_free(*pp);
111622       *pp = 0;
111623       return SQLITE_NOMEM;
111624     }
111625     p->nSpace = nNew;
111626     p->aData = (char *)&p[1];
111627   }
111628
111629   /* Append the new serialized varint to the end of the list. */
111630   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
111631   p->aData[p->nData] = '\0';
111632   *pp = p;
111633   return SQLITE_OK;
111634 }
111635
111636 /*
111637 ** Add a docid/column/position entry to a PendingList structure. Non-zero
111638 ** is returned if the structure is sqlite3_realloced as part of adding
111639 ** the entry. Otherwise, zero.
111640 **
111641 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
111642 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
111643 ** it is set to SQLITE_OK.
111644 */
111645 static int fts3PendingListAppend(
111646   PendingList **pp,               /* IN/OUT: PendingList structure */
111647   sqlite3_int64 iDocid,           /* Docid for entry to add */
111648   sqlite3_int64 iCol,             /* Column for entry to add */
111649   sqlite3_int64 iPos,             /* Position of term for entry to add */
111650   int *pRc                        /* OUT: Return code */
111651 ){
111652   PendingList *p = *pp;
111653   int rc = SQLITE_OK;
111654
111655   assert( !p || p->iLastDocid<=iDocid );
111656
111657   if( !p || p->iLastDocid!=iDocid ){
111658     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
111659     if( p ){
111660       assert( p->nData<p->nSpace );
111661       assert( p->aData[p->nData]==0 );
111662       p->nData++;
111663     }
111664     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
111665       goto pendinglistappend_out;
111666     }
111667     p->iLastCol = -1;
111668     p->iLastPos = 0;
111669     p->iLastDocid = iDocid;
111670   }
111671   if( iCol>0 && p->iLastCol!=iCol ){
111672     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
111673      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
111674     ){
111675       goto pendinglistappend_out;
111676     }
111677     p->iLastCol = iCol;
111678     p->iLastPos = 0;
111679   }
111680   if( iCol>=0 ){
111681     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
111682     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
111683     if( rc==SQLITE_OK ){
111684       p->iLastPos = iPos;
111685     }
111686   }
111687
111688  pendinglistappend_out:
111689   *pRc = rc;
111690   if( p!=*pp ){
111691     *pp = p;
111692     return 1;
111693   }
111694   return 0;
111695 }
111696
111697 /*
111698 ** Tokenize the nul-terminated string zText and add all tokens to the
111699 ** pending-terms hash-table. The docid used is that currently stored in
111700 ** p->iPrevDocid, and the column is specified by argument iCol.
111701 **
111702 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
111703 */
111704 static int fts3PendingTermsAdd(
111705   Fts3Table *p,          /* FTS table into which text will be inserted */
111706   const char *zText,     /* Text of document to be inseted */
111707   int iCol,              /* Column number into which text is inserted */
111708   u32 *pnWord            /* OUT: Number of tokens inserted */
111709 ){
111710   int rc;
111711   int iStart;
111712   int iEnd;
111713   int iPos;
111714   int nWord = 0;
111715
111716   char const *zToken;
111717   int nToken;
111718
111719   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
111720   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
111721   sqlite3_tokenizer_cursor *pCsr;
111722   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
111723       const char**,int*,int*,int*,int*);
111724
111725   assert( pTokenizer && pModule );
111726
111727   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
111728   if( rc!=SQLITE_OK ){
111729     return rc;
111730   }
111731   pCsr->pTokenizer = pTokenizer;
111732
111733   xNext = pModule->xNext;
111734   while( SQLITE_OK==rc
111735       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
111736   ){
111737     PendingList *pList;
111738  
111739     if( iPos>=nWord ) nWord = iPos+1;
111740
111741     /* Positions cannot be negative; we use -1 as a terminator internally.
111742     ** Tokens must have a non-zero length.
111743     */
111744     if( iPos<0 || !zToken || nToken<=0 ){
111745       rc = SQLITE_ERROR;
111746       break;
111747     }
111748
111749     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
111750     if( pList ){
111751       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
111752     }
111753     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
111754       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
111755         /* Malloc failed while inserting the new entry. This can only 
111756         ** happen if there was no previous entry for this token.
111757         */
111758         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
111759         sqlite3_free(pList);
111760         rc = SQLITE_NOMEM;
111761       }
111762     }
111763     if( rc==SQLITE_OK ){
111764       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
111765     }
111766   }
111767
111768   pModule->xClose(pCsr);
111769   *pnWord = nWord;
111770   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
111771 }
111772
111773 /* 
111774 ** Calling this function indicates that subsequent calls to 
111775 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
111776 ** contents of the document with docid iDocid.
111777 */
111778 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
111779   /* TODO(shess) Explore whether partially flushing the buffer on
111780   ** forced-flush would provide better performance.  I suspect that if
111781   ** we ordered the doclists by size and flushed the largest until the
111782   ** buffer was half empty, that would let the less frequent terms
111783   ** generate longer doclists.
111784   */
111785   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
111786     int rc = sqlite3Fts3PendingTermsFlush(p);
111787     if( rc!=SQLITE_OK ) return rc;
111788   }
111789   p->iPrevDocid = iDocid;
111790   return SQLITE_OK;
111791 }
111792
111793 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
111794   Fts3HashElem *pElem;
111795   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
111796     sqlite3_free(fts3HashData(pElem));
111797   }
111798   fts3HashClear(&p->pendingTerms);
111799   p->nPendingData = 0;
111800 }
111801
111802 /*
111803 ** This function is called by the xUpdate() method as part of an INSERT
111804 ** operation. It adds entries for each term in the new record to the
111805 ** pendingTerms hash table.
111806 **
111807 ** Argument apVal is the same as the similarly named argument passed to
111808 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
111809 */
111810 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
111811   int i;                          /* Iterator variable */
111812   for(i=2; i<p->nColumn+2; i++){
111813     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
111814     if( zText ){
111815       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
111816       if( rc!=SQLITE_OK ){
111817         return rc;
111818       }
111819     }
111820   }
111821   return SQLITE_OK;
111822 }
111823
111824 /*
111825 ** This function is called by the xUpdate() method for an INSERT operation.
111826 ** The apVal parameter is passed a copy of the apVal argument passed by
111827 ** SQLite to the xUpdate() method. i.e:
111828 **
111829 **   apVal[0]                Not used for INSERT.
111830 **   apVal[1]                rowid
111831 **   apVal[2]                Left-most user-defined column
111832 **   ...
111833 **   apVal[p->nColumn+1]     Right-most user-defined column
111834 **   apVal[p->nColumn+2]     Hidden column with same name as table
111835 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
111836 */
111837 static int fts3InsertData(
111838   Fts3Table *p,                   /* Full-text table */
111839   sqlite3_value **apVal,          /* Array of values to insert */
111840   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
111841 ){
111842   int rc;                         /* Return code */
111843   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
111844
111845   /* Locate the statement handle used to insert data into the %_content
111846   ** table. The SQL for this statement is:
111847   **
111848   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
111849   **
111850   ** The statement features N '?' variables, where N is the number of user
111851   ** defined columns in the FTS3 table, plus one for the docid field.
111852   */
111853   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
111854   if( rc!=SQLITE_OK ){
111855     return rc;
111856   }
111857
111858   /* There is a quirk here. The users INSERT statement may have specified
111859   ** a value for the "rowid" field, for the "docid" field, or for both.
111860   ** Which is a problem, since "rowid" and "docid" are aliases for the
111861   ** same value. For example:
111862   **
111863   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
111864   **
111865   ** In FTS3, this is an error. It is an error to specify non-NULL values
111866   ** for both docid and some other rowid alias.
111867   */
111868   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
111869     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
111870      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
111871     ){
111872       /* A rowid/docid conflict. */
111873       return SQLITE_ERROR;
111874     }
111875     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
111876     if( rc!=SQLITE_OK ) return rc;
111877   }
111878
111879   /* Execute the statement to insert the record. Set *piDocid to the 
111880   ** new docid value. 
111881   */
111882   sqlite3_step(pContentInsert);
111883   rc = sqlite3_reset(pContentInsert);
111884
111885   *piDocid = sqlite3_last_insert_rowid(p->db);
111886   return rc;
111887 }
111888
111889
111890
111891 /*
111892 ** Remove all data from the FTS3 table. Clear the hash table containing
111893 ** pending terms.
111894 */
111895 static int fts3DeleteAll(Fts3Table *p){
111896   int rc = SQLITE_OK;             /* Return code */
111897
111898   /* Discard the contents of the pending-terms hash table. */
111899   sqlite3Fts3PendingTermsClear(p);
111900
111901   /* Delete everything from the %_content, %_segments and %_segdir tables. */
111902   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
111903   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
111904   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
111905   if( p->bHasDocsize ){
111906     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
111907     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
111908   }
111909   return rc;
111910 }
111911
111912 /*
111913 ** The first element in the apVal[] array is assumed to contain the docid
111914 ** (an integer) of a row about to be deleted. Remove all terms from the
111915 ** full-text index.
111916 */
111917 static void fts3DeleteTerms(
111918   int *pRC,               /* Result code */
111919   Fts3Table *p,           /* The FTS table to delete from */
111920   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
111921   u32 *aSz                /* Sizes of deleted document written here */
111922 ){
111923   int rc;
111924   sqlite3_stmt *pSelect;
111925
111926   if( *pRC ) return;
111927   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
111928   if( rc==SQLITE_OK ){
111929     if( SQLITE_ROW==sqlite3_step(pSelect) ){
111930       int i;
111931       for(i=1; i<=p->nColumn; i++){
111932         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
111933         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
111934         if( rc!=SQLITE_OK ){
111935           sqlite3_reset(pSelect);
111936           *pRC = rc;
111937           return;
111938         }
111939       }
111940     }
111941     rc = sqlite3_reset(pSelect);
111942   }else{
111943     sqlite3_reset(pSelect);
111944   }
111945   *pRC = rc;
111946 }
111947
111948 /*
111949 ** Forward declaration to account for the circular dependency between
111950 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
111951 */
111952 static int fts3SegmentMerge(Fts3Table *, int);
111953
111954 /* 
111955 ** This function allocates a new level iLevel index in the segdir table.
111956 ** Usually, indexes are allocated within a level sequentially starting
111957 ** with 0, so the allocated index is one greater than the value returned
111958 ** by:
111959 **
111960 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
111961 **
111962 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
111963 ** level, they are merged into a single level (iLevel+1) segment and the 
111964 ** allocated index is 0.
111965 **
111966 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
111967 ** returned. Otherwise, an SQLite error code is returned.
111968 */
111969 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
111970   int rc;                         /* Return Code */
111971   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
111972   int iNext = 0;                  /* Result of query pNextIdx */
111973
111974   /* Set variable iNext to the next available segdir index at level iLevel. */
111975   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
111976   if( rc==SQLITE_OK ){
111977     sqlite3_bind_int(pNextIdx, 1, iLevel);
111978     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
111979       iNext = sqlite3_column_int(pNextIdx, 0);
111980     }
111981     rc = sqlite3_reset(pNextIdx);
111982   }
111983
111984   if( rc==SQLITE_OK ){
111985     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
111986     ** full, merge all segments in level iLevel into a single iLevel+1
111987     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
111988     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
111989     */
111990     if( iNext>=FTS3_MERGE_COUNT ){
111991       rc = fts3SegmentMerge(p, iLevel);
111992       *piIdx = 0;
111993     }else{
111994       *piIdx = iNext;
111995     }
111996   }
111997
111998   return rc;
111999 }
112000
112001 /*
112002 ** Move the iterator passed as the first argument to the next term in the
112003 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
112004 ** SQLITE_DONE. Otherwise, an SQLite error code.
112005 */
112006 static int fts3SegReaderNext(Fts3SegReader *pReader){
112007   char *pNext;                    /* Cursor variable */
112008   int nPrefix;                    /* Number of bytes in term prefix */
112009   int nSuffix;                    /* Number of bytes in term suffix */
112010
112011   if( !pReader->aDoclist ){
112012     pNext = pReader->aNode;
112013   }else{
112014     pNext = &pReader->aDoclist[pReader->nDoclist];
112015   }
112016
112017   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
112018     int rc;
112019     if( fts3SegReaderIsPending(pReader) ){
112020       Fts3HashElem *pElem = *(pReader->ppNextElem);
112021       if( pElem==0 ){
112022         pReader->aNode = 0;
112023       }else{
112024         PendingList *pList = (PendingList *)fts3HashData(pElem);
112025         pReader->zTerm = (char *)fts3HashKey(pElem);
112026         pReader->nTerm = fts3HashKeysize(pElem);
112027         pReader->nNode = pReader->nDoclist = pList->nData + 1;
112028         pReader->aNode = pReader->aDoclist = pList->aData;
112029         pReader->ppNextElem++;
112030         assert( pReader->aNode );
112031       }
112032       return SQLITE_OK;
112033     }
112034     if( !pReader->pStmt ){
112035       pReader->aNode = 0;
112036       return SQLITE_OK;
112037     }
112038     rc = sqlite3_step(pReader->pStmt);
112039     if( rc!=SQLITE_ROW ){
112040       pReader->aNode = 0;
112041       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
112042     }
112043     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
112044     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
112045     pNext = pReader->aNode;
112046   }
112047   
112048   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
112049   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
112050
112051   if( nPrefix+nSuffix>pReader->nTermAlloc ){
112052     int nNew = (nPrefix+nSuffix)*2;
112053     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
112054     if( !zNew ){
112055       return SQLITE_NOMEM;
112056     }
112057     pReader->zTerm = zNew;
112058     pReader->nTermAlloc = nNew;
112059   }
112060   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
112061   pReader->nTerm = nPrefix+nSuffix;
112062   pNext += nSuffix;
112063   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
112064   assert( pNext<&pReader->aNode[pReader->nNode] );
112065   pReader->aDoclist = pNext;
112066   pReader->pOffsetList = 0;
112067   return SQLITE_OK;
112068 }
112069
112070 /*
112071 ** Set the SegReader to point to the first docid in the doclist associated
112072 ** with the current term.
112073 */
112074 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
112075   int n;
112076   assert( pReader->aDoclist );
112077   assert( !pReader->pOffsetList );
112078   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
112079   pReader->pOffsetList = &pReader->aDoclist[n];
112080 }
112081
112082 /*
112083 ** Advance the SegReader to point to the next docid in the doclist
112084 ** associated with the current term.
112085 ** 
112086 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
112087 ** *ppOffsetList is set to point to the first column-offset list
112088 ** in the doclist entry (i.e. immediately past the docid varint).
112089 ** *pnOffsetList is set to the length of the set of column-offset
112090 ** lists, not including the nul-terminator byte. For example:
112091 */
112092 static void fts3SegReaderNextDocid(
112093   Fts3SegReader *pReader,
112094   char **ppOffsetList,
112095   int *pnOffsetList
112096 ){
112097   char *p = pReader->pOffsetList;
112098   char c = 0;
112099
112100   /* Pointer p currently points at the first byte of an offset list. The
112101   ** following two lines advance it to point one byte past the end of
112102   ** the same offset list.
112103   */
112104   while( *p | c ) c = *p++ & 0x80;
112105   p++;
112106
112107   /* If required, populate the output variables with a pointer to and the
112108   ** size of the previous offset-list.
112109   */
112110   if( ppOffsetList ){
112111     *ppOffsetList = pReader->pOffsetList;
112112     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
112113   }
112114
112115   /* If there are no more entries in the doclist, set pOffsetList to
112116   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
112117   ** Fts3SegReader.pOffsetList to point to the next offset list before
112118   ** returning.
112119   */
112120   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
112121     pReader->pOffsetList = 0;
112122   }else{
112123     sqlite3_int64 iDelta;
112124     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
112125     pReader->iDocid += iDelta;
112126   }
112127 }
112128
112129 /*
112130 ** Free all allocations associated with the iterator passed as the 
112131 ** second argument.
112132 */
112133 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
112134   if( pReader ){
112135     if( pReader->pStmt ){
112136       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
112137       ** so that it can be reused when required by another query.
112138       */
112139       assert( p->nLeavesStmt<p->nLeavesTotal );
112140       sqlite3_reset(pReader->pStmt);
112141       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
112142     }
112143     if( !fts3SegReaderIsPending(pReader) ){
112144       sqlite3_free(pReader->zTerm);
112145     }
112146     sqlite3_free(pReader);
112147   }
112148 }
112149
112150 /*
112151 ** Allocate a new SegReader object.
112152 */
112153 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
112154   Fts3Table *p,                   /* Virtual table handle */
112155   int iAge,                       /* Segment "age". */
112156   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
112157   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
112158   sqlite3_int64 iEndBlock,        /* Final block of segment */
112159   const char *zRoot,              /* Buffer containing root node */
112160   int nRoot,                      /* Size of buffer containing root node */
112161   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
112162 ){
112163   int rc = SQLITE_OK;             /* Return code */
112164   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
112165   int nExtra = 0;                 /* Bytes to allocate segment root node */
112166
112167   if( iStartLeaf==0 ){
112168     nExtra = nRoot;
112169   }
112170
112171   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
112172   if( !pReader ){
112173     return SQLITE_NOMEM;
112174   }
112175   memset(pReader, 0, sizeof(Fts3SegReader));
112176   pReader->iStartBlock = iStartLeaf;
112177   pReader->iIdx = iAge;
112178   pReader->iEndBlock = iEndBlock;
112179
112180   if( nExtra ){
112181     /* The entire segment is stored in the root node. */
112182     pReader->aNode = (char *)&pReader[1];
112183     pReader->nNode = nRoot;
112184     memcpy(pReader->aNode, zRoot, nRoot);
112185   }else{
112186     /* If the text of the SQL statement to iterate through a contiguous
112187     ** set of entries in the %_segments table has not yet been composed,
112188     ** compose it now.
112189     */
112190     if( !p->zSelectLeaves ){
112191       p->zSelectLeaves = sqlite3_mprintf(
112192           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
112193           "ORDER BY blockid", p->zDb, p->zName
112194       );
112195       if( !p->zSelectLeaves ){
112196         rc = SQLITE_NOMEM;
112197         goto finished;
112198       }
112199     }
112200
112201     /* If there are no free statements in the aLeavesStmt[] array, prepare
112202     ** a new statement now. Otherwise, reuse a prepared statement from
112203     ** aLeavesStmt[].
112204     */
112205     if( p->nLeavesStmt==0 ){
112206       if( p->nLeavesTotal==p->nLeavesAlloc ){
112207         int nNew = p->nLeavesAlloc + 16;
112208         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
112209             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
112210         );
112211         if( !aNew ){
112212           rc = SQLITE_NOMEM;
112213           goto finished;
112214         }
112215         p->nLeavesAlloc = nNew;
112216         p->aLeavesStmt = aNew;
112217       }
112218       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
112219       if( rc!=SQLITE_OK ){
112220         goto finished;
112221       }
112222       p->nLeavesTotal++;
112223     }else{
112224       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
112225     }
112226
112227     /* Bind the start and end leaf blockids to the prepared SQL statement. */
112228     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
112229     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
112230   }
112231   rc = fts3SegReaderNext(pReader);
112232
112233  finished:
112234   if( rc==SQLITE_OK ){
112235     *ppReader = pReader;
112236   }else{
112237     sqlite3Fts3SegReaderFree(p, pReader);
112238   }
112239   return rc;
112240 }
112241
112242 /*
112243 ** This is a comparison function used as a qsort() callback when sorting
112244 ** an array of pending terms by term. This occurs as part of flushing
112245 ** the contents of the pending-terms hash table to the database.
112246 */
112247 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
112248   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
112249   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
112250   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
112251   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
112252
112253   int n = (n1<n2 ? n1 : n2);
112254   int c = memcmp(z1, z2, n);
112255   if( c==0 ){
112256     c = n1 - n2;
112257   }
112258   return c;
112259 }
112260
112261 /*
112262 ** This function is used to allocate an Fts3SegReader that iterates through
112263 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
112264 */
112265 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
112266   Fts3Table *p,                   /* Virtual table handle */
112267   const char *zTerm,              /* Term to search for */
112268   int nTerm,                      /* Size of buffer zTerm */
112269   int isPrefix,                   /* True for a term-prefix query */
112270   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
112271 ){
112272   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
112273   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
112274   int nElem = 0;                  /* Size of array at aElem */
112275   int rc = SQLITE_OK;             /* Return Code */
112276
112277   if( isPrefix ){
112278     int nAlloc = 0;               /* Size of allocated array at aElem */
112279     Fts3HashElem *pE = 0;         /* Iterator variable */
112280
112281     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
112282       char *zKey = (char *)fts3HashKey(pE);
112283       int nKey = fts3HashKeysize(pE);
112284       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
112285         if( nElem==nAlloc ){
112286           Fts3HashElem **aElem2;
112287           nAlloc += 16;
112288           aElem2 = (Fts3HashElem **)sqlite3_realloc(
112289               aElem, nAlloc*sizeof(Fts3HashElem *)
112290           );
112291           if( !aElem2 ){
112292             rc = SQLITE_NOMEM;
112293             nElem = 0;
112294             break;
112295           }
112296           aElem = aElem2;
112297         }
112298         aElem[nElem++] = pE;
112299       }
112300     }
112301
112302     /* If more than one term matches the prefix, sort the Fts3HashElem
112303     ** objects in term order using qsort(). This uses the same comparison
112304     ** callback as is used when flushing terms to disk.
112305     */
112306     if( nElem>1 ){
112307       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
112308     }
112309
112310   }else{
112311     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
112312     if( pE ){
112313       aElem = &pE;
112314       nElem = 1;
112315     }
112316   }
112317
112318   if( nElem>0 ){
112319     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
112320     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
112321     if( !pReader ){
112322       rc = SQLITE_NOMEM;
112323     }else{
112324       memset(pReader, 0, nByte);
112325       pReader->iIdx = 0x7FFFFFFF;
112326       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
112327       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
112328       fts3SegReaderNext(pReader);
112329     }
112330   }
112331
112332   if( isPrefix ){
112333     sqlite3_free(aElem);
112334   }
112335   *ppReader = pReader;
112336   return rc;
112337 }
112338
112339
112340 /*
112341 ** The second argument to this function is expected to be a statement of
112342 ** the form:
112343 **
112344 **   SELECT 
112345 **     idx,                  -- col 0
112346 **     start_block,          -- col 1
112347 **     leaves_end_block,     -- col 2
112348 **     end_block,            -- col 3
112349 **     root                  -- col 4
112350 **   FROM %_segdir ...
112351 **
112352 ** This function allocates and initializes a Fts3SegReader structure to
112353 ** iterate through the terms stored in the segment identified by the
112354 ** current row that pStmt is pointing to. 
112355 **
112356 ** If successful, the Fts3SegReader is left pointing to the first term
112357 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
112358 ** code is returned.
112359 */
112360 static int fts3SegReaderNew(
112361   Fts3Table *p,                   /* Virtual table handle */
112362   sqlite3_stmt *pStmt,            /* See above */
112363   int iAge,                       /* Segment "age". */
112364   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
112365 ){
112366   return sqlite3Fts3SegReaderNew(p, iAge, 
112367       sqlite3_column_int64(pStmt, 1),
112368       sqlite3_column_int64(pStmt, 2),
112369       sqlite3_column_int64(pStmt, 3),
112370       sqlite3_column_blob(pStmt, 4),
112371       sqlite3_column_bytes(pStmt, 4),
112372       ppReader
112373   );
112374 }
112375
112376 /*
112377 ** Compare the entries pointed to by two Fts3SegReader structures. 
112378 ** Comparison is as follows:
112379 **
112380 **   1) EOF is greater than not EOF.
112381 **
112382 **   2) The current terms (if any) are compared using memcmp(). If one
112383 **      term is a prefix of another, the longer term is considered the
112384 **      larger.
112385 **
112386 **   3) By segment age. An older segment is considered larger.
112387 */
112388 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
112389   int rc;
112390   if( pLhs->aNode && pRhs->aNode ){
112391     int rc2 = pLhs->nTerm - pRhs->nTerm;
112392     if( rc2<0 ){
112393       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
112394     }else{
112395       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
112396     }
112397     if( rc==0 ){
112398       rc = rc2;
112399     }
112400   }else{
112401     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
112402   }
112403   if( rc==0 ){
112404     rc = pRhs->iIdx - pLhs->iIdx;
112405   }
112406   assert( rc!=0 );
112407   return rc;
112408 }
112409
112410 /*
112411 ** A different comparison function for SegReader structures. In this
112412 ** version, it is assumed that each SegReader points to an entry in
112413 ** a doclist for identical terms. Comparison is made as follows:
112414 **
112415 **   1) EOF (end of doclist in this case) is greater than not EOF.
112416 **
112417 **   2) By current docid.
112418 **
112419 **   3) By segment age. An older segment is considered larger.
112420 */
112421 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
112422   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
112423   if( rc==0 ){
112424     if( pLhs->iDocid==pRhs->iDocid ){
112425       rc = pRhs->iIdx - pLhs->iIdx;
112426     }else{
112427       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
112428     }
112429   }
112430   assert( pLhs->aNode && pRhs->aNode );
112431   return rc;
112432 }
112433
112434 /*
112435 ** Compare the term that the Fts3SegReader object passed as the first argument
112436 ** points to with the term specified by arguments zTerm and nTerm. 
112437 **
112438 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
112439 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
112440 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
112441 */
112442 static int fts3SegReaderTermCmp(
112443   Fts3SegReader *pSeg,            /* Segment reader object */
112444   const char *zTerm,              /* Term to compare to */
112445   int nTerm                       /* Size of term zTerm in bytes */
112446 ){
112447   int res = 0;
112448   if( pSeg->aNode ){
112449     if( pSeg->nTerm>nTerm ){
112450       res = memcmp(pSeg->zTerm, zTerm, nTerm);
112451     }else{
112452       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
112453     }
112454     if( res==0 ){
112455       res = pSeg->nTerm-nTerm;
112456     }
112457   }
112458   return res;
112459 }
112460
112461 /*
112462 ** Argument apSegment is an array of nSegment elements. It is known that
112463 ** the final (nSegment-nSuspect) members are already in sorted order
112464 ** (according to the comparison function provided). This function shuffles
112465 ** the array around until all entries are in sorted order.
112466 */
112467 static void fts3SegReaderSort(
112468   Fts3SegReader **apSegment,                     /* Array to sort entries of */
112469   int nSegment,                                  /* Size of apSegment array */
112470   int nSuspect,                                  /* Unsorted entry count */
112471   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
112472 ){
112473   int i;                          /* Iterator variable */
112474
112475   assert( nSuspect<=nSegment );
112476
112477   if( nSuspect==nSegment ) nSuspect--;
112478   for(i=nSuspect-1; i>=0; i--){
112479     int j;
112480     for(j=i; j<(nSegment-1); j++){
112481       Fts3SegReader *pTmp;
112482       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
112483       pTmp = apSegment[j+1];
112484       apSegment[j+1] = apSegment[j];
112485       apSegment[j] = pTmp;
112486     }
112487   }
112488
112489 #ifndef NDEBUG
112490   /* Check that the list really is sorted now. */
112491   for(i=0; i<(nSuspect-1); i++){
112492     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
112493   }
112494 #endif
112495 }
112496
112497 /* 
112498 ** Insert a record into the %_segments table.
112499 */
112500 static int fts3WriteSegment(
112501   Fts3Table *p,                   /* Virtual table handle */
112502   sqlite3_int64 iBlock,           /* Block id for new block */
112503   char *z,                        /* Pointer to buffer containing block data */
112504   int n                           /* Size of buffer z in bytes */
112505 ){
112506   sqlite3_stmt *pStmt;
112507   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
112508   if( rc==SQLITE_OK ){
112509     sqlite3_bind_int64(pStmt, 1, iBlock);
112510     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
112511     sqlite3_step(pStmt);
112512     rc = sqlite3_reset(pStmt);
112513   }
112514   return rc;
112515 }
112516
112517 /* 
112518 ** Insert a record into the %_segdir table.
112519 */
112520 static int fts3WriteSegdir(
112521   Fts3Table *p,                   /* Virtual table handle */
112522   int iLevel,                     /* Value for "level" field */
112523   int iIdx,                       /* Value for "idx" field */
112524   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
112525   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
112526   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
112527   char *zRoot,                    /* Blob value for "root" field */
112528   int nRoot                       /* Number of bytes in buffer zRoot */
112529 ){
112530   sqlite3_stmt *pStmt;
112531   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
112532   if( rc==SQLITE_OK ){
112533     sqlite3_bind_int(pStmt, 1, iLevel);
112534     sqlite3_bind_int(pStmt, 2, iIdx);
112535     sqlite3_bind_int64(pStmt, 3, iStartBlock);
112536     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
112537     sqlite3_bind_int64(pStmt, 5, iEndBlock);
112538     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
112539     sqlite3_step(pStmt);
112540     rc = sqlite3_reset(pStmt);
112541   }
112542   return rc;
112543 }
112544
112545 /*
112546 ** Return the size of the common prefix (if any) shared by zPrev and
112547 ** zNext, in bytes. For example, 
112548 **
112549 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
112550 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
112551 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
112552 */
112553 static int fts3PrefixCompress(
112554   const char *zPrev,              /* Buffer containing previous term */
112555   int nPrev,                      /* Size of buffer zPrev in bytes */
112556   const char *zNext,              /* Buffer containing next term */
112557   int nNext                       /* Size of buffer zNext in bytes */
112558 ){
112559   int n;
112560   UNUSED_PARAMETER(nNext);
112561   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
112562   return n;
112563 }
112564
112565 /*
112566 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
112567 ** (according to memcmp) than the previous term.
112568 */
112569 static int fts3NodeAddTerm(
112570   Fts3Table *p,               /* Virtual table handle */
112571   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
112572   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
112573   const char *zTerm,              /* Pointer to buffer containing term */
112574   int nTerm                       /* Size of term in bytes */
112575 ){
112576   SegmentNode *pTree = *ppTree;
112577   int rc;
112578   SegmentNode *pNew;
112579
112580   /* First try to append the term to the current node. Return early if 
112581   ** this is possible.
112582   */
112583   if( pTree ){
112584     int nData = pTree->nData;     /* Current size of node in bytes */
112585     int nReq = nData;             /* Required space after adding zTerm */
112586     int nPrefix;                  /* Number of bytes of prefix compression */
112587     int nSuffix;                  /* Suffix length */
112588
112589     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
112590     nSuffix = nTerm-nPrefix;
112591
112592     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
112593     if( nReq<=p->nNodeSize || !pTree->zTerm ){
112594
112595       if( nReq>p->nNodeSize ){
112596         /* An unusual case: this is the first term to be added to the node
112597         ** and the static node buffer (p->nNodeSize bytes) is not large
112598         ** enough. Use a separately malloced buffer instead This wastes
112599         ** p->nNodeSize bytes, but since this scenario only comes about when
112600         ** the database contain two terms that share a prefix of almost 2KB, 
112601         ** this is not expected to be a serious problem. 
112602         */
112603         assert( pTree->aData==(char *)&pTree[1] );
112604         pTree->aData = (char *)sqlite3_malloc(nReq);
112605         if( !pTree->aData ){
112606           return SQLITE_NOMEM;
112607         }
112608       }
112609
112610       if( pTree->zTerm ){
112611         /* There is no prefix-length field for first term in a node */
112612         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
112613       }
112614
112615       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
112616       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
112617       pTree->nData = nData + nSuffix;
112618       pTree->nEntry++;
112619
112620       if( isCopyTerm ){
112621         if( pTree->nMalloc<nTerm ){
112622           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
112623           if( !zNew ){
112624             return SQLITE_NOMEM;
112625           }
112626           pTree->nMalloc = nTerm*2;
112627           pTree->zMalloc = zNew;
112628         }
112629         pTree->zTerm = pTree->zMalloc;
112630         memcpy(pTree->zTerm, zTerm, nTerm);
112631         pTree->nTerm = nTerm;
112632       }else{
112633         pTree->zTerm = (char *)zTerm;
112634         pTree->nTerm = nTerm;
112635       }
112636       return SQLITE_OK;
112637     }
112638   }
112639
112640   /* If control flows to here, it was not possible to append zTerm to the
112641   ** current node. Create a new node (a right-sibling of the current node).
112642   ** If this is the first node in the tree, the term is added to it.
112643   **
112644   ** Otherwise, the term is not added to the new node, it is left empty for
112645   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
112646   ** has no parent, one is created here.
112647   */
112648   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
112649   if( !pNew ){
112650     return SQLITE_NOMEM;
112651   }
112652   memset(pNew, 0, sizeof(SegmentNode));
112653   pNew->nData = 1 + FTS3_VARINT_MAX;
112654   pNew->aData = (char *)&pNew[1];
112655
112656   if( pTree ){
112657     SegmentNode *pParent = pTree->pParent;
112658     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
112659     if( pTree->pParent==0 ){
112660       pTree->pParent = pParent;
112661     }
112662     pTree->pRight = pNew;
112663     pNew->pLeftmost = pTree->pLeftmost;
112664     pNew->pParent = pParent;
112665     pNew->zMalloc = pTree->zMalloc;
112666     pNew->nMalloc = pTree->nMalloc;
112667     pTree->zMalloc = 0;
112668   }else{
112669     pNew->pLeftmost = pNew;
112670     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
112671   }
112672
112673   *ppTree = pNew;
112674   return rc;
112675 }
112676
112677 /*
112678 ** Helper function for fts3NodeWrite().
112679 */
112680 static int fts3TreeFinishNode(
112681   SegmentNode *pTree, 
112682   int iHeight, 
112683   sqlite3_int64 iLeftChild
112684 ){
112685   int nStart;
112686   assert( iHeight>=1 && iHeight<128 );
112687   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
112688   pTree->aData[nStart] = (char)iHeight;
112689   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
112690   return nStart;
112691 }
112692
112693 /*
112694 ** Write the buffer for the segment node pTree and all of its peers to the
112695 ** database. Then call this function recursively to write the parent of 
112696 ** pTree and its peers to the database. 
112697 **
112698 ** Except, if pTree is a root node, do not write it to the database. Instead,
112699 ** set output variables *paRoot and *pnRoot to contain the root node.
112700 **
112701 ** If successful, SQLITE_OK is returned and output variable *piLast is
112702 ** set to the largest blockid written to the database (or zero if no
112703 ** blocks were written to the db). Otherwise, an SQLite error code is 
112704 ** returned.
112705 */
112706 static int fts3NodeWrite(
112707   Fts3Table *p,                   /* Virtual table handle */
112708   SegmentNode *pTree,             /* SegmentNode handle */
112709   int iHeight,                    /* Height of this node in tree */
112710   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
112711   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
112712   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
112713   char **paRoot,                  /* OUT: Data for root node */
112714   int *pnRoot                     /* OUT: Size of root node in bytes */
112715 ){
112716   int rc = SQLITE_OK;
112717
112718   if( !pTree->pParent ){
112719     /* Root node of the tree. */
112720     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
112721     *piLast = iFree-1;
112722     *pnRoot = pTree->nData - nStart;
112723     *paRoot = &pTree->aData[nStart];
112724   }else{
112725     SegmentNode *pIter;
112726     sqlite3_int64 iNextFree = iFree;
112727     sqlite3_int64 iNextLeaf = iLeaf;
112728     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
112729       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
112730       int nWrite = pIter->nData - nStart;
112731   
112732       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
112733       iNextFree++;
112734       iNextLeaf += (pIter->nEntry+1);
112735     }
112736     if( rc==SQLITE_OK ){
112737       assert( iNextLeaf==iFree );
112738       rc = fts3NodeWrite(
112739           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
112740       );
112741     }
112742   }
112743
112744   return rc;
112745 }
112746
112747 /*
112748 ** Free all memory allocations associated with the tree pTree.
112749 */
112750 static void fts3NodeFree(SegmentNode *pTree){
112751   if( pTree ){
112752     SegmentNode *p = pTree->pLeftmost;
112753     fts3NodeFree(p->pParent);
112754     while( p ){
112755       SegmentNode *pRight = p->pRight;
112756       if( p->aData!=(char *)&p[1] ){
112757         sqlite3_free(p->aData);
112758       }
112759       assert( pRight==0 || p->zMalloc==0 );
112760       sqlite3_free(p->zMalloc);
112761       sqlite3_free(p);
112762       p = pRight;
112763     }
112764   }
112765 }
112766
112767 /*
112768 ** Add a term to the segment being constructed by the SegmentWriter object
112769 ** *ppWriter. When adding the first term to a segment, *ppWriter should
112770 ** be passed NULL. This function will allocate a new SegmentWriter object
112771 ** and return it via the input/output variable *ppWriter in this case.
112772 **
112773 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
112774 */
112775 static int fts3SegWriterAdd(
112776   Fts3Table *p,                   /* Virtual table handle */
112777   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
112778   int isCopyTerm,                 /* True if buffer zTerm must be copied */
112779   const char *zTerm,              /* Pointer to buffer containing term */
112780   int nTerm,                      /* Size of term in bytes */
112781   const char *aDoclist,           /* Pointer to buffer containing doclist */
112782   int nDoclist                    /* Size of doclist in bytes */
112783 ){
112784   int nPrefix;                    /* Size of term prefix in bytes */
112785   int nSuffix;                    /* Size of term suffix in bytes */
112786   int nReq;                       /* Number of bytes required on leaf page */
112787   int nData;
112788   SegmentWriter *pWriter = *ppWriter;
112789
112790   if( !pWriter ){
112791     int rc;
112792     sqlite3_stmt *pStmt;
112793
112794     /* Allocate the SegmentWriter structure */
112795     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
112796     if( !pWriter ) return SQLITE_NOMEM;
112797     memset(pWriter, 0, sizeof(SegmentWriter));
112798     *ppWriter = pWriter;
112799
112800     /* Allocate a buffer in which to accumulate data */
112801     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
112802     if( !pWriter->aData ) return SQLITE_NOMEM;
112803     pWriter->nSize = p->nNodeSize;
112804
112805     /* Find the next free blockid in the %_segments table */
112806     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
112807     if( rc!=SQLITE_OK ) return rc;
112808     if( SQLITE_ROW==sqlite3_step(pStmt) ){
112809       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
112810       pWriter->iFirst = pWriter->iFree;
112811     }
112812     rc = sqlite3_reset(pStmt);
112813     if( rc!=SQLITE_OK ) return rc;
112814   }
112815   nData = pWriter->nData;
112816
112817   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
112818   nSuffix = nTerm-nPrefix;
112819
112820   /* Figure out how many bytes are required by this new entry */
112821   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
112822     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
112823     nSuffix +                               /* Term suffix */
112824     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
112825     nDoclist;                               /* Doclist data */
112826
112827   if( nData>0 && nData+nReq>p->nNodeSize ){
112828     int rc;
112829
112830     /* The current leaf node is full. Write it out to the database. */
112831     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
112832     if( rc!=SQLITE_OK ) return rc;
112833
112834     /* Add the current term to the interior node tree. The term added to
112835     ** the interior tree must:
112836     **
112837     **   a) be greater than the largest term on the leaf node just written
112838     **      to the database (still available in pWriter->zTerm), and
112839     **
112840     **   b) be less than or equal to the term about to be added to the new
112841     **      leaf node (zTerm/nTerm).
112842     **
112843     ** In other words, it must be the prefix of zTerm 1 byte longer than
112844     ** the common prefix (if any) of zTerm and pWriter->zTerm.
112845     */
112846     assert( nPrefix<nTerm );
112847     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
112848     if( rc!=SQLITE_OK ) return rc;
112849
112850     nData = 0;
112851     pWriter->nTerm = 0;
112852
112853     nPrefix = 0;
112854     nSuffix = nTerm;
112855     nReq = 1 +                              /* varint containing prefix size */
112856       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
112857       nTerm +                               /* Term suffix */
112858       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
112859       nDoclist;                             /* Doclist data */
112860   }
112861
112862   /* If the buffer currently allocated is too small for this entry, realloc
112863   ** the buffer to make it large enough.
112864   */
112865   if( nReq>pWriter->nSize ){
112866     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
112867     if( !aNew ) return SQLITE_NOMEM;
112868     pWriter->aData = aNew;
112869     pWriter->nSize = nReq;
112870   }
112871   assert( nData+nReq<=pWriter->nSize );
112872
112873   /* Append the prefix-compressed term and doclist to the buffer. */
112874   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
112875   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
112876   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
112877   nData += nSuffix;
112878   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
112879   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
112880   pWriter->nData = nData + nDoclist;
112881
112882   /* Save the current term so that it can be used to prefix-compress the next.
112883   ** If the isCopyTerm parameter is true, then the buffer pointed to by
112884   ** zTerm is transient, so take a copy of the term data. Otherwise, just
112885   ** store a copy of the pointer.
112886   */
112887   if( isCopyTerm ){
112888     if( nTerm>pWriter->nMalloc ){
112889       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
112890       if( !zNew ){
112891         return SQLITE_NOMEM;
112892       }
112893       pWriter->nMalloc = nTerm*2;
112894       pWriter->zMalloc = zNew;
112895       pWriter->zTerm = zNew;
112896     }
112897     assert( pWriter->zTerm==pWriter->zMalloc );
112898     memcpy(pWriter->zTerm, zTerm, nTerm);
112899   }else{
112900     pWriter->zTerm = (char *)zTerm;
112901   }
112902   pWriter->nTerm = nTerm;
112903
112904   return SQLITE_OK;
112905 }
112906
112907 /*
112908 ** Flush all data associated with the SegmentWriter object pWriter to the
112909 ** database. This function must be called after all terms have been added
112910 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
112911 ** returned. Otherwise, an SQLite error code.
112912 */
112913 static int fts3SegWriterFlush(
112914   Fts3Table *p,                   /* Virtual table handle */
112915   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
112916   int iLevel,                     /* Value for 'level' column of %_segdir */
112917   int iIdx                        /* Value for 'idx' column of %_segdir */
112918 ){
112919   int rc;                         /* Return code */
112920   if( pWriter->pTree ){
112921     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
112922     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
112923     char *zRoot = NULL;           /* Pointer to buffer containing root node */
112924     int nRoot = 0;                /* Size of buffer zRoot */
112925
112926     iLastLeaf = pWriter->iFree;
112927     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
112928     if( rc==SQLITE_OK ){
112929       rc = fts3NodeWrite(p, pWriter->pTree, 1,
112930           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
112931     }
112932     if( rc==SQLITE_OK ){
112933       rc = fts3WriteSegdir(
112934           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
112935     }
112936   }else{
112937     /* The entire tree fits on the root node. Write it to the segdir table. */
112938     rc = fts3WriteSegdir(
112939         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
112940   }
112941   return rc;
112942 }
112943
112944 /*
112945 ** Release all memory held by the SegmentWriter object passed as the 
112946 ** first argument.
112947 */
112948 static void fts3SegWriterFree(SegmentWriter *pWriter){
112949   if( pWriter ){
112950     sqlite3_free(pWriter->aData);
112951     sqlite3_free(pWriter->zMalloc);
112952     fts3NodeFree(pWriter->pTree);
112953     sqlite3_free(pWriter);
112954   }
112955 }
112956
112957 /*
112958 ** The first value in the apVal[] array is assumed to contain an integer.
112959 ** This function tests if there exist any documents with docid values that
112960 ** are different from that integer. i.e. if deleting the document with docid
112961 ** apVal[0] would mean the FTS3 table were empty.
112962 **
112963 ** If successful, *pisEmpty is set to true if the table is empty except for
112964 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
112965 ** error occurs, an SQLite error code is returned.
112966 */
112967 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
112968   sqlite3_stmt *pStmt;
112969   int rc;
112970   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
112971   if( rc==SQLITE_OK ){
112972     if( SQLITE_ROW==sqlite3_step(pStmt) ){
112973       *pisEmpty = sqlite3_column_int(pStmt, 0);
112974     }
112975     rc = sqlite3_reset(pStmt);
112976   }
112977   return rc;
112978 }
112979
112980 /*
112981 ** Set *pnSegment to the number of segments of level iLevel in the database.
112982 **
112983 ** Return SQLITE_OK if successful, or an SQLite error code if not.
112984 */
112985 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
112986   sqlite3_stmt *pStmt;
112987   int rc;
112988
112989   assert( iLevel>=0 );
112990   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
112991   if( rc!=SQLITE_OK ) return rc;
112992   sqlite3_bind_int(pStmt, 1, iLevel);
112993   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112994     *pnSegment = sqlite3_column_int(pStmt, 0);
112995   }
112996   return sqlite3_reset(pStmt);
112997 }
112998
112999 /*
113000 ** Set *pnSegment to the total number of segments in the database. Set
113001 ** *pnMax to the largest segment level in the database (segment levels
113002 ** are stored in the 'level' column of the %_segdir table).
113003 **
113004 ** Return SQLITE_OK if successful, or an SQLite error code if not.
113005 */
113006 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
113007   sqlite3_stmt *pStmt;
113008   int rc;
113009
113010   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
113011   if( rc!=SQLITE_OK ) return rc;
113012   if( SQLITE_ROW==sqlite3_step(pStmt) ){
113013     *pnSegment = sqlite3_column_int(pStmt, 0);
113014     *pnMax = sqlite3_column_int(pStmt, 1);
113015   }
113016   return sqlite3_reset(pStmt);
113017 }
113018
113019 /*
113020 ** This function is used after merging multiple segments into a single large
113021 ** segment to delete the old, now redundant, segment b-trees. Specifically,
113022 ** it:
113023 ** 
113024 **   1) Deletes all %_segments entries for the segments associated with 
113025 **      each of the SegReader objects in the array passed as the third 
113026 **      argument, and
113027 **
113028 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
113029 **      entries regardless of level if (iLevel<0).
113030 **
113031 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
113032 */
113033 static int fts3DeleteSegdir(
113034   Fts3Table *p,                   /* Virtual table handle */
113035   int iLevel,                     /* Level of %_segdir entries to delete */
113036   Fts3SegReader **apSegment,      /* Array of SegReader objects */
113037   int nReader                     /* Size of array apSegment */
113038 ){
113039   int rc;                         /* Return Code */
113040   int i;                          /* Iterator variable */
113041   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
113042
113043   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
113044   for(i=0; rc==SQLITE_OK && i<nReader; i++){
113045     Fts3SegReader *pSegment = apSegment[i];
113046     if( pSegment->iStartBlock ){
113047       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
113048       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
113049       sqlite3_step(pDelete);
113050       rc = sqlite3_reset(pDelete);
113051     }
113052   }
113053   if( rc!=SQLITE_OK ){
113054     return rc;
113055   }
113056
113057   if( iLevel>=0 ){
113058     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
113059     if( rc==SQLITE_OK ){
113060       sqlite3_bind_int(pDelete, 1, iLevel);
113061       sqlite3_step(pDelete);
113062       rc = sqlite3_reset(pDelete);
113063     }
113064   }else{
113065     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
113066   }
113067
113068   return rc;
113069 }
113070
113071 /*
113072 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
113073 ** a position list that may (or may not) feature multiple columns. This
113074 ** function adjusts the pointer *ppList and the length *pnList so that they
113075 ** identify the subset of the position list that corresponds to column iCol.
113076 **
113077 ** If there are no entries in the input position list for column iCol, then
113078 ** *pnList is set to zero before returning.
113079 */
113080 static void fts3ColumnFilter(
113081   int iCol,                       /* Column to filter on */
113082   char **ppList,                  /* IN/OUT: Pointer to position list */
113083   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
113084 ){
113085   char *pList = *ppList;
113086   int nList = *pnList;
113087   char *pEnd = &pList[nList];
113088   int iCurrent = 0;
113089   char *p = pList;
113090
113091   assert( iCol>=0 );
113092   while( 1 ){
113093     char c = 0;
113094     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
113095   
113096     if( iCol==iCurrent ){
113097       nList = (int)(p - pList);
113098       break;
113099     }
113100
113101     nList -= (int)(p - pList);
113102     pList = p;
113103     if( nList==0 ){
113104       break;
113105     }
113106     p = &pList[1];
113107     p += sqlite3Fts3GetVarint32(p, &iCurrent);
113108   }
113109
113110   *ppList = pList;
113111   *pnList = nList;
113112 }
113113
113114 /*
113115 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
113116 ** segments to create a single, larger segment.
113117 */
113118 static int fts3MergeCallback(
113119   Fts3Table *p,                   /* FTS3 Virtual table handle */
113120   void *pContext,                 /* Pointer to SegmentWriter* to write with */
113121   char *zTerm,                    /* Term to write to the db */
113122   int nTerm,                      /* Number of bytes in zTerm */
113123   char *aDoclist,                 /* Doclist associated with zTerm */
113124   int nDoclist                    /* Number of bytes in doclist */
113125 ){
113126   SegmentWriter **ppW = (SegmentWriter **)pContext;
113127   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
113128 }
113129
113130 /*
113131 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
113132 ** of the pending-terms hash table to the database.
113133 */
113134 static int fts3FlushCallback(
113135   Fts3Table *p,                   /* FTS3 Virtual table handle */
113136   void *pContext,                 /* Pointer to SegmentWriter* to write with */
113137   char *zTerm,                    /* Term to write to the db */
113138   int nTerm,                      /* Number of bytes in zTerm */
113139   char *aDoclist,                 /* Doclist associated with zTerm */
113140   int nDoclist                    /* Number of bytes in doclist */
113141 ){
113142   SegmentWriter **ppW = (SegmentWriter **)pContext;
113143   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
113144 }
113145
113146 /*
113147 ** This function is used to iterate through a contiguous set of terms 
113148 ** stored in the full-text index. It merges data contained in one or 
113149 ** more segments to support this.
113150 **
113151 ** The second argument is passed an array of pointers to SegReader objects
113152 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
113153 ** of terms selected by each SegReader. If a single term is present in
113154 ** more than one segment, the associated doclists are merged. For each
113155 ** term and (possibly merged) doclist in the merged range, the callback
113156 ** function xFunc is invoked with its arguments set as follows.
113157 **
113158 **   arg 0: Copy of 'p' parameter passed to this function
113159 **   arg 1: Copy of 'pContext' parameter passed to this function
113160 **   arg 2: Pointer to buffer containing term
113161 **   arg 3: Size of arg 2 buffer in bytes
113162 **   arg 4: Pointer to buffer containing doclist
113163 **   arg 5: Size of arg 2 buffer in bytes
113164 **
113165 ** The 4th argument to this function is a pointer to a structure of type
113166 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
113167 ** further restrict the range of terms that callbacks are made for and
113168 ** modify the behaviour of this function. See comments above structure
113169 ** definition for details.
113170 */
113171 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
113172   Fts3Table *p,                   /* Virtual table handle */
113173   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
113174   int nSegment,                   /* Size of apSegment array */
113175   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
113176   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
113177   void *pContext                  /* Callback context (2nd argument) */
113178 ){
113179   int i;                          /* Iterator variable */
113180   char *aBuffer = 0;              /* Buffer to merge doclists in */
113181   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
113182   int rc = SQLITE_OK;             /* Return code */
113183
113184   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
113185   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
113186   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
113187   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
113188
113189   /* If there are zero segments, this function is a no-op. This scenario
113190   ** comes about only when reading from an empty database.
113191   */
113192   if( nSegment==0 ) goto finished;
113193
113194   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
113195   ** for, then advance each segment iterator until it points to a term of
113196   ** equal or greater value than the specified term. This prevents many
113197   ** unnecessary merge/sort operations for the case where single segment
113198   ** b-tree leaf nodes contain more than one term.
113199   */
113200   if( pFilter->zTerm ){
113201     int nTerm = pFilter->nTerm;
113202     const char *zTerm = pFilter->zTerm;
113203     for(i=0; i<nSegment; i++){
113204       Fts3SegReader *pSeg = apSegment[i];
113205       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
113206         rc = fts3SegReaderNext(pSeg);
113207         if( rc!=SQLITE_OK ) goto finished; }
113208     }
113209   }
113210
113211   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
113212   while( apSegment[0]->aNode ){
113213     int nTerm = apSegment[0]->nTerm;
113214     char *zTerm = apSegment[0]->zTerm;
113215     int nMerge = 1;
113216
113217     /* If this is a prefix-search, and if the term that apSegment[0] points
113218     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
113219     ** required callbacks have been made. In this case exit early.
113220     **
113221     ** Similarly, if this is a search for an exact match, and the first term
113222     ** of segment apSegment[0] is not a match, exit early.
113223     */
113224     if( pFilter->zTerm ){
113225       if( nTerm<pFilter->nTerm 
113226        || (!isPrefix && nTerm>pFilter->nTerm)
113227        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
113228     ){
113229         goto finished;
113230       }
113231     }
113232
113233     while( nMerge<nSegment 
113234         && apSegment[nMerge]->aNode
113235         && apSegment[nMerge]->nTerm==nTerm 
113236         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
113237     ){
113238       nMerge++;
113239     }
113240
113241     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
113242     if( nMerge==1 && !isIgnoreEmpty ){
113243       Fts3SegReader *p0 = apSegment[0];
113244       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
113245       if( rc!=SQLITE_OK ) goto finished;
113246     }else{
113247       int nDoclist = 0;           /* Size of doclist */
113248       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
113249
113250       /* The current term of the first nMerge entries in the array
113251       ** of Fts3SegReader objects is the same. The doclists must be merged
113252       ** and a single term added to the new segment.
113253       */
113254       for(i=0; i<nMerge; i++){
113255         fts3SegReaderFirstDocid(apSegment[i]);
113256       }
113257       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
113258       while( apSegment[0]->pOffsetList ){
113259         int j;                    /* Number of segments that share a docid */
113260         char *pList;
113261         int nList;
113262         int nByte;
113263         sqlite3_int64 iDocid = apSegment[0]->iDocid;
113264         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
113265         j = 1;
113266         while( j<nMerge
113267             && apSegment[j]->pOffsetList
113268             && apSegment[j]->iDocid==iDocid
113269         ){
113270           fts3SegReaderNextDocid(apSegment[j], 0, 0);
113271           j++;
113272         }
113273
113274         if( isColFilter ){
113275           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
113276         }
113277
113278         if( !isIgnoreEmpty || nList>0 ){
113279           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
113280           if( nDoclist+nByte>nAlloc ){
113281             char *aNew;
113282             nAlloc = nDoclist+nByte*2;
113283             aNew = sqlite3_realloc(aBuffer, nAlloc);
113284             if( !aNew ){
113285               rc = SQLITE_NOMEM;
113286               goto finished;
113287             }
113288             aBuffer = aNew;
113289           }
113290           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
113291           iPrev = iDocid;
113292           if( isRequirePos ){
113293             memcpy(&aBuffer[nDoclist], pList, nList);
113294             nDoclist += nList;
113295             aBuffer[nDoclist++] = '\0';
113296           }
113297         }
113298
113299         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
113300       }
113301
113302       if( nDoclist>0 ){
113303         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
113304         if( rc!=SQLITE_OK ) goto finished;
113305       }
113306     }
113307
113308     /* If there is a term specified to filter on, and this is not a prefix
113309     ** search, return now. The callback that corresponds to the required
113310     ** term (if such a term exists in the index) has already been made.
113311     */
113312     if( pFilter->zTerm && !isPrefix ){
113313       goto finished;
113314     }
113315
113316     for(i=0; i<nMerge; i++){
113317       rc = fts3SegReaderNext(apSegment[i]);
113318       if( rc!=SQLITE_OK ) goto finished;
113319     }
113320     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
113321   }
113322
113323  finished:
113324   sqlite3_free(aBuffer);
113325   return rc;
113326 }
113327
113328 /*
113329 ** Merge all level iLevel segments in the database into a single 
113330 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
113331 ** single segment with a level equal to the numerically largest level 
113332 ** currently present in the database.
113333 **
113334 ** If this function is called with iLevel<0, but there is only one
113335 ** segment in the database, SQLITE_DONE is returned immediately. 
113336 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
113337 ** an SQLite error code is returned.
113338 */
113339 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
113340   int i;                          /* Iterator variable */
113341   int rc;                         /* Return code */
113342   int iIdx;                       /* Index of new segment */
113343   int iNewLevel;                  /* Level to create new segment at */
113344   sqlite3_stmt *pStmt = 0;
113345   SegmentWriter *pWriter = 0;
113346   int nSegment = 0;               /* Number of segments being merged */
113347   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
113348   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
113349   Fts3SegFilter filter;           /* Segment term filter condition */
113350
113351   if( iLevel<0 ){
113352     /* This call is to merge all segments in the database to a single
113353     ** segment. The level of the new segment is equal to the the numerically 
113354     ** greatest segment level currently present in the database. The index
113355     ** of the new segment is always 0.
113356     */
113357     iIdx = 0;
113358     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
113359     if( rc!=SQLITE_OK ) goto finished;
113360     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
113361     if( rc!=SQLITE_OK ) goto finished;
113362     nSegment += (pPending!=0);
113363     if( nSegment<=1 ){
113364       return SQLITE_DONE;
113365     }
113366   }else{
113367     /* This call is to merge all segments at level iLevel. Find the next
113368     ** available segment index at level iLevel+1. The call to
113369     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
113370     ** a single iLevel+2 segment if necessary.
113371     */
113372     iNewLevel = iLevel+1;
113373     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
113374     if( rc!=SQLITE_OK ) goto finished;
113375     rc = fts3SegmentCount(p, iLevel, &nSegment);
113376     if( rc!=SQLITE_OK ) goto finished;
113377   }
113378   assert( nSegment>0 );
113379   assert( iNewLevel>=0 );
113380
113381   /* Allocate space for an array of pointers to segment iterators. */
113382   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
113383   if( !apSegment ){
113384     rc = SQLITE_NOMEM;
113385     goto finished;
113386   }
113387   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
113388
113389   /* Allocate a Fts3SegReader structure for each segment being merged. A 
113390   ** Fts3SegReader stores the state data required to iterate through all 
113391   ** entries on all leaves of a single segment. 
113392   */
113393   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
113394   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
113395   if( rc!=SQLITE_OK ) goto finished;
113396   sqlite3_bind_int(pStmt, 1, iLevel);
113397   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
113398     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
113399     if( rc!=SQLITE_OK ){
113400       goto finished;
113401     }
113402   }
113403   rc = sqlite3_reset(pStmt);
113404   if( pPending ){
113405     apSegment[i] = pPending;
113406     pPending = 0;
113407   }
113408   pStmt = 0;
113409   if( rc!=SQLITE_OK ) goto finished;
113410
113411   memset(&filter, 0, sizeof(Fts3SegFilter));
113412   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
113413   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
113414   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
113415       &filter, fts3MergeCallback, (void *)&pWriter
113416   );
113417   if( rc!=SQLITE_OK ) goto finished;
113418
113419   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
113420   if( rc==SQLITE_OK ){
113421     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
113422   }
113423
113424  finished:
113425   fts3SegWriterFree(pWriter);
113426   if( apSegment ){
113427     for(i=0; i<nSegment; i++){
113428       sqlite3Fts3SegReaderFree(p, apSegment[i]);
113429     }
113430     sqlite3_free(apSegment);
113431   }
113432   sqlite3Fts3SegReaderFree(p, pPending);
113433   sqlite3_reset(pStmt);
113434   return rc;
113435 }
113436
113437
113438 /* 
113439 ** Flush the contents of pendingTerms to a level 0 segment.
113440 */
113441 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
113442   int rc;                         /* Return Code */
113443   int idx;                        /* Index of new segment created */
113444   SegmentWriter *pWriter = 0;     /* Used to write the segment */
113445   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
113446
113447   /* Allocate a SegReader object to iterate through the contents of the
113448   ** pending-terms table. If an error occurs, or if there are no terms
113449   ** in the pending-terms table, return immediately.
113450   */
113451   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
113452   if( rc!=SQLITE_OK || pReader==0 ){
113453     return rc;
113454   }
113455
113456   /* Determine the next index at level 0. If level 0 is already full, this
113457   ** call may merge all existing level 0 segments into a single level 1
113458   ** segment.
113459   */
113460   rc = fts3AllocateSegdirIdx(p, 0, &idx);
113461
113462   /* If no errors have occured, iterate through the contents of the 
113463   ** pending-terms hash table using the Fts3SegReader iterator. The callback
113464   ** writes each term (along with its doclist) to the database via the
113465   ** SegmentWriter handle pWriter.
113466   */
113467   if( rc==SQLITE_OK ){
113468     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
113469     Fts3SegFilter f;              /* SegReaderIterate() parameters */
113470
113471     memset(&f, 0, sizeof(Fts3SegFilter));
113472     f.flags = FTS3_SEGMENT_REQUIRE_POS;
113473     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
113474   }
113475   assert( pWriter || rc!=SQLITE_OK );
113476
113477   /* If no errors have occured, flush the SegmentWriter object to the
113478   ** database. Then delete the SegmentWriter and Fts3SegReader objects
113479   ** allocated by this function.
113480   */
113481   if( rc==SQLITE_OK ){
113482     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
113483   }
113484   fts3SegWriterFree(pWriter);
113485   sqlite3Fts3SegReaderFree(p, pReader);
113486
113487   if( rc==SQLITE_OK ){
113488     sqlite3Fts3PendingTermsClear(p);
113489   }
113490   return rc;
113491 }
113492
113493 /*
113494 ** Encode N integers as varints into a blob.
113495 */
113496 static void fts3EncodeIntArray(
113497   int N,             /* The number of integers to encode */
113498   u32 *a,            /* The integer values */
113499   char *zBuf,        /* Write the BLOB here */
113500   int *pNBuf         /* Write number of bytes if zBuf[] used here */
113501 ){
113502   int i, j;
113503   for(i=j=0; i<N; i++){
113504     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
113505   }
113506   *pNBuf = j;
113507 }
113508
113509 /*
113510 ** Decode a blob of varints into N integers
113511 */
113512 static void fts3DecodeIntArray(
113513   int N,             /* The number of integers to decode */
113514   u32 *a,            /* Write the integer values */
113515   const char *zBuf,  /* The BLOB containing the varints */
113516   int nBuf           /* size of the BLOB */
113517 ){
113518   int i, j;
113519   UNUSED_PARAMETER(nBuf);
113520   for(i=j=0; i<N; i++){
113521     sqlite3_int64 x;
113522     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
113523     assert(j<=nBuf);
113524     a[i] = (u32)(x & 0xffffffff);
113525   }
113526 }
113527
113528 /*
113529 ** Fill in the document size auxiliary information for the matchinfo
113530 ** structure.  The auxiliary information is:
113531 **
113532 **    N     Total number of documents in the full-text index
113533 **    a0    Average length of column 0 over the whole index
113534 **    n0    Length of column 0 on the matching row
113535 **    ...
113536 **    aM    Average length of column M over the whole index
113537 **    nM    Length of column M on the matching row
113538 **
113539 ** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
113540 ** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
113541 */
113542 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
113543   const char *pBlob;       /* The BLOB holding %_docsize info */
113544   int nBlob;               /* Size of the BLOB */
113545   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113546   int i, j;                /* Loop counters */
113547   sqlite3_int64 x;         /* Varint value */
113548   int rc;                  /* Result code from subfunctions */
113549   Fts3Table *p;            /* The FTS table */
113550
113551   p = (Fts3Table*)pCur->base.pVtab;
113552   rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
113553   if( rc ){
113554     return rc;
113555   }
113556   sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
113557   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113558     nBlob = sqlite3_column_bytes(pStmt, 0);
113559     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113560     for(i=j=0; i<p->nColumn && j<nBlob; i++){
113561       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113562       a[2+i*2] = (u32)(x & 0xffffffff);
113563     }
113564   }
113565   sqlite3_reset(pStmt);
113566   return SQLITE_OK; 
113567 }
113568 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
113569   const char *pBlob;       /* The BLOB holding %_stat info */
113570   int nBlob;               /* Size of the BLOB */
113571   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113572   int i, j;                /* Loop counters */
113573   sqlite3_int64 x;         /* Varint value */
113574   int nDoc;                /* Number of documents */
113575   int rc;                  /* Result code from subfunctions */
113576   Fts3Table *p;            /* The FTS table */
113577
113578   p = (Fts3Table*)pCur->base.pVtab;
113579   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113580   if( rc ){
113581     return rc;
113582   }
113583   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113584     nBlob = sqlite3_column_bytes(pStmt, 0);
113585     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113586     j = sqlite3Fts3GetVarint(pBlob, &x);
113587     a[0] = nDoc = (u32)(x & 0xffffffff);
113588     for(i=0; i<p->nColumn && j<nBlob; i++){
113589       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113590       a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
113591     }
113592   }
113593   sqlite3_reset(pStmt);
113594   return SQLITE_OK; 
113595 }
113596
113597 /*
113598 ** Insert the sizes (in tokens) for each column of the document
113599 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
113600 ** a blob of varints.
113601 */
113602 static void fts3InsertDocsize(
113603   int *pRC,         /* Result code */
113604   Fts3Table *p,     /* Table into which to insert */
113605   u32 *aSz          /* Sizes of each column */
113606 ){
113607   char *pBlob;             /* The BLOB encoding of the document size */
113608   int nBlob;               /* Number of bytes in the BLOB */
113609   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
113610   int rc;                  /* Result code from subfunctions */
113611
113612   if( *pRC ) return;
113613   pBlob = sqlite3_malloc( 10*p->nColumn );
113614   if( pBlob==0 ){
113615     *pRC = SQLITE_NOMEM;
113616     return;
113617   }
113618   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
113619   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
113620   if( rc ){
113621     sqlite3_free(pBlob);
113622     *pRC = rc;
113623     return;
113624   }
113625   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
113626   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
113627   sqlite3_step(pStmt);
113628   *pRC = sqlite3_reset(pStmt);
113629 }
113630
113631 /*
113632 ** Update the 0 record of the %_stat table so that it holds a blob
113633 ** which contains the document count followed by the cumulative
113634 ** document sizes for all columns.
113635 */
113636 static void fts3UpdateDocTotals(
113637   int *pRC,       /* The result code */
113638   Fts3Table *p,   /* Table being updated */
113639   u32 *aSzIns,    /* Size increases */
113640   u32 *aSzDel,    /* Size decreases */
113641   int nChng       /* Change in the number of documents */
113642 ){
113643   char *pBlob;             /* Storage for BLOB written into %_stat */
113644   int nBlob;               /* Size of BLOB written into %_stat */
113645   u32 *a;                  /* Array of integers that becomes the BLOB */
113646   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113647   int i;                   /* Loop counter */
113648   int rc;                  /* Result code from subfunctions */
113649
113650   if( *pRC ) return;
113651   a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
113652   if( a==0 ){
113653     *pRC = SQLITE_NOMEM;
113654     return;
113655   }
113656   pBlob = (char*)&a[p->nColumn+1];
113657   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113658   if( rc ){
113659     sqlite3_free(a);
113660     *pRC = rc;
113661     return;
113662   }
113663   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113664     fts3DecodeIntArray(p->nColumn+1, a,
113665          sqlite3_column_blob(pStmt, 0),
113666          sqlite3_column_bytes(pStmt, 0));
113667   }else{
113668     memset(a, 0, sizeof(u32)*(p->nColumn+1) );
113669   }
113670   sqlite3_reset(pStmt);
113671   if( nChng<0 && a[0]<(u32)(-nChng) ){
113672     a[0] = 0;
113673   }else{
113674     a[0] += nChng;
113675   }
113676   for(i=0; i<p->nColumn; i++){
113677     u32 x = a[i+1];
113678     if( x+aSzIns[i] < aSzDel[i] ){
113679       x = 0;
113680     }else{
113681       x = x + aSzIns[i] - aSzDel[i];
113682     }
113683     a[i+1] = x;
113684   }
113685   fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
113686   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
113687   if( rc ){
113688     sqlite3_free(a);
113689     *pRC = rc;
113690     return;
113691   }
113692   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
113693   sqlite3_step(pStmt);
113694   *pRC = sqlite3_reset(pStmt);
113695   sqlite3_free(a);
113696 }
113697
113698 /*
113699 ** Handle a 'special' INSERT of the form:
113700 **
113701 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
113702 **
113703 ** Argument pVal contains the result of <expr>. Currently the only 
113704 ** meaningful value to insert is the text 'optimize'.
113705 */
113706 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
113707   int rc;                         /* Return Code */
113708   const char *zVal = (const char *)sqlite3_value_text(pVal);
113709   int nVal = sqlite3_value_bytes(pVal);
113710
113711   if( !zVal ){
113712     return SQLITE_NOMEM;
113713   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
113714     rc = fts3SegmentMerge(p, -1);
113715     if( rc==SQLITE_DONE ){
113716       rc = SQLITE_OK;
113717     }else{
113718       sqlite3Fts3PendingTermsClear(p);
113719     }
113720 #ifdef SQLITE_TEST
113721   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
113722     p->nNodeSize = atoi(&zVal[9]);
113723     rc = SQLITE_OK;
113724   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
113725     p->nMaxPendingData = atoi(&zVal[11]);
113726     rc = SQLITE_OK;
113727 #endif
113728   }else{
113729     rc = SQLITE_ERROR;
113730   }
113731
113732   return rc;
113733 }
113734
113735 /*
113736 ** This function does the work for the xUpdate method of FTS3 virtual
113737 ** tables.
113738 */
113739 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
113740   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
113741   int nArg,                       /* Size of argument array */
113742   sqlite3_value **apVal,          /* Array of arguments */
113743   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
113744 ){
113745   Fts3Table *p = (Fts3Table *)pVtab;
113746   int rc = SQLITE_OK;             /* Return Code */
113747   int isRemove = 0;               /* True for an UPDATE or DELETE */
113748   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
113749   u32 *aSzIns;                    /* Sizes of inserted documents */
113750   u32 *aSzDel;                    /* Sizes of deleted documents */
113751   int nChng = 0;                  /* Net change in number of documents */
113752
113753
113754   /* Allocate space to hold the change in document sizes */
113755   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
113756   if( aSzIns==0 ) return SQLITE_NOMEM;
113757   aSzDel = &aSzIns[p->nColumn];
113758   memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
113759
113760   /* If this is a DELETE or UPDATE operation, remove the old record. */
113761   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
113762     int isEmpty;
113763     rc = fts3IsEmpty(p, apVal, &isEmpty);
113764     if( rc==SQLITE_OK ){
113765       if( isEmpty ){
113766         /* Deleting this row means the whole table is empty. In this case
113767         ** delete the contents of all three tables and throw away any
113768         ** data in the pendingTerms hash table.
113769         */
113770         rc = fts3DeleteAll(p);
113771       }else{
113772         isRemove = 1;
113773         iRemove = sqlite3_value_int64(apVal[0]);
113774         rc = fts3PendingTermsDocid(p, iRemove);
113775         fts3DeleteTerms(&rc, p, apVal, aSzDel);
113776         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
113777         if( p->bHasDocsize ){
113778           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
113779           nChng--;
113780         }
113781       }
113782     }
113783   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
113784     sqlite3_free(aSzIns);
113785     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
113786   }
113787   
113788   /* If this is an INSERT or UPDATE operation, insert the new record. */
113789   if( nArg>1 && rc==SQLITE_OK ){
113790     rc = fts3InsertData(p, apVal, pRowid);
113791     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
113792       rc = fts3PendingTermsDocid(p, *pRowid);
113793     }
113794     if( rc==SQLITE_OK ){
113795       rc = fts3InsertTerms(p, apVal, aSzIns);
113796     }
113797     if( p->bHasDocsize ){
113798       nChng++;
113799       fts3InsertDocsize(&rc, p, aSzIns);
113800     }
113801   }
113802
113803   if( p->bHasDocsize ){
113804     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
113805   }
113806
113807   sqlite3_free(aSzIns);
113808   return rc;
113809 }
113810
113811 /* 
113812 ** Flush any data in the pending-terms hash table to disk. If successful,
113813 ** merge all segments in the database (including the new segment, if 
113814 ** there was any data to flush) into a single segment. 
113815 */
113816 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
113817   int rc;
113818   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
113819   if( rc==SQLITE_OK ){
113820     rc = fts3SegmentMerge(p, -1);
113821     if( rc==SQLITE_OK ){
113822       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113823       if( rc==SQLITE_OK ){
113824         sqlite3Fts3PendingTermsClear(p);
113825       }
113826     }else{
113827       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
113828       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113829     }
113830   }
113831   return rc;
113832 }
113833
113834 #endif
113835
113836 /************** End of fts3_write.c ******************************************/
113837 /************** Begin file fts3_snippet.c ************************************/
113838 /*
113839 ** 2009 Oct 23
113840 **
113841 ** The author disclaims copyright to this source code.  In place of
113842 ** a legal notice, here is a blessing:
113843 **
113844 **    May you do good and not evil.
113845 **    May you find forgiveness for yourself and forgive others.
113846 **    May you share freely, never taking more than you give.
113847 **
113848 ******************************************************************************
113849 */
113850
113851 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113852
113853
113854
113855 /*
113856 ** Used as an fts3ExprIterate() context when loading phrase doclists to
113857 ** Fts3Expr.aDoclist[]/nDoclist.
113858 */
113859 typedef struct LoadDoclistCtx LoadDoclistCtx;
113860 struct LoadDoclistCtx {
113861   Fts3Table *pTab;                /* FTS3 Table */
113862   int nPhrase;                    /* Number of phrases seen so far */
113863   int nToken;                     /* Number of tokens seen so far */
113864 };
113865
113866 /*
113867 ** The following types are used as part of the implementation of the 
113868 ** fts3BestSnippet() routine.
113869 */
113870 typedef struct SnippetIter SnippetIter;
113871 typedef struct SnippetPhrase SnippetPhrase;
113872 typedef struct SnippetFragment SnippetFragment;
113873
113874 struct SnippetIter {
113875   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
113876   int iCol;                       /* Extract snippet from this column */
113877   int nSnippet;                   /* Requested snippet length (in tokens) */
113878   int nPhrase;                    /* Number of phrases in query */
113879   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
113880   int iCurrent;                   /* First token of current snippet */
113881 };
113882
113883 struct SnippetPhrase {
113884   int nToken;                     /* Number of tokens in phrase */
113885   char *pList;                    /* Pointer to start of phrase position list */
113886   int iHead;                      /* Next value in position list */
113887   char *pHead;                    /* Position list data following iHead */
113888   int iTail;                      /* Next value in trailing position list */
113889   char *pTail;                    /* Position list data following iTail */
113890 };
113891
113892 struct SnippetFragment {
113893   int iCol;                       /* Column snippet is extracted from */
113894   int iPos;                       /* Index of first token in snippet */
113895   u64 covered;                    /* Mask of query phrases covered */
113896   u64 hlmask;                     /* Mask of snippet terms to highlight */
113897 };
113898
113899 /*
113900 ** This type is used as an fts3ExprIterate() context object while 
113901 ** accumulating the data returned by the matchinfo() function.
113902 */
113903 typedef struct MatchInfo MatchInfo;
113904 struct MatchInfo {
113905   Fts3Cursor *pCursor;            /* FTS3 Cursor */
113906   int nCol;                       /* Number of columns in table */
113907   u32 *aMatchinfo;                /* Pre-allocated buffer */
113908 };
113909
113910
113911
113912 /*
113913 ** The snippet() and offsets() functions both return text values. An instance
113914 ** of the following structure is used to accumulate those values while the
113915 ** functions are running. See fts3StringAppend() for details.
113916 */
113917 typedef struct StrBuffer StrBuffer;
113918 struct StrBuffer {
113919   char *z;                        /* Pointer to buffer containing string */
113920   int n;                          /* Length of z in bytes (excl. nul-term) */
113921   int nAlloc;                     /* Allocated size of buffer z in bytes */
113922 };
113923
113924
113925 /*
113926 ** This function is used to help iterate through a position-list. A position
113927 ** list is a list of unique integers, sorted from smallest to largest. Each
113928 ** element of the list is represented by an FTS3 varint that takes the value
113929 ** of the difference between the current element and the previous one plus
113930 ** two. For example, to store the position-list:
113931 **
113932 **     4 9 113
113933 **
113934 ** the three varints:
113935 **
113936 **     6 7 106
113937 **
113938 ** are encoded.
113939 **
113940 ** When this function is called, *pp points to the start of an element of
113941 ** the list. *piPos contains the value of the previous entry in the list.
113942 ** After it returns, *piPos contains the value of the next element of the
113943 ** list and *pp is advanced to the following varint.
113944 */
113945 static void fts3GetDeltaPosition(char **pp, int *piPos){
113946   int iVal;
113947   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
113948   *piPos += (iVal-2);
113949 }
113950
113951 /*
113952 ** Helper function for fts3ExprIterate() (see below).
113953 */
113954 static int fts3ExprIterate2(
113955   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113956   int *piPhrase,                  /* Pointer to phrase counter */
113957   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113958   void *pCtx                      /* Second argument to pass to callback */
113959 ){
113960   int rc;                         /* Return code */
113961   int eType = pExpr->eType;       /* Type of expression node pExpr */
113962
113963   if( eType!=FTSQUERY_PHRASE ){
113964     assert( pExpr->pLeft && pExpr->pRight );
113965     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
113966     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
113967       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
113968     }
113969   }else{
113970     rc = x(pExpr, *piPhrase, pCtx);
113971     (*piPhrase)++;
113972   }
113973   return rc;
113974 }
113975
113976 /*
113977 ** Iterate through all phrase nodes in an FTS3 query, except those that
113978 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
113979 ** For each phrase node found, the supplied callback function is invoked.
113980 **
113981 ** If the callback function returns anything other than SQLITE_OK, 
113982 ** the iteration is abandoned and the error code returned immediately.
113983 ** Otherwise, SQLITE_OK is returned after a callback has been made for
113984 ** all eligible phrase nodes.
113985 */
113986 static int fts3ExprIterate(
113987   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113988   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113989   void *pCtx                      /* Second argument to pass to callback */
113990 ){
113991   int iPhrase = 0;                /* Variable used as the phrase counter */
113992   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
113993 }
113994
113995 /*
113996 ** The argument to this function is always a phrase node. Its doclist 
113997 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
113998 ** to the left of this one in the query tree have already been loaded.
113999 **
114000 ** If this phrase node is part of a series of phrase nodes joined by 
114001 ** NEAR operators (and is not the left-most of said series), then elements are
114002 ** removed from the phrases doclist consistent with the NEAR restriction. If
114003 ** required, elements may be removed from the doclists of phrases to the
114004 ** left of this one that are part of the same series of NEAR operator 
114005 ** connected phrases.
114006 **
114007 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
114008 */
114009 static int fts3ExprNearTrim(Fts3Expr *pExpr){
114010   int rc = SQLITE_OK;
114011   Fts3Expr *pParent = pExpr->pParent;
114012
114013   assert( pExpr->eType==FTSQUERY_PHRASE );
114014   while( rc==SQLITE_OK
114015    && pParent 
114016    && pParent->eType==FTSQUERY_NEAR 
114017    && pParent->pRight==pExpr 
114018   ){
114019     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
114020     ** Find the expression to the left of the same operator.
114021     */
114022     int nNear = pParent->nNear;
114023     Fts3Expr *pLeft = pParent->pLeft;
114024
114025     if( pLeft->eType!=FTSQUERY_PHRASE ){
114026       assert( pLeft->eType==FTSQUERY_NEAR );
114027       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
114028       pLeft = pLeft->pRight;
114029     }
114030
114031     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
114032
114033     pExpr = pLeft;
114034     pParent = pExpr->pParent;
114035   }
114036
114037   return rc;
114038 }
114039
114040 /*
114041 ** This is an fts3ExprIterate() callback used while loading the doclists
114042 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
114043 ** fts3ExprLoadDoclists().
114044 */
114045 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
114046   int rc = SQLITE_OK;
114047   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
114048
114049   UNUSED_PARAMETER(iPhrase);
114050
114051   p->nPhrase++;
114052   p->nToken += pExpr->pPhrase->nToken;
114053
114054   if( pExpr->isLoaded==0 ){
114055     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
114056     pExpr->isLoaded = 1;
114057     if( rc==SQLITE_OK ){
114058       rc = fts3ExprNearTrim(pExpr);
114059     }
114060   }
114061
114062   return rc;
114063 }
114064
114065 /*
114066 ** This is an fts3ExprIterate() callback used while loading the doclists
114067 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
114068 ** fts3ExprLoadDoclists().
114069 */
114070 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
114071   UNUSED_PARAMETER(iPhrase);
114072   UNUSED_PARAMETER(ctx);
114073   if( pExpr->aDoclist ){
114074     pExpr->pCurrent = pExpr->aDoclist;
114075     pExpr->iCurrent = 0;
114076     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
114077   }
114078   return SQLITE_OK;
114079 }
114080
114081 /*
114082 ** Load the doclists for each phrase in the query associated with FTS3 cursor
114083 ** pCsr. 
114084 **
114085 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
114086 ** phrases in the expression (all phrases except those directly or 
114087 ** indirectly descended from the right-hand-side of a NOT operator). If 
114088 ** pnToken is not NULL, then it is set to the number of tokens in all
114089 ** matchable phrases of the expression.
114090 */
114091 static int fts3ExprLoadDoclists(
114092   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
114093   int *pnPhrase,                  /* OUT: Number of phrases in query */
114094   int *pnToken                    /* OUT: Number of tokens in query */
114095 ){
114096   int rc;                         /* Return Code */
114097   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
114098   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
114099   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
114100   if( rc==SQLITE_OK ){
114101     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
114102   }
114103   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
114104   if( pnToken ) *pnToken = sCtx.nToken;
114105   return rc;
114106 }
114107
114108 /*
114109 ** Advance the position list iterator specified by the first two 
114110 ** arguments so that it points to the first element with a value greater
114111 ** than or equal to parameter iNext.
114112 */
114113 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
114114   char *pIter = *ppIter;
114115   if( pIter ){
114116     int iIter = *piIter;
114117
114118     while( iIter<iNext ){
114119       if( 0==(*pIter & 0xFE) ){
114120         iIter = -1;
114121         pIter = 0;
114122         break;
114123       }
114124       fts3GetDeltaPosition(&pIter, &iIter);
114125     }
114126
114127     *piIter = iIter;
114128     *ppIter = pIter;
114129   }
114130 }
114131
114132 /*
114133 ** Advance the snippet iterator to the next candidate snippet.
114134 */
114135 static int fts3SnippetNextCandidate(SnippetIter *pIter){
114136   int i;                          /* Loop counter */
114137
114138   if( pIter->iCurrent<0 ){
114139     /* The SnippetIter object has just been initialized. The first snippet
114140     ** candidate always starts at offset 0 (even if this candidate has a
114141     ** score of 0.0).
114142     */
114143     pIter->iCurrent = 0;
114144
114145     /* Advance the 'head' iterator of each phrase to the first offset that
114146     ** is greater than or equal to (iNext+nSnippet).
114147     */
114148     for(i=0; i<pIter->nPhrase; i++){
114149       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114150       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
114151     }
114152   }else{
114153     int iStart;
114154     int iEnd = 0x7FFFFFFF;
114155
114156     for(i=0; i<pIter->nPhrase; i++){
114157       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114158       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
114159         iEnd = pPhrase->iHead;
114160       }
114161     }
114162     if( iEnd==0x7FFFFFFF ){
114163       return 1;
114164     }
114165
114166     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
114167     for(i=0; i<pIter->nPhrase; i++){
114168       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114169       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
114170       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
114171     }
114172   }
114173
114174   return 0;
114175 }
114176
114177 /*
114178 ** Retrieve information about the current candidate snippet of snippet 
114179 ** iterator pIter.
114180 */
114181 static void fts3SnippetDetails(
114182   SnippetIter *pIter,             /* Snippet iterator */
114183   u64 mCovered,                   /* Bitmask of phrases already covered */
114184   int *piToken,                   /* OUT: First token of proposed snippet */
114185   int *piScore,                   /* OUT: "Score" for this snippet */
114186   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
114187   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
114188 ){
114189   int iStart = pIter->iCurrent;   /* First token of snippet */
114190   int iScore = 0;                 /* Score of this snippet */
114191   int i;                          /* Loop counter */
114192   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
114193   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
114194
114195   for(i=0; i<pIter->nPhrase; i++){
114196     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114197     if( pPhrase->pTail ){
114198       char *pCsr = pPhrase->pTail;
114199       int iCsr = pPhrase->iTail;
114200
114201       while( iCsr<(iStart+pIter->nSnippet) ){
114202         int j;
114203         u64 mPhrase = (u64)1 << i;
114204         u64 mPos = (u64)1 << (iCsr - iStart);
114205         assert( iCsr>=iStart );
114206         if( (mCover|mCovered)&mPhrase ){
114207           iScore++;
114208         }else{
114209           iScore += 1000;
114210         }
114211         mCover |= mPhrase;
114212
114213         for(j=0; j<pPhrase->nToken; j++){
114214           mHighlight |= (mPos>>j);
114215         }
114216
114217         if( 0==(*pCsr & 0x0FE) ) break;
114218         fts3GetDeltaPosition(&pCsr, &iCsr);
114219       }
114220     }
114221   }
114222
114223   /* Set the output variables before returning. */
114224   *piToken = iStart;
114225   *piScore = iScore;
114226   *pmCover = mCover;
114227   *pmHighlight = mHighlight;
114228 }
114229
114230 /*
114231 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
114232 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
114233 */
114234 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
114235   SnippetIter *p = (SnippetIter *)ctx;
114236   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
114237   char *pCsr;
114238
114239   pPhrase->nToken = pExpr->pPhrase->nToken;
114240
114241   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
114242   if( pCsr ){
114243     int iFirst = 0;
114244     pPhrase->pList = pCsr;
114245     fts3GetDeltaPosition(&pCsr, &iFirst);
114246     pPhrase->pHead = pCsr;
114247     pPhrase->pTail = pCsr;
114248     pPhrase->iHead = iFirst;
114249     pPhrase->iTail = iFirst;
114250   }else{
114251     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
114252   }
114253
114254   return SQLITE_OK;
114255 }
114256
114257 /*
114258 ** Select the fragment of text consisting of nFragment contiguous tokens 
114259 ** from column iCol that represent the "best" snippet. The best snippet
114260 ** is the snippet with the highest score, where scores are calculated
114261 ** by adding:
114262 **
114263 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
114264 **
114265 **   (b) +1000 points for the first occurence of each matchable phrase in 
114266 **       the snippet for which the corresponding mCovered bit is not set.
114267 **
114268 ** The selected snippet parameters are stored in structure *pFragment before
114269 ** returning. The score of the selected snippet is stored in *piScore
114270 ** before returning.
114271 */
114272 static int fts3BestSnippet(
114273   int nSnippet,                   /* Desired snippet length */
114274   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
114275   int iCol,                       /* Index of column to create snippet from */
114276   u64 mCovered,                   /* Mask of phrases already covered */
114277   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
114278   SnippetFragment *pFragment,     /* OUT: Best snippet found */
114279   int *piScore                    /* OUT: Score of snippet pFragment */
114280 ){
114281   int rc;                         /* Return Code */
114282   int nList;                      /* Number of phrases in expression */
114283   SnippetIter sIter;              /* Iterates through snippet candidates */
114284   int nByte;                      /* Number of bytes of space to allocate */
114285   int iBestScore = -1;            /* Best snippet score found so far */
114286   int i;                          /* Loop counter */
114287
114288   memset(&sIter, 0, sizeof(sIter));
114289
114290   /* Iterate through the phrases in the expression to count them. The same
114291   ** callback makes sure the doclists are loaded for each phrase.
114292   */
114293   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
114294   if( rc!=SQLITE_OK ){
114295     return rc;
114296   }
114297
114298   /* Now that it is known how many phrases there are, allocate and zero
114299   ** the required space using malloc().
114300   */
114301   nByte = sizeof(SnippetPhrase) * nList;
114302   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
114303   if( !sIter.aPhrase ){
114304     return SQLITE_NOMEM;
114305   }
114306   memset(sIter.aPhrase, 0, nByte);
114307
114308   /* Initialize the contents of the SnippetIter object. Then iterate through
114309   ** the set of phrases in the expression to populate the aPhrase[] array.
114310   */
114311   sIter.pCsr = pCsr;
114312   sIter.iCol = iCol;
114313   sIter.nSnippet = nSnippet;
114314   sIter.nPhrase = nList;
114315   sIter.iCurrent = -1;
114316   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
114317
114318   /* Set the *pmSeen output variable. */
114319   for(i=0; i<nList; i++){
114320     if( sIter.aPhrase[i].pHead ){
114321       *pmSeen |= (u64)1 << i;
114322     }
114323   }
114324
114325   /* Loop through all candidate snippets. Store the best snippet in 
114326   ** *pFragment. Store its associated 'score' in iBestScore.
114327   */
114328   pFragment->iCol = iCol;
114329   while( !fts3SnippetNextCandidate(&sIter) ){
114330     int iPos;
114331     int iScore;
114332     u64 mCover;
114333     u64 mHighlight;
114334     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
114335     assert( iScore>=0 );
114336     if( iScore>iBestScore ){
114337       pFragment->iPos = iPos;
114338       pFragment->hlmask = mHighlight;
114339       pFragment->covered = mCover;
114340       iBestScore = iScore;
114341     }
114342   }
114343
114344   sqlite3_free(sIter.aPhrase);
114345   *piScore = iBestScore;
114346   return SQLITE_OK;
114347 }
114348
114349
114350 /*
114351 ** Append a string to the string-buffer passed as the first argument.
114352 **
114353 ** If nAppend is negative, then the length of the string zAppend is
114354 ** determined using strlen().
114355 */
114356 static int fts3StringAppend(
114357   StrBuffer *pStr,                /* Buffer to append to */
114358   const char *zAppend,            /* Pointer to data to append to buffer */
114359   int nAppend                     /* Size of zAppend in bytes (or -1) */
114360 ){
114361   if( nAppend<0 ){
114362     nAppend = (int)strlen(zAppend);
114363   }
114364
114365   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
114366   ** to grow the buffer until so that it is big enough to accomadate the
114367   ** appended data.
114368   */
114369   if( pStr->n+nAppend+1>=pStr->nAlloc ){
114370     int nAlloc = pStr->nAlloc+nAppend+100;
114371     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
114372     if( !zNew ){
114373       return SQLITE_NOMEM;
114374     }
114375     pStr->z = zNew;
114376     pStr->nAlloc = nAlloc;
114377   }
114378
114379   /* Append the data to the string buffer. */
114380   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
114381   pStr->n += nAppend;
114382   pStr->z[pStr->n] = '\0';
114383
114384   return SQLITE_OK;
114385 }
114386
114387 /*
114388 ** The fts3BestSnippet() function often selects snippets that end with a
114389 ** query term. That is, the final term of the snippet is always a term
114390 ** that requires highlighting. For example, if 'X' is a highlighted term
114391 ** and '.' is a non-highlighted term, BestSnippet() may select:
114392 **
114393 **     ........X.....X
114394 **
114395 ** This function "shifts" the beginning of the snippet forward in the 
114396 ** document so that there are approximately the same number of 
114397 ** non-highlighted terms to the right of the final highlighted term as there
114398 ** are to the left of the first highlighted term. For example, to this:
114399 **
114400 **     ....X.....X....
114401 **
114402 ** This is done as part of extracting the snippet text, not when selecting
114403 ** the snippet. Snippet selection is done based on doclists only, so there
114404 ** is no way for fts3BestSnippet() to know whether or not the document 
114405 ** actually contains terms that follow the final highlighted term. 
114406 */
114407 static int fts3SnippetShift(
114408   Fts3Table *pTab,                /* FTS3 table snippet comes from */
114409   int nSnippet,                   /* Number of tokens desired for snippet */
114410   const char *zDoc,               /* Document text to extract snippet from */
114411   int nDoc,                       /* Size of buffer zDoc in bytes */
114412   int *piPos,                     /* IN/OUT: First token of snippet */
114413   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
114414 ){
114415   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
114416
114417   if( hlmask ){
114418     int nLeft;                    /* Tokens to the left of first highlight */
114419     int nRight;                   /* Tokens to the right of last highlight */
114420     int nDesired;                 /* Ideal number of tokens to shift forward */
114421
114422     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
114423     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
114424     nDesired = (nLeft-nRight)/2;
114425
114426     /* Ideally, the start of the snippet should be pushed forward in the
114427     ** document nDesired tokens. This block checks if there are actually
114428     ** nDesired tokens to the right of the snippet. If so, *piPos and
114429     ** *pHlMask are updated to shift the snippet nDesired tokens to the
114430     ** right. Otherwise, the snippet is shifted by the number of tokens
114431     ** available.
114432     */
114433     if( nDesired>0 ){
114434       int nShift;                 /* Number of tokens to shift snippet by */
114435       int iCurrent = 0;           /* Token counter */
114436       int rc;                     /* Return Code */
114437       sqlite3_tokenizer_module *pMod;
114438       sqlite3_tokenizer_cursor *pC;
114439       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114440
114441       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
114442       ** or more tokens in zDoc/nDoc.
114443       */
114444       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114445       if( rc!=SQLITE_OK ){
114446         return rc;
114447       }
114448       pC->pTokenizer = pTab->pTokenizer;
114449       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
114450         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
114451         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
114452       }
114453       pMod->xClose(pC);
114454       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
114455
114456       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
114457       assert( nShift<=nDesired );
114458       if( nShift>0 ){
114459         *piPos += nShift;
114460         *pHlmask = hlmask >> nShift;
114461       }
114462     }
114463   }
114464   return SQLITE_OK;
114465 }
114466
114467 /*
114468 ** Extract the snippet text for fragment pFragment from cursor pCsr and
114469 ** append it to string buffer pOut.
114470 */
114471 static int fts3SnippetText(
114472   Fts3Cursor *pCsr,               /* FTS3 Cursor */
114473   SnippetFragment *pFragment,     /* Snippet to extract */
114474   int iFragment,                  /* Fragment number */
114475   int isLast,                     /* True for final fragment in snippet */
114476   int nSnippet,                   /* Number of tokens in extracted snippet */
114477   const char *zOpen,              /* String inserted before highlighted term */
114478   const char *zClose,             /* String inserted after highlighted term */
114479   const char *zEllipsis,          /* String inserted between snippets */
114480   StrBuffer *pOut                 /* Write output here */
114481 ){
114482   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114483   int rc;                         /* Return code */
114484   const char *zDoc;               /* Document text to extract snippet from */
114485   int nDoc;                       /* Size of zDoc in bytes */
114486   int iCurrent = 0;               /* Current token number of document */
114487   int iEnd = 0;                   /* Byte offset of end of current token */
114488   int isShiftDone = 0;            /* True after snippet is shifted */
114489   int iPos = pFragment->iPos;     /* First token of snippet */
114490   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
114491   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
114492   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
114493   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
114494   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
114495   int DUMMY1;                     /* Dummy argument used with tokenizer */
114496   
114497   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
114498   if( zDoc==0 ){
114499     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
114500       return SQLITE_NOMEM;
114501     }
114502     return SQLITE_OK;
114503   }
114504   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
114505
114506   /* Open a token cursor on the document. */
114507   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114508   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114509   if( rc!=SQLITE_OK ){
114510     return rc;
114511   }
114512   pC->pTokenizer = pTab->pTokenizer;
114513
114514   while( rc==SQLITE_OK ){
114515     int iBegin;                   /* Offset in zDoc of start of token */
114516     int iFin;                     /* Offset in zDoc of end of token */
114517     int isHighlight;              /* True for highlighted terms */
114518
114519     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
114520     if( rc!=SQLITE_OK ){
114521       if( rc==SQLITE_DONE ){
114522         /* Special case - the last token of the snippet is also the last token
114523         ** of the column. Append any punctuation that occurred between the end
114524         ** of the previous token and the end of the document to the output. 
114525         ** Then break out of the loop. */
114526         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
114527       }
114528       break;
114529     }
114530     if( iCurrent<iPos ){ continue; }
114531
114532     if( !isShiftDone ){
114533       int n = nDoc - iBegin;
114534       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
114535       isShiftDone = 1;
114536
114537       /* Now that the shift has been done, check if the initial "..." are
114538       ** required. They are required if (a) this is not the first fragment,
114539       ** or (b) this fragment does not begin at position 0 of its column. 
114540       */
114541       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
114542         rc = fts3StringAppend(pOut, zEllipsis, -1);
114543       }
114544       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
114545     }
114546
114547     if( iCurrent>=(iPos+nSnippet) ){
114548       if( isLast ){
114549         rc = fts3StringAppend(pOut, zEllipsis, -1);
114550       }
114551       break;
114552     }
114553
114554     /* Set isHighlight to true if this term should be highlighted. */
114555     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
114556
114557     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
114558     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
114559     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
114560     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
114561
114562     iEnd = iFin;
114563   }
114564
114565   pMod->xClose(pC);
114566   return rc;
114567 }
114568
114569
114570 /*
114571 ** This function is used to count the entries in a column-list (a 
114572 ** delta-encoded list of term offsets within a single column of a single 
114573 ** row). When this function is called, *ppCollist should point to the
114574 ** beginning of the first varint in the column-list (the varint that
114575 ** contains the position of the first matching term in the column data).
114576 ** Before returning, *ppCollist is set to point to the first byte after
114577 ** the last varint in the column-list (either the 0x00 signifying the end
114578 ** of the position-list, or the 0x01 that precedes the column number of
114579 ** the next column in the position-list).
114580 **
114581 ** The number of elements in the column-list is returned.
114582 */
114583 static int fts3ColumnlistCount(char **ppCollist){
114584   char *pEnd = *ppCollist;
114585   char c = 0;
114586   int nEntry = 0;
114587
114588   /* A column-list is terminated by either a 0x01 or 0x00. */
114589   while( 0xFE & (*pEnd | c) ){
114590     c = *pEnd++ & 0x80;
114591     if( !c ) nEntry++;
114592   }
114593
114594   *ppCollist = pEnd;
114595   return nEntry;
114596 }
114597
114598 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
114599   char *pCsr = *pp;
114600   while( *pCsr ){
114601     int nHit;
114602     sqlite3_int64 iCol = 0;
114603     if( *pCsr==0x01 ){
114604       pCsr++;
114605       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
114606     }
114607     nHit = fts3ColumnlistCount(&pCsr);
114608     assert( nHit>0 );
114609     if( isGlobal ){
114610       aOut[iCol*3+1]++;
114611     }
114612     aOut[iCol*3] += nHit;
114613   }
114614   pCsr++;
114615   *pp = pCsr;
114616 }
114617
114618 /*
114619 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
114620 ** for a single query. The "global" stats are those elements of the matchinfo
114621 ** array that are constant for all rows returned by the current query.
114622 */
114623 static int fts3ExprGlobalMatchinfoCb(
114624   Fts3Expr *pExpr,                /* Phrase expression node */
114625   int iPhrase,                    /* Phrase number (numbered from zero) */
114626   void *pCtx                      /* Pointer to MatchInfo structure */
114627 ){
114628   MatchInfo *p = (MatchInfo *)pCtx;
114629   char *pCsr;
114630   char *pEnd;
114631   const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
114632
114633   assert( pExpr->isLoaded );
114634
114635   /* Fill in the global hit count matrix row for this phrase. */
114636   pCsr = pExpr->aDoclist;
114637   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114638   while( pCsr<pEnd ){
114639     while( *pCsr++ & 0x80 );      /* Skip past docid. */
114640     fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
114641   }
114642
114643   return SQLITE_OK;
114644 }
114645
114646 /*
114647 ** fts3ExprIterate() callback used to collect the "local" matchinfo stats
114648 ** for a single query. The "local" stats are those elements of the matchinfo
114649 ** array that are different for each row returned by the query.
114650 */
114651 static int fts3ExprLocalMatchinfoCb(
114652   Fts3Expr *pExpr,                /* Phrase expression node */
114653   int iPhrase,                    /* Phrase number */
114654   void *pCtx                      /* Pointer to MatchInfo structure */
114655 ){
114656   MatchInfo *p = (MatchInfo *)pCtx;
114657
114658   if( pExpr->aDoclist ){
114659     char *pCsr;
114660     int iStart = 2 + (iPhrase * p->nCol * 3);
114661     int i;
114662
114663     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
114664
114665     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
114666     if( pCsr ){
114667       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
114668     }
114669   }
114670
114671   return SQLITE_OK;
114672 }
114673
114674 /*
114675 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
114676 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
114677 */
114678 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
114679   MatchInfo sInfo;
114680   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114681   int rc = SQLITE_OK;
114682
114683   sInfo.pCursor = pCsr;
114684   sInfo.nCol = pTab->nColumn;
114685
114686   if( pCsr->aMatchinfo==0 ){
114687     /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
114688     ** matchinfo function has been called for this query. In this case 
114689     ** allocate the array used to accumulate the matchinfo data and
114690     ** initialize those elements that are constant for every row.
114691     */
114692     int nPhrase;                  /* Number of phrases */
114693     int nMatchinfo;               /* Number of u32 elements in match-info */
114694
114695     /* Load doclists for each phrase in the query. */
114696     rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
114697     if( rc!=SQLITE_OK ){
114698       return rc;
114699     }
114700     nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
114701     if( pTab->bHasDocsize ){
114702       nMatchinfo += 1 + 2*pTab->nColumn;
114703     }
114704
114705     sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
114706     if( !sInfo.aMatchinfo ){ 
114707       return SQLITE_NOMEM;
114708     }
114709     memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
114710
114711
114712     /* First element of match-info is the number of phrases in the query */
114713     sInfo.aMatchinfo[0] = nPhrase;
114714     sInfo.aMatchinfo[1] = sInfo.nCol;
114715     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
114716     if( pTab->bHasDocsize ){
114717       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114718       rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
114719     }
114720     pCsr->aMatchinfo = sInfo.aMatchinfo;
114721     pCsr->isMatchinfoNeeded = 1;
114722   }
114723
114724   sInfo.aMatchinfo = pCsr->aMatchinfo;
114725   if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
114726     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
114727     if( pTab->bHasDocsize ){
114728       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114729       rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
114730     }
114731     pCsr->isMatchinfoNeeded = 0;
114732   }
114733
114734   return SQLITE_OK;
114735 }
114736
114737 /*
114738 ** Implementation of snippet() function.
114739 */
114740 SQLITE_PRIVATE void sqlite3Fts3Snippet(
114741   sqlite3_context *pCtx,          /* SQLite function call context */
114742   Fts3Cursor *pCsr,               /* Cursor object */
114743   const char *zStart,             /* Snippet start text - "<b>" */
114744   const char *zEnd,               /* Snippet end text - "</b>" */
114745   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
114746   int iCol,                       /* Extract snippet from this column */
114747   int nToken                      /* Approximate number of tokens in snippet */
114748 ){
114749   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114750   int rc = SQLITE_OK;
114751   int i;
114752   StrBuffer res = {0, 0, 0};
114753
114754   /* The returned text includes up to four fragments of text extracted from
114755   ** the data in the current row. The first iteration of the for(...) loop
114756   ** below attempts to locate a single fragment of text nToken tokens in 
114757   ** size that contains at least one instance of all phrases in the query
114758   ** expression that appear in the current row. If such a fragment of text
114759   ** cannot be found, the second iteration of the loop attempts to locate
114760   ** a pair of fragments, and so on.
114761   */
114762   int nSnippet = 0;               /* Number of fragments in this snippet */
114763   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
114764   int nFToken = -1;               /* Number of tokens in each fragment */
114765
114766   if( !pCsr->pExpr ){
114767     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114768     return;
114769   }
114770
114771   for(nSnippet=1; 1; nSnippet++){
114772
114773     int iSnip;                    /* Loop counter 0..nSnippet-1 */
114774     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
114775     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
114776
114777     if( nToken>=0 ){
114778       nFToken = (nToken+nSnippet-1) / nSnippet;
114779     }else{
114780       nFToken = -1 * nToken;
114781     }
114782
114783     for(iSnip=0; iSnip<nSnippet; iSnip++){
114784       int iBestScore = -1;        /* Best score of columns checked so far */
114785       int iRead;                  /* Used to iterate through columns */
114786       SnippetFragment *pFragment = &aSnippet[iSnip];
114787
114788       memset(pFragment, 0, sizeof(*pFragment));
114789
114790       /* Loop through all columns of the table being considered for snippets.
114791       ** If the iCol argument to this function was negative, this means all
114792       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
114793       */
114794       for(iRead=0; iRead<pTab->nColumn; iRead++){
114795         SnippetFragment sF;
114796         int iS;
114797         if( iCol>=0 && iRead!=iCol ) continue;
114798
114799         /* Find the best snippet of nFToken tokens in column iRead. */
114800         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
114801         if( rc!=SQLITE_OK ){
114802           goto snippet_out;
114803         }
114804         if( iS>iBestScore ){
114805           *pFragment = sF;
114806           iBestScore = iS;
114807         }
114808       }
114809
114810       mCovered |= pFragment->covered;
114811     }
114812
114813     /* If all query phrases seen by fts3BestSnippet() are present in at least
114814     ** one of the nSnippet snippet fragments, break out of the loop.
114815     */
114816     assert( (mCovered&mSeen)==mCovered );
114817     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
114818   }
114819
114820   assert( nFToken>0 );
114821
114822   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
114823     rc = fts3SnippetText(pCsr, &aSnippet[i], 
114824         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
114825     );
114826   }
114827
114828  snippet_out:
114829   if( rc!=SQLITE_OK ){
114830     sqlite3_result_error_code(pCtx, rc);
114831     sqlite3_free(res.z);
114832   }else{
114833     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
114834   }
114835 }
114836
114837
114838 typedef struct TermOffset TermOffset;
114839 typedef struct TermOffsetCtx TermOffsetCtx;
114840
114841 struct TermOffset {
114842   char *pList;                    /* Position-list */
114843   int iPos;                       /* Position just read from pList */
114844   int iOff;                       /* Offset of this term from read positions */
114845 };
114846
114847 struct TermOffsetCtx {
114848   int iCol;                       /* Column of table to populate aTerm for */
114849   int iTerm;
114850   sqlite3_int64 iDocid;
114851   TermOffset *aTerm;
114852 };
114853
114854 /*
114855 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
114856 */
114857 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
114858   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
114859   int nTerm;                      /* Number of tokens in phrase */
114860   int iTerm;                      /* For looping through nTerm phrase terms */
114861   char *pList;                    /* Pointer to position list for phrase */
114862   int iPos = 0;                   /* First position in position-list */
114863
114864   UNUSED_PARAMETER(iPhrase);
114865   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
114866   nTerm = pExpr->pPhrase->nToken;
114867   if( pList ){
114868     fts3GetDeltaPosition(&pList, &iPos);
114869     assert( iPos>=0 );
114870   }
114871
114872   for(iTerm=0; iTerm<nTerm; iTerm++){
114873     TermOffset *pT = &p->aTerm[p->iTerm++];
114874     pT->iOff = nTerm-iTerm-1;
114875     pT->pList = pList;
114876     pT->iPos = iPos;
114877   }
114878
114879   return SQLITE_OK;
114880 }
114881
114882 /*
114883 ** Implementation of offsets() function.
114884 */
114885 SQLITE_PRIVATE void sqlite3Fts3Offsets(
114886   sqlite3_context *pCtx,          /* SQLite function call context */
114887   Fts3Cursor *pCsr                /* Cursor object */
114888 ){
114889   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114890   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
114891   const char *ZDUMMY;             /* Dummy argument used with xNext() */
114892   int NDUMMY;                     /* Dummy argument used with xNext() */
114893   int rc;                         /* Return Code */
114894   int nToken;                     /* Number of tokens in query */
114895   int iCol;                       /* Column currently being processed */
114896   StrBuffer res = {0, 0, 0};      /* Result string */
114897   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
114898
114899   if( !pCsr->pExpr ){
114900     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114901     return;
114902   }
114903
114904   memset(&sCtx, 0, sizeof(sCtx));
114905   assert( pCsr->isRequireSeek==0 );
114906
114907   /* Count the number of terms in the query */
114908   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
114909   if( rc!=SQLITE_OK ) goto offsets_out;
114910
114911   /* Allocate the array of TermOffset iterators. */
114912   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
114913   if( 0==sCtx.aTerm ){
114914     rc = SQLITE_NOMEM;
114915     goto offsets_out;
114916   }
114917   sCtx.iDocid = pCsr->iPrevId;
114918
114919   /* Loop through the table columns, appending offset information to 
114920   ** string-buffer res for each column.
114921   */
114922   for(iCol=0; iCol<pTab->nColumn; iCol++){
114923     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
114924     int iStart;
114925     int iEnd;
114926     int iCurrent;
114927     const char *zDoc;
114928     int nDoc;
114929
114930     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
114931     ** no way that this operation can fail, so the return code from
114932     ** fts3ExprIterate() can be discarded.
114933     */
114934     sCtx.iCol = iCol;
114935     sCtx.iTerm = 0;
114936     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
114937
114938     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
114939     ** in column iCol, jump immediately to the next iteration of the loop.
114940     ** If an OOM occurs while retrieving the data (this can happen if SQLite
114941     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
114942     ** to the caller. 
114943     */
114944     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
114945     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
114946     if( zDoc==0 ){
114947       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
114948         continue;
114949       }
114950       rc = SQLITE_NOMEM;
114951       goto offsets_out;
114952     }
114953
114954     /* Initialize a tokenizer iterator to iterate through column iCol. */
114955     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114956     if( rc!=SQLITE_OK ) goto offsets_out;
114957     pC->pTokenizer = pTab->pTokenizer;
114958
114959     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114960     while( rc==SQLITE_OK ){
114961       int i;                      /* Used to loop through terms */
114962       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
114963       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
114964
114965       for(i=0; i<nToken; i++){
114966         TermOffset *pT = &sCtx.aTerm[i];
114967         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
114968           iMinPos = pT->iPos-pT->iOff;
114969           pTerm = pT;
114970         }
114971       }
114972
114973       if( !pTerm ){
114974         /* All offsets for this column have been gathered. */
114975         break;
114976       }else{
114977         assert( iCurrent<=iMinPos );
114978         if( 0==(0xFE&*pTerm->pList) ){
114979           pTerm->pList = 0;
114980         }else{
114981           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
114982         }
114983         while( rc==SQLITE_OK && iCurrent<iMinPos ){
114984           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114985         }
114986         if( rc==SQLITE_OK ){
114987           char aBuffer[64];
114988           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
114989               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
114990           );
114991           rc = fts3StringAppend(&res, aBuffer, -1);
114992         }else if( rc==SQLITE_DONE ){
114993           rc = SQLITE_CORRUPT;
114994         }
114995       }
114996     }
114997     if( rc==SQLITE_DONE ){
114998       rc = SQLITE_OK;
114999     }
115000
115001     pMod->xClose(pC);
115002     if( rc!=SQLITE_OK ) goto offsets_out;
115003   }
115004
115005  offsets_out:
115006   sqlite3_free(sCtx.aTerm);
115007   assert( rc!=SQLITE_DONE );
115008   if( rc!=SQLITE_OK ){
115009     sqlite3_result_error_code(pCtx,  rc);
115010     sqlite3_free(res.z);
115011   }else{
115012     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
115013   }
115014   return;
115015 }
115016
115017 /*
115018 ** Implementation of matchinfo() function.
115019 */
115020 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
115021   int rc;
115022   if( !pCsr->pExpr ){
115023     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
115024     return;
115025   }
115026   rc = fts3GetMatchinfo(pCsr);
115027   if( rc!=SQLITE_OK ){
115028     sqlite3_result_error_code(pContext, rc);
115029   }else{
115030     Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
115031     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
115032     if( pTab->bHasDocsize ){
115033       n += sizeof(u32)*(1 + 2*pTab->nColumn);
115034     }
115035     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
115036   }
115037 }
115038
115039 #endif
115040
115041 /************** End of fts3_snippet.c ****************************************/
115042 /************** Begin file rtree.c *******************************************/
115043 /*
115044 ** 2001 September 15
115045 **
115046 ** The author disclaims copyright to this source code.  In place of
115047 ** a legal notice, here is a blessing:
115048 **
115049 **    May you do good and not evil.
115050 **    May you find forgiveness for yourself and forgive others.
115051 **    May you share freely, never taking more than you give.
115052 **
115053 *************************************************************************
115054 ** This file contains code for implementations of the r-tree and r*-tree
115055 ** algorithms packaged as an SQLite virtual table module.
115056 */
115057
115058 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
115059
115060 /*
115061 ** This file contains an implementation of a couple of different variants
115062 ** of the r-tree algorithm. See the README file for further details. The 
115063 ** same data-structure is used for all, but the algorithms for insert and
115064 ** delete operations vary. The variants used are selected at compile time 
115065 ** by defining the following symbols:
115066 */
115067
115068 /* Either, both or none of the following may be set to activate 
115069 ** r*tree variant algorithms.
115070 */
115071 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
115072 #define VARIANT_RSTARTREE_REINSERT      1
115073
115074 /* 
115075 ** Exactly one of the following must be set to 1.
115076 */
115077 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
115078 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
115079 #define VARIANT_RSTARTREE_SPLIT         1
115080
115081 #define VARIANT_GUTTMAN_SPLIT \
115082         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
115083
115084 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
115085   #define PickNext QuadraticPickNext
115086   #define PickSeeds QuadraticPickSeeds
115087   #define AssignCells splitNodeGuttman
115088 #endif
115089 #if VARIANT_GUTTMAN_LINEAR_SPLIT
115090   #define PickNext LinearPickNext
115091   #define PickSeeds LinearPickSeeds
115092   #define AssignCells splitNodeGuttman
115093 #endif
115094 #if VARIANT_RSTARTREE_SPLIT
115095   #define AssignCells splitNodeStartree
115096 #endif
115097
115098
115099 #ifndef SQLITE_CORE
115100   SQLITE_EXTENSION_INIT1
115101 #else
115102 #endif
115103
115104
115105 #ifndef SQLITE_AMALGAMATION
115106 typedef sqlite3_int64 i64;
115107 typedef unsigned char u8;
115108 typedef unsigned int u32;
115109 #endif
115110
115111 typedef struct Rtree Rtree;
115112 typedef struct RtreeCursor RtreeCursor;
115113 typedef struct RtreeNode RtreeNode;
115114 typedef struct RtreeCell RtreeCell;
115115 typedef struct RtreeConstraint RtreeConstraint;
115116 typedef union RtreeCoord RtreeCoord;
115117
115118 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
115119 #define RTREE_MAX_DIMENSIONS 5
115120
115121 /* Size of hash table Rtree.aHash. This hash table is not expected to
115122 ** ever contain very many entries, so a fixed number of buckets is 
115123 ** used.
115124 */
115125 #define HASHSIZE 128
115126
115127 /* 
115128 ** An rtree virtual-table object.
115129 */
115130 struct Rtree {
115131   sqlite3_vtab base;
115132   sqlite3 *db;                /* Host database connection */
115133   int iNodeSize;              /* Size in bytes of each node in the node table */
115134   int nDim;                   /* Number of dimensions */
115135   int nBytesPerCell;          /* Bytes consumed per cell */
115136   int iDepth;                 /* Current depth of the r-tree structure */
115137   char *zDb;                  /* Name of database containing r-tree table */
115138   char *zName;                /* Name of r-tree table */ 
115139   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
115140   int nBusy;                  /* Current number of users of this structure */
115141
115142   /* List of nodes removed during a CondenseTree operation. List is
115143   ** linked together via the pointer normally used for hash chains -
115144   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
115145   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
115146   */
115147   RtreeNode *pDeleted;
115148   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
115149
115150   /* Statements to read/write/delete a record from xxx_node */
115151   sqlite3_stmt *pReadNode;
115152   sqlite3_stmt *pWriteNode;
115153   sqlite3_stmt *pDeleteNode;
115154
115155   /* Statements to read/write/delete a record from xxx_rowid */
115156   sqlite3_stmt *pReadRowid;
115157   sqlite3_stmt *pWriteRowid;
115158   sqlite3_stmt *pDeleteRowid;
115159
115160   /* Statements to read/write/delete a record from xxx_parent */
115161   sqlite3_stmt *pReadParent;
115162   sqlite3_stmt *pWriteParent;
115163   sqlite3_stmt *pDeleteParent;
115164
115165   int eCoordType;
115166 };
115167
115168 /* Possible values for eCoordType: */
115169 #define RTREE_COORD_REAL32 0
115170 #define RTREE_COORD_INT32  1
115171
115172 /*
115173 ** The minimum number of cells allowed for a node is a third of the 
115174 ** maximum. In Gutman's notation:
115175 **
115176 **     m = M/3
115177 **
115178 ** If an R*-tree "Reinsert" operation is required, the same number of
115179 ** cells are removed from the overfull node and reinserted into the tree.
115180 */
115181 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
115182 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
115183 #define RTREE_MAXCELLS 51
115184
115185 /* 
115186 ** An rtree cursor object.
115187 */
115188 struct RtreeCursor {
115189   sqlite3_vtab_cursor base;
115190   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
115191   int iCell;                        /* Index of current cell in pNode */
115192   int iStrategy;                    /* Copy of idxNum search parameter */
115193   int nConstraint;                  /* Number of entries in aConstraint */
115194   RtreeConstraint *aConstraint;     /* Search constraints. */
115195 };
115196
115197 union RtreeCoord {
115198   float f;
115199   int i;
115200 };
115201
115202 /*
115203 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
115204 ** formatted as a double. This macro assumes that local variable pRtree points
115205 ** to the Rtree structure associated with the RtreeCoord.
115206 */
115207 #define DCOORD(coord) (                           \
115208   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
115209     ((double)coord.f) :                           \
115210     ((double)coord.i)                             \
115211 )
115212
115213 /*
115214 ** A search constraint.
115215 */
115216 struct RtreeConstraint {
115217   int iCoord;                       /* Index of constrained coordinate */
115218   int op;                           /* Constraining operation */
115219   double rValue;                    /* Constraint value. */
115220 };
115221
115222 /* Possible values for RtreeConstraint.op */
115223 #define RTREE_EQ 0x41
115224 #define RTREE_LE 0x42
115225 #define RTREE_LT 0x43
115226 #define RTREE_GE 0x44
115227 #define RTREE_GT 0x45
115228
115229 /* 
115230 ** An rtree structure node.
115231 **
115232 ** Data format (RtreeNode.zData):
115233 **
115234 **   1. If the node is the root node (node 1), then the first 2 bytes
115235 **      of the node contain the tree depth as a big-endian integer.
115236 **      For non-root nodes, the first 2 bytes are left unused.
115237 **
115238 **   2. The next 2 bytes contain the number of entries currently 
115239 **      stored in the node.
115240 **
115241 **   3. The remainder of the node contains the node entries. Each entry
115242 **      consists of a single 8-byte integer followed by an even number
115243 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
115244 **      of a record. For internal nodes it is the node number of a
115245 **      child page.
115246 */
115247 struct RtreeNode {
115248   RtreeNode *pParent;               /* Parent node */
115249   i64 iNode;
115250   int nRef;
115251   int isDirty;
115252   u8 *zData;
115253   RtreeNode *pNext;                 /* Next node in this hash chain */
115254 };
115255 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
115256
115257 /* 
115258 ** Structure to store a deserialized rtree record.
115259 */
115260 struct RtreeCell {
115261   i64 iRowid;
115262   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
115263 };
115264
115265 #ifndef MAX
115266 # define MAX(x,y) ((x) < (y) ? (y) : (x))
115267 #endif
115268 #ifndef MIN
115269 # define MIN(x,y) ((x) > (y) ? (y) : (x))
115270 #endif
115271
115272 /*
115273 ** Functions to deserialize a 16 bit integer, 32 bit real number and
115274 ** 64 bit integer. The deserialized value is returned.
115275 */
115276 static int readInt16(u8 *p){
115277   return (p[0]<<8) + p[1];
115278 }
115279 static void readCoord(u8 *p, RtreeCoord *pCoord){
115280   u32 i = (
115281     (((u32)p[0]) << 24) + 
115282     (((u32)p[1]) << 16) + 
115283     (((u32)p[2]) <<  8) + 
115284     (((u32)p[3]) <<  0)
115285   );
115286   *(u32 *)pCoord = i;
115287 }
115288 static i64 readInt64(u8 *p){
115289   return (
115290     (((i64)p[0]) << 56) + 
115291     (((i64)p[1]) << 48) + 
115292     (((i64)p[2]) << 40) + 
115293     (((i64)p[3]) << 32) + 
115294     (((i64)p[4]) << 24) + 
115295     (((i64)p[5]) << 16) + 
115296     (((i64)p[6]) <<  8) + 
115297     (((i64)p[7]) <<  0)
115298   );
115299 }
115300
115301 /*
115302 ** Functions to serialize a 16 bit integer, 32 bit real number and
115303 ** 64 bit integer. The value returned is the number of bytes written
115304 ** to the argument buffer (always 2, 4 and 8 respectively).
115305 */
115306 static int writeInt16(u8 *p, int i){
115307   p[0] = (i>> 8)&0xFF;
115308   p[1] = (i>> 0)&0xFF;
115309   return 2;
115310 }
115311 static int writeCoord(u8 *p, RtreeCoord *pCoord){
115312   u32 i;
115313   assert( sizeof(RtreeCoord)==4 );
115314   assert( sizeof(u32)==4 );
115315   i = *(u32 *)pCoord;
115316   p[0] = (i>>24)&0xFF;
115317   p[1] = (i>>16)&0xFF;
115318   p[2] = (i>> 8)&0xFF;
115319   p[3] = (i>> 0)&0xFF;
115320   return 4;
115321 }
115322 static int writeInt64(u8 *p, i64 i){
115323   p[0] = (i>>56)&0xFF;
115324   p[1] = (i>>48)&0xFF;
115325   p[2] = (i>>40)&0xFF;
115326   p[3] = (i>>32)&0xFF;
115327   p[4] = (i>>24)&0xFF;
115328   p[5] = (i>>16)&0xFF;
115329   p[6] = (i>> 8)&0xFF;
115330   p[7] = (i>> 0)&0xFF;
115331   return 8;
115332 }
115333
115334 /*
115335 ** Increment the reference count of node p.
115336 */
115337 static void nodeReference(RtreeNode *p){
115338   if( p ){
115339     p->nRef++;
115340   }
115341 }
115342
115343 /*
115344 ** Clear the content of node p (set all bytes to 0x00).
115345 */
115346 static void nodeZero(Rtree *pRtree, RtreeNode *p){
115347   if( p ){
115348     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
115349     p->isDirty = 1;
115350   }
115351 }
115352
115353 /*
115354 ** Given a node number iNode, return the corresponding key to use
115355 ** in the Rtree.aHash table.
115356 */
115357 static int nodeHash(i64 iNode){
115358   return (
115359     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
115360     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
115361   ) % HASHSIZE;
115362 }
115363
115364 /*
115365 ** Search the node hash table for node iNode. If found, return a pointer
115366 ** to it. Otherwise, return 0.
115367 */
115368 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
115369   RtreeNode *p;
115370   assert( iNode!=0 );
115371   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
115372   return p;
115373 }
115374
115375 /*
115376 ** Add node pNode to the node hash table.
115377 */
115378 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
115379   if( pNode ){
115380     int iHash;
115381     assert( pNode->pNext==0 );
115382     iHash = nodeHash(pNode->iNode);
115383     pNode->pNext = pRtree->aHash[iHash];
115384     pRtree->aHash[iHash] = pNode;
115385   }
115386 }
115387
115388 /*
115389 ** Remove node pNode from the node hash table.
115390 */
115391 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
115392   RtreeNode **pp;
115393   if( pNode->iNode!=0 ){
115394     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
115395     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
115396     *pp = pNode->pNext;
115397     pNode->pNext = 0;
115398   }
115399 }
115400
115401 /*
115402 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
115403 ** indicating that node has not yet been assigned a node number. It is
115404 ** assigned a node number when nodeWrite() is called to write the
115405 ** node contents out to the database.
115406 */
115407 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
115408   RtreeNode *pNode;
115409   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
115410   if( pNode ){
115411     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
115412     pNode->zData = (u8 *)&pNode[1];
115413     pNode->nRef = 1;
115414     pNode->pParent = pParent;
115415     pNode->isDirty = 1;
115416     nodeReference(pParent);
115417   }
115418   return pNode;
115419 }
115420
115421 /*
115422 ** Obtain a reference to an r-tree node.
115423 */
115424 static int
115425 nodeAcquire(
115426   Rtree *pRtree,             /* R-tree structure */
115427   i64 iNode,                 /* Node number to load */
115428   RtreeNode *pParent,        /* Either the parent node or NULL */
115429   RtreeNode **ppNode         /* OUT: Acquired node */
115430 ){
115431   int rc;
115432   RtreeNode *pNode;
115433
115434   /* Check if the requested node is already in the hash table. If so,
115435   ** increase its reference count and return it.
115436   */
115437   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
115438     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
115439     if( pParent && !pNode->pParent ){
115440       nodeReference(pParent);
115441       pNode->pParent = pParent;
115442     }
115443     pNode->nRef++;
115444     *ppNode = pNode;
115445     return SQLITE_OK;
115446   }
115447
115448   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
115449   if( !pNode ){
115450     *ppNode = 0;
115451     return SQLITE_NOMEM;
115452   }
115453   pNode->pParent = pParent;
115454   pNode->zData = (u8 *)&pNode[1];
115455   pNode->nRef = 1;
115456   pNode->iNode = iNode;
115457   pNode->isDirty = 0;
115458   pNode->pNext = 0;
115459
115460   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
115461   rc = sqlite3_step(pRtree->pReadNode);
115462   if( rc==SQLITE_ROW ){
115463     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
115464     assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
115465     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
115466     nodeReference(pParent);
115467   }else{
115468     sqlite3_free(pNode);
115469     pNode = 0;
115470   }
115471
115472   *ppNode = pNode;
115473   rc = sqlite3_reset(pRtree->pReadNode);
115474
115475   if( rc==SQLITE_OK && iNode==1 ){
115476     pRtree->iDepth = readInt16(pNode->zData);
115477   }
115478
115479   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
115480   nodeHashInsert(pRtree, pNode);
115481
115482   return rc;
115483 }
115484
115485 /*
115486 ** Overwrite cell iCell of node pNode with the contents of pCell.
115487 */
115488 static void nodeOverwriteCell(
115489   Rtree *pRtree, 
115490   RtreeNode *pNode,  
115491   RtreeCell *pCell, 
115492   int iCell
115493 ){
115494   int ii;
115495   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115496   p += writeInt64(p, pCell->iRowid);
115497   for(ii=0; ii<(pRtree->nDim*2); ii++){
115498     p += writeCoord(p, &pCell->aCoord[ii]);
115499   }
115500   pNode->isDirty = 1;
115501 }
115502
115503 /*
115504 ** Remove cell the cell with index iCell from node pNode.
115505 */
115506 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
115507   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115508   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
115509   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
115510   memmove(pDst, pSrc, nByte);
115511   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
115512   pNode->isDirty = 1;
115513 }
115514
115515 /*
115516 ** Insert the contents of cell pCell into node pNode. If the insert
115517 ** is successful, return SQLITE_OK.
115518 **
115519 ** If there is not enough free space in pNode, return SQLITE_FULL.
115520 */
115521 static int
115522 nodeInsertCell(
115523   Rtree *pRtree, 
115524   RtreeNode *pNode, 
115525   RtreeCell *pCell 
115526 ){
115527   int nCell;                    /* Current number of cells in pNode */
115528   int nMaxCell;                 /* Maximum number of cells for pNode */
115529
115530   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
115531   nCell = NCELL(pNode);
115532
115533   assert(nCell<=nMaxCell);
115534
115535   if( nCell<nMaxCell ){
115536     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
115537     writeInt16(&pNode->zData[2], nCell+1);
115538     pNode->isDirty = 1;
115539   }
115540
115541   return (nCell==nMaxCell);
115542 }
115543
115544 /*
115545 ** If the node is dirty, write it out to the database.
115546 */
115547 static int
115548 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
115549   int rc = SQLITE_OK;
115550   if( pNode->isDirty ){
115551     sqlite3_stmt *p = pRtree->pWriteNode;
115552     if( pNode->iNode ){
115553       sqlite3_bind_int64(p, 1, pNode->iNode);
115554     }else{
115555       sqlite3_bind_null(p, 1);
115556     }
115557     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
115558     sqlite3_step(p);
115559     pNode->isDirty = 0;
115560     rc = sqlite3_reset(p);
115561     if( pNode->iNode==0 && rc==SQLITE_OK ){
115562       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
115563       nodeHashInsert(pRtree, pNode);
115564     }
115565   }
115566   return rc;
115567 }
115568
115569 /*
115570 ** Release a reference to a node. If the node is dirty and the reference
115571 ** count drops to zero, the node data is written to the database.
115572 */
115573 static int
115574 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
115575   int rc = SQLITE_OK;
115576   if( pNode ){
115577     assert( pNode->nRef>0 );
115578     pNode->nRef--;
115579     if( pNode->nRef==0 ){
115580       if( pNode->iNode==1 ){
115581         pRtree->iDepth = -1;
115582       }
115583       if( pNode->pParent ){
115584         rc = nodeRelease(pRtree, pNode->pParent);
115585       }
115586       if( rc==SQLITE_OK ){
115587         rc = nodeWrite(pRtree, pNode);
115588       }
115589       nodeHashDelete(pRtree, pNode);
115590       sqlite3_free(pNode);
115591     }
115592   }
115593   return rc;
115594 }
115595
115596 /*
115597 ** Return the 64-bit integer value associated with cell iCell of
115598 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
115599 ** an internal node, then the 64-bit integer is a child page number.
115600 */
115601 static i64 nodeGetRowid(
115602   Rtree *pRtree, 
115603   RtreeNode *pNode, 
115604   int iCell
115605 ){
115606   assert( iCell<NCELL(pNode) );
115607   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
115608 }
115609
115610 /*
115611 ** Return coordinate iCoord from cell iCell in node pNode.
115612 */
115613 static void nodeGetCoord(
115614   Rtree *pRtree, 
115615   RtreeNode *pNode, 
115616   int iCell,
115617   int iCoord,
115618   RtreeCoord *pCoord           /* Space to write result to */
115619 ){
115620   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
115621 }
115622
115623 /*
115624 ** Deserialize cell iCell of node pNode. Populate the structure pointed
115625 ** to by pCell with the results.
115626 */
115627 static void nodeGetCell(
115628   Rtree *pRtree, 
115629   RtreeNode *pNode, 
115630   int iCell,
115631   RtreeCell *pCell
115632 ){
115633   int ii;
115634   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
115635   for(ii=0; ii<pRtree->nDim*2; ii++){
115636     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
115637   }
115638 }
115639
115640
115641 /* Forward declaration for the function that does the work of
115642 ** the virtual table module xCreate() and xConnect() methods.
115643 */
115644 static int rtreeInit(
115645   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
115646 );
115647
115648 /* 
115649 ** Rtree virtual table module xCreate method.
115650 */
115651 static int rtreeCreate(
115652   sqlite3 *db,
115653   void *pAux,
115654   int argc, const char *const*argv,
115655   sqlite3_vtab **ppVtab,
115656   char **pzErr
115657 ){
115658   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
115659 }
115660
115661 /* 
115662 ** Rtree virtual table module xConnect method.
115663 */
115664 static int rtreeConnect(
115665   sqlite3 *db,
115666   void *pAux,
115667   int argc, const char *const*argv,
115668   sqlite3_vtab **ppVtab,
115669   char **pzErr
115670 ){
115671   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
115672 }
115673
115674 /*
115675 ** Increment the r-tree reference count.
115676 */
115677 static void rtreeReference(Rtree *pRtree){
115678   pRtree->nBusy++;
115679 }
115680
115681 /*
115682 ** Decrement the r-tree reference count. When the reference count reaches
115683 ** zero the structure is deleted.
115684 */
115685 static void rtreeRelease(Rtree *pRtree){
115686   pRtree->nBusy--;
115687   if( pRtree->nBusy==0 ){
115688     sqlite3_finalize(pRtree->pReadNode);
115689     sqlite3_finalize(pRtree->pWriteNode);
115690     sqlite3_finalize(pRtree->pDeleteNode);
115691     sqlite3_finalize(pRtree->pReadRowid);
115692     sqlite3_finalize(pRtree->pWriteRowid);
115693     sqlite3_finalize(pRtree->pDeleteRowid);
115694     sqlite3_finalize(pRtree->pReadParent);
115695     sqlite3_finalize(pRtree->pWriteParent);
115696     sqlite3_finalize(pRtree->pDeleteParent);
115697     sqlite3_free(pRtree);
115698   }
115699 }
115700
115701 /* 
115702 ** Rtree virtual table module xDisconnect method.
115703 */
115704 static int rtreeDisconnect(sqlite3_vtab *pVtab){
115705   rtreeRelease((Rtree *)pVtab);
115706   return SQLITE_OK;
115707 }
115708
115709 /* 
115710 ** Rtree virtual table module xDestroy method.
115711 */
115712 static int rtreeDestroy(sqlite3_vtab *pVtab){
115713   Rtree *pRtree = (Rtree *)pVtab;
115714   int rc;
115715   char *zCreate = sqlite3_mprintf(
115716     "DROP TABLE '%q'.'%q_node';"
115717     "DROP TABLE '%q'.'%q_rowid';"
115718     "DROP TABLE '%q'.'%q_parent';",
115719     pRtree->zDb, pRtree->zName, 
115720     pRtree->zDb, pRtree->zName,
115721     pRtree->zDb, pRtree->zName
115722   );
115723   if( !zCreate ){
115724     rc = SQLITE_NOMEM;
115725   }else{
115726     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
115727     sqlite3_free(zCreate);
115728   }
115729   if( rc==SQLITE_OK ){
115730     rtreeRelease(pRtree);
115731   }
115732
115733   return rc;
115734 }
115735
115736 /* 
115737 ** Rtree virtual table module xOpen method.
115738 */
115739 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
115740   int rc = SQLITE_NOMEM;
115741   RtreeCursor *pCsr;
115742
115743   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
115744   if( pCsr ){
115745     memset(pCsr, 0, sizeof(RtreeCursor));
115746     pCsr->base.pVtab = pVTab;
115747     rc = SQLITE_OK;
115748   }
115749   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
115750
115751   return rc;
115752 }
115753
115754 /* 
115755 ** Rtree virtual table module xClose method.
115756 */
115757 static int rtreeClose(sqlite3_vtab_cursor *cur){
115758   Rtree *pRtree = (Rtree *)(cur->pVtab);
115759   int rc;
115760   RtreeCursor *pCsr = (RtreeCursor *)cur;
115761   sqlite3_free(pCsr->aConstraint);
115762   rc = nodeRelease(pRtree, pCsr->pNode);
115763   sqlite3_free(pCsr);
115764   return rc;
115765 }
115766
115767 /*
115768 ** Rtree virtual table module xEof method.
115769 **
115770 ** Return non-zero if the cursor does not currently point to a valid 
115771 ** record (i.e if the scan has finished), or zero otherwise.
115772 */
115773 static int rtreeEof(sqlite3_vtab_cursor *cur){
115774   RtreeCursor *pCsr = (RtreeCursor *)cur;
115775   return (pCsr->pNode==0);
115776 }
115777
115778 /* 
115779 ** Cursor pCursor currently points to a cell in a non-leaf page.
115780 ** Return true if the sub-tree headed by the cell is filtered
115781 ** (excluded) by the constraints in the pCursor->aConstraint[] 
115782 ** array, or false otherwise.
115783 */
115784 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
115785   RtreeCell cell;
115786   int ii;
115787   int bRes = 0;
115788
115789   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115790   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
115791     RtreeConstraint *p = &pCursor->aConstraint[ii];
115792     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
115793     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
115794
115795     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
115796         || p->op==RTREE_GT || p->op==RTREE_EQ
115797     );
115798
115799     switch( p->op ){
115800       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
115801       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
115802       case RTREE_EQ: 
115803         bRes = (p->rValue>cell_max || p->rValue<cell_min);
115804         break;
115805     }
115806   }
115807
115808   return bRes;
115809 }
115810
115811 /* 
115812 ** Return true if the cell that cursor pCursor currently points to
115813 ** would be filtered (excluded) by the constraints in the 
115814 ** pCursor->aConstraint[] array, or false otherwise.
115815 **
115816 ** This function assumes that the cell is part of a leaf node.
115817 */
115818 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
115819   RtreeCell cell;
115820   int ii;
115821
115822   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115823   for(ii=0; ii<pCursor->nConstraint; ii++){
115824     RtreeConstraint *p = &pCursor->aConstraint[ii];
115825     double coord = DCOORD(cell.aCoord[p->iCoord]);
115826     int res;
115827     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
115828         || p->op==RTREE_GT || p->op==RTREE_EQ
115829     );
115830     switch( p->op ){
115831       case RTREE_LE: res = (coord<=p->rValue); break;
115832       case RTREE_LT: res = (coord<p->rValue);  break;
115833       case RTREE_GE: res = (coord>=p->rValue); break;
115834       case RTREE_GT: res = (coord>p->rValue);  break;
115835       case RTREE_EQ: res = (coord==p->rValue); break;
115836     }
115837
115838     if( !res ) return 1;
115839   }
115840
115841   return 0;
115842 }
115843
115844 /*
115845 ** Cursor pCursor currently points at a node that heads a sub-tree of
115846 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
115847 ** to point to the left-most cell of the sub-tree that matches the 
115848 ** configured constraints.
115849 */
115850 static int descendToCell(
115851   Rtree *pRtree, 
115852   RtreeCursor *pCursor, 
115853   int iHeight,
115854   int *pEof                 /* OUT: Set to true if cannot descend */
115855 ){
115856   int isEof;
115857   int rc;
115858   int ii;
115859   RtreeNode *pChild;
115860   sqlite3_int64 iRowid;
115861
115862   RtreeNode *pSavedNode = pCursor->pNode;
115863   int iSavedCell = pCursor->iCell;
115864
115865   assert( iHeight>=0 );
115866
115867   if( iHeight==0 ){
115868     isEof = testRtreeEntry(pRtree, pCursor);
115869   }else{
115870     isEof = testRtreeCell(pRtree, pCursor);
115871   }
115872   if( isEof || iHeight==0 ){
115873     *pEof = isEof;
115874     return SQLITE_OK;
115875   }
115876
115877   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
115878   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
115879   if( rc!=SQLITE_OK ){
115880     return rc;
115881   }
115882
115883   nodeRelease(pRtree, pCursor->pNode);
115884   pCursor->pNode = pChild;
115885   isEof = 1;
115886   for(ii=0; isEof && ii<NCELL(pChild); ii++){
115887     pCursor->iCell = ii;
115888     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
115889     if( rc!=SQLITE_OK ){
115890       return rc;
115891     }
115892   }
115893
115894   if( isEof ){
115895     assert( pCursor->pNode==pChild );
115896     nodeReference(pSavedNode);
115897     nodeRelease(pRtree, pChild);
115898     pCursor->pNode = pSavedNode;
115899     pCursor->iCell = iSavedCell;
115900   }
115901
115902   *pEof = isEof;
115903   return SQLITE_OK;
115904 }
115905
115906 /*
115907 ** One of the cells in node pNode is guaranteed to have a 64-bit 
115908 ** integer value equal to iRowid. Return the index of this cell.
115909 */
115910 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
115911   int ii;
115912   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
115913     assert( ii<(NCELL(pNode)-1) );
115914   }
115915   return ii;
115916 }
115917
115918 /*
115919 ** Return the index of the cell containing a pointer to node pNode
115920 ** in its parent. If pNode is the root node, return -1.
115921 */
115922 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
115923   RtreeNode *pParent = pNode->pParent;
115924   if( pParent ){
115925     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
115926   }
115927   return -1;
115928 }
115929
115930 /* 
115931 ** Rtree virtual table module xNext method.
115932 */
115933 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
115934   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
115935   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115936   int rc = SQLITE_OK;
115937
115938   if( pCsr->iStrategy==1 ){
115939     /* This "scan" is a direct lookup by rowid. There is no next entry. */
115940     nodeRelease(pRtree, pCsr->pNode);
115941     pCsr->pNode = 0;
115942   }
115943
115944   else if( pCsr->pNode ){
115945     /* Move to the next entry that matches the configured constraints. */
115946     int iHeight = 0;
115947     while( pCsr->pNode ){
115948       RtreeNode *pNode = pCsr->pNode;
115949       int nCell = NCELL(pNode);
115950       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
115951         int isEof;
115952         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
115953         if( rc!=SQLITE_OK || !isEof ){
115954           return rc;
115955         }
115956       }
115957       pCsr->pNode = pNode->pParent;
115958       pCsr->iCell = nodeParentIndex(pRtree, pNode);
115959       nodeReference(pCsr->pNode);
115960       nodeRelease(pRtree, pNode);
115961       iHeight++;
115962     }
115963   }
115964
115965   return rc;
115966 }
115967
115968 /* 
115969 ** Rtree virtual table module xRowid method.
115970 */
115971 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
115972   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
115973   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115974
115975   assert(pCsr->pNode);
115976   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115977
115978   return SQLITE_OK;
115979 }
115980
115981 /* 
115982 ** Rtree virtual table module xColumn method.
115983 */
115984 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
115985   Rtree *pRtree = (Rtree *)cur->pVtab;
115986   RtreeCursor *pCsr = (RtreeCursor *)cur;
115987
115988   if( i==0 ){
115989     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115990     sqlite3_result_int64(ctx, iRowid);
115991   }else{
115992     RtreeCoord c;
115993     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
115994     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
115995       sqlite3_result_double(ctx, c.f);
115996     }else{
115997       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
115998       sqlite3_result_int(ctx, c.i);
115999     }
116000   }
116001
116002   return SQLITE_OK;
116003 }
116004
116005 /* 
116006 ** Use nodeAcquire() to obtain the leaf node containing the record with 
116007 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
116008 ** return SQLITE_OK. If there is no such record in the table, set
116009 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
116010 ** to zero and return an SQLite error code.
116011 */
116012 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
116013   int rc;
116014   *ppLeaf = 0;
116015   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
116016   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
116017     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
116018     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
116019     sqlite3_reset(pRtree->pReadRowid);
116020   }else{
116021     rc = sqlite3_reset(pRtree->pReadRowid);
116022   }
116023   return rc;
116024 }
116025
116026
116027 /* 
116028 ** Rtree virtual table module xFilter method.
116029 */
116030 static int rtreeFilter(
116031   sqlite3_vtab_cursor *pVtabCursor, 
116032   int idxNum, const char *idxStr,
116033   int argc, sqlite3_value **argv
116034 ){
116035   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
116036   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116037
116038   RtreeNode *pRoot = 0;
116039   int ii;
116040   int rc = SQLITE_OK;
116041
116042   rtreeReference(pRtree);
116043
116044   sqlite3_free(pCsr->aConstraint);
116045   pCsr->aConstraint = 0;
116046   pCsr->iStrategy = idxNum;
116047
116048   if( idxNum==1 ){
116049     /* Special case - lookup by rowid. */
116050     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
116051     i64 iRowid = sqlite3_value_int64(argv[0]);
116052     rc = findLeafNode(pRtree, iRowid, &pLeaf);
116053     pCsr->pNode = pLeaf; 
116054     if( pLeaf && rc==SQLITE_OK ){
116055       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
116056     }
116057   }else{
116058     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
116059     ** with the configured constraints. 
116060     */
116061     if( argc>0 ){
116062       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
116063       pCsr->nConstraint = argc;
116064       if( !pCsr->aConstraint ){
116065         rc = SQLITE_NOMEM;
116066       }else{
116067         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
116068         for(ii=0; ii<argc; ii++){
116069           RtreeConstraint *p = &pCsr->aConstraint[ii];
116070           p->op = idxStr[ii*2];
116071           p->iCoord = idxStr[ii*2+1]-'a';
116072           p->rValue = sqlite3_value_double(argv[ii]);
116073         }
116074       }
116075     }
116076   
116077     if( rc==SQLITE_OK ){
116078       pCsr->pNode = 0;
116079       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
116080     }
116081     if( rc==SQLITE_OK ){
116082       int isEof = 1;
116083       int nCell = NCELL(pRoot);
116084       pCsr->pNode = pRoot;
116085       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
116086         assert( pCsr->pNode==pRoot );
116087         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
116088         if( !isEof ){
116089           break;
116090         }
116091       }
116092       if( rc==SQLITE_OK && isEof ){
116093         assert( pCsr->pNode==pRoot );
116094         nodeRelease(pRtree, pRoot);
116095         pCsr->pNode = 0;
116096       }
116097       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
116098     }
116099   }
116100
116101   rtreeRelease(pRtree);
116102   return rc;
116103 }
116104
116105 /*
116106 ** Rtree virtual table module xBestIndex method. There are three
116107 ** table scan strategies to choose from (in order from most to 
116108 ** least desirable):
116109 **
116110 **   idxNum     idxStr        Strategy
116111 **   ------------------------------------------------
116112 **     1        Unused        Direct lookup by rowid.
116113 **     2        See below     R-tree query.
116114 **     3        Unused        Full table scan.
116115 **   ------------------------------------------------
116116 **
116117 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
116118 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
116119 ** constraint used. The first two bytes of idxStr correspond to 
116120 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
116121 ** (argvIndex==1) etc.
116122 **
116123 ** The first of each pair of bytes in idxStr identifies the constraint
116124 ** operator as follows:
116125 **
116126 **   Operator    Byte Value
116127 **   ----------------------
116128 **      =        0x41 ('A')
116129 **     <=        0x42 ('B')
116130 **      <        0x43 ('C')
116131 **     >=        0x44 ('D')
116132 **      >        0x45 ('E')
116133 **   ----------------------
116134 **
116135 ** The second of each pair of bytes identifies the coordinate column
116136 ** to which the constraint applies. The leftmost coordinate column
116137 ** is 'a', the second from the left 'b' etc.
116138 */
116139 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
116140   int rc = SQLITE_OK;
116141   int ii, cCol;
116142
116143   int iIdx = 0;
116144   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
116145   memset(zIdxStr, 0, sizeof(zIdxStr));
116146
116147   assert( pIdxInfo->idxStr==0 );
116148   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
116149     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
116150
116151     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
116152       /* We have an equality constraint on the rowid. Use strategy 1. */
116153       int jj;
116154       for(jj=0; jj<ii; jj++){
116155         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
116156         pIdxInfo->aConstraintUsage[jj].omit = 0;
116157       }
116158       pIdxInfo->idxNum = 1;
116159       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
116160       pIdxInfo->aConstraintUsage[jj].omit = 1;
116161
116162       /* This strategy involves a two rowid lookups on an B-Tree structures
116163       ** and then a linear search of an R-Tree node. This should be 
116164       ** considered almost as quick as a direct rowid lookup (for which 
116165       ** sqlite uses an internal cost of 0.0).
116166       */ 
116167       pIdxInfo->estimatedCost = 10.0;
116168       return SQLITE_OK;
116169     }
116170
116171     if( p->usable && p->iColumn>0 ){
116172       u8 op = 0;
116173       switch( p->op ){
116174         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
116175         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
116176         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
116177         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
116178         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
116179       }
116180       if( op ){
116181         /* Make sure this particular constraint has not been used before.
116182         ** If it has been used before, ignore it.
116183         **
116184         ** A <= or < can be used if there is a prior >= or >.
116185         ** A >= or > can be used if there is a prior < or <=.
116186         ** A <= or < is disqualified if there is a prior <=, <, or ==.
116187         ** A >= or > is disqualified if there is a prior >=, >, or ==.
116188         ** A == is disqualifed if there is any prior constraint.
116189         */
116190         int j, opmsk;
116191         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
116192         assert( compatible[RTREE_EQ & 7]==0 );
116193         assert( compatible[RTREE_LT & 7]==1 );
116194         assert( compatible[RTREE_LE & 7]==1 );
116195         assert( compatible[RTREE_GT & 7]==2 );
116196         assert( compatible[RTREE_GE & 7]==2 );
116197         cCol = p->iColumn - 1 + 'a';
116198         opmsk = compatible[op & 7];
116199         for(j=0; j<iIdx; j+=2){
116200           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
116201             op = 0;
116202             break;
116203           }
116204         }
116205       }
116206       if( op ){
116207         assert( iIdx<sizeof(zIdxStr)-1 );
116208         zIdxStr[iIdx++] = op;
116209         zIdxStr[iIdx++] = cCol;
116210         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
116211         pIdxInfo->aConstraintUsage[ii].omit = 1;
116212       }
116213     }
116214   }
116215
116216   pIdxInfo->idxNum = 2;
116217   pIdxInfo->needToFreeIdxStr = 1;
116218   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
116219     return SQLITE_NOMEM;
116220   }
116221   assert( iIdx>=0 );
116222   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
116223   return rc;
116224 }
116225
116226 /*
116227 ** Return the N-dimensional volumn of the cell stored in *p.
116228 */
116229 static float cellArea(Rtree *pRtree, RtreeCell *p){
116230   float area = 1.0;
116231   int ii;
116232   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116233     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
116234   }
116235   return area;
116236 }
116237
116238 /*
116239 ** Return the margin length of cell p. The margin length is the sum
116240 ** of the objects size in each dimension.
116241 */
116242 static float cellMargin(Rtree *pRtree, RtreeCell *p){
116243   float margin = 0.0;
116244   int ii;
116245   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116246     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
116247   }
116248   return margin;
116249 }
116250
116251 /*
116252 ** Store the union of cells p1 and p2 in p1.
116253 */
116254 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
116255   int ii;
116256   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
116257     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116258       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
116259       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
116260     }
116261   }else{
116262     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116263       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
116264       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
116265     }
116266   }
116267 }
116268
116269 /*
116270 ** Return true if the area covered by p2 is a subset of the area covered
116271 ** by p1. False otherwise.
116272 */
116273 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
116274   int ii;
116275   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
116276   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116277     RtreeCoord *a1 = &p1->aCoord[ii];
116278     RtreeCoord *a2 = &p2->aCoord[ii];
116279     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
116280      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
116281     ){
116282       return 0;
116283     }
116284   }
116285   return 1;
116286 }
116287
116288 /*
116289 ** Return the amount cell p would grow by if it were unioned with pCell.
116290 */
116291 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
116292   float area;
116293   RtreeCell cell;
116294   memcpy(&cell, p, sizeof(RtreeCell));
116295   area = cellArea(pRtree, &cell);
116296   cellUnion(pRtree, &cell, pCell);
116297   return (cellArea(pRtree, &cell)-area);
116298 }
116299
116300 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
116301 static float cellOverlap(
116302   Rtree *pRtree, 
116303   RtreeCell *p, 
116304   RtreeCell *aCell, 
116305   int nCell, 
116306   int iExclude
116307 ){
116308   int ii;
116309   float overlap = 0.0;
116310   for(ii=0; ii<nCell; ii++){
116311     if( ii!=iExclude ){
116312       int jj;
116313       float o = 1.0;
116314       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
116315         double x1;
116316         double x2;
116317
116318         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
116319         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
116320
116321         if( x2<x1 ){
116322           o = 0.0;
116323           break;
116324         }else{
116325           o = o * (x2-x1);
116326         }
116327       }
116328       overlap += o;
116329     }
116330   }
116331   return overlap;
116332 }
116333 #endif
116334
116335 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116336 static float cellOverlapEnlargement(
116337   Rtree *pRtree, 
116338   RtreeCell *p, 
116339   RtreeCell *pInsert, 
116340   RtreeCell *aCell, 
116341   int nCell, 
116342   int iExclude
116343 ){
116344   float before;
116345   float after;
116346   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
116347   cellUnion(pRtree, p, pInsert);
116348   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
116349   return after-before;
116350 }
116351 #endif
116352
116353
116354 /*
116355 ** This function implements the ChooseLeaf algorithm from Gutman[84].
116356 ** ChooseSubTree in r*tree terminology.
116357 */
116358 static int ChooseLeaf(
116359   Rtree *pRtree,               /* Rtree table */
116360   RtreeCell *pCell,            /* Cell to insert into rtree */
116361   int iHeight,                 /* Height of sub-tree rooted at pCell */
116362   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
116363 ){
116364   int rc;
116365   int ii;
116366   RtreeNode *pNode;
116367   rc = nodeAcquire(pRtree, 1, 0, &pNode);
116368
116369   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
116370     int iCell;
116371     sqlite3_int64 iBest;
116372
116373     float fMinGrowth;
116374     float fMinArea;
116375     float fMinOverlap;
116376
116377     int nCell = NCELL(pNode);
116378     RtreeCell cell;
116379     RtreeNode *pChild;
116380
116381     RtreeCell *aCell = 0;
116382
116383 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116384     if( ii==(pRtree->iDepth-1) ){
116385       int jj;
116386       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
116387       if( !aCell ){
116388         rc = SQLITE_NOMEM;
116389         nodeRelease(pRtree, pNode);
116390         pNode = 0;
116391         continue;
116392       }
116393       for(jj=0; jj<nCell; jj++){
116394         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
116395       }
116396     }
116397 #endif
116398
116399     /* Select the child node which will be enlarged the least if pCell
116400     ** is inserted into it. Resolve ties by choosing the entry with
116401     ** the smallest area.
116402     */
116403     for(iCell=0; iCell<nCell; iCell++){
116404       float growth;
116405       float area;
116406       float overlap = 0.0;
116407       nodeGetCell(pRtree, pNode, iCell, &cell);
116408       growth = cellGrowth(pRtree, &cell, pCell);
116409       area = cellArea(pRtree, &cell);
116410 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116411       if( ii==(pRtree->iDepth-1) ){
116412         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
116413       }
116414 #endif
116415       if( (iCell==0) 
116416        || (overlap<fMinOverlap) 
116417        || (overlap==fMinOverlap && growth<fMinGrowth)
116418        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
116419       ){
116420         fMinOverlap = overlap;
116421         fMinGrowth = growth;
116422         fMinArea = area;
116423         iBest = cell.iRowid;
116424       }
116425     }
116426
116427     sqlite3_free(aCell);
116428     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
116429     nodeRelease(pRtree, pNode);
116430     pNode = pChild;
116431   }
116432
116433   *ppLeaf = pNode;
116434   return rc;
116435 }
116436
116437 /*
116438 ** A cell with the same content as pCell has just been inserted into
116439 ** the node pNode. This function updates the bounding box cells in
116440 ** all ancestor elements.
116441 */
116442 static void AdjustTree(
116443   Rtree *pRtree,                    /* Rtree table */
116444   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
116445   RtreeCell *pCell                  /* This cell was just inserted */
116446 ){
116447   RtreeNode *p = pNode;
116448   while( p->pParent ){
116449     RtreeCell cell;
116450     RtreeNode *pParent = p->pParent;
116451     int iCell = nodeParentIndex(pRtree, p);
116452
116453     nodeGetCell(pRtree, pParent, iCell, &cell);
116454     if( !cellContains(pRtree, &cell, pCell) ){
116455       cellUnion(pRtree, &cell, pCell);
116456       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
116457     }
116458  
116459     p = pParent;
116460   }
116461 }
116462
116463 /*
116464 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
116465 */
116466 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
116467   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
116468   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
116469   sqlite3_step(pRtree->pWriteRowid);
116470   return sqlite3_reset(pRtree->pWriteRowid);
116471 }
116472
116473 /*
116474 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
116475 */
116476 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
116477   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
116478   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
116479   sqlite3_step(pRtree->pWriteParent);
116480   return sqlite3_reset(pRtree->pWriteParent);
116481 }
116482
116483 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
116484
116485 #if VARIANT_GUTTMAN_LINEAR_SPLIT
116486 /*
116487 ** Implementation of the linear variant of the PickNext() function from
116488 ** Guttman[84].
116489 */
116490 static RtreeCell *LinearPickNext(
116491   Rtree *pRtree,
116492   RtreeCell *aCell, 
116493   int nCell, 
116494   RtreeCell *pLeftBox, 
116495   RtreeCell *pRightBox,
116496   int *aiUsed
116497 ){
116498   int ii;
116499   for(ii=0; aiUsed[ii]; ii++);
116500   aiUsed[ii] = 1;
116501   return &aCell[ii];
116502 }
116503
116504 /*
116505 ** Implementation of the linear variant of the PickSeeds() function from
116506 ** Guttman[84].
116507 */
116508 static void LinearPickSeeds(
116509   Rtree *pRtree,
116510   RtreeCell *aCell, 
116511   int nCell, 
116512   int *piLeftSeed, 
116513   int *piRightSeed
116514 ){
116515   int i;
116516   int iLeftSeed = 0;
116517   int iRightSeed = 1;
116518   float maxNormalInnerWidth = 0.0;
116519
116520   /* Pick two "seed" cells from the array of cells. The algorithm used
116521   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
116522   ** indices of the two seed cells in the array are stored in local
116523   ** variables iLeftSeek and iRightSeed.
116524   */
116525   for(i=0; i<pRtree->nDim; i++){
116526     float x1 = DCOORD(aCell[0].aCoord[i*2]);
116527     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
116528     float x3 = x1;
116529     float x4 = x2;
116530     int jj;
116531
116532     int iCellLeft = 0;
116533     int iCellRight = 0;
116534
116535     for(jj=1; jj<nCell; jj++){
116536       float left = DCOORD(aCell[jj].aCoord[i*2]);
116537       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
116538
116539       if( left<x1 ) x1 = left;
116540       if( right>x4 ) x4 = right;
116541       if( left>x3 ){
116542         x3 = left;
116543         iCellRight = jj;
116544       }
116545       if( right<x2 ){
116546         x2 = right;
116547         iCellLeft = jj;
116548       }
116549     }
116550
116551     if( x4!=x1 ){
116552       float normalwidth = (x3 - x2) / (x4 - x1);
116553       if( normalwidth>maxNormalInnerWidth ){
116554         iLeftSeed = iCellLeft;
116555         iRightSeed = iCellRight;
116556       }
116557     }
116558   }
116559
116560   *piLeftSeed = iLeftSeed;
116561   *piRightSeed = iRightSeed;
116562 }
116563 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
116564
116565 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
116566 /*
116567 ** Implementation of the quadratic variant of the PickNext() function from
116568 ** Guttman[84].
116569 */
116570 static RtreeCell *QuadraticPickNext(
116571   Rtree *pRtree,
116572   RtreeCell *aCell, 
116573   int nCell, 
116574   RtreeCell *pLeftBox, 
116575   RtreeCell *pRightBox,
116576   int *aiUsed
116577 ){
116578   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
116579
116580   int iSelect = -1;
116581   float fDiff;
116582   int ii;
116583   for(ii=0; ii<nCell; ii++){
116584     if( aiUsed[ii]==0 ){
116585       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116586       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116587       float diff = FABS(right-left);
116588       if( iSelect<0 || diff>fDiff ){
116589         fDiff = diff;
116590         iSelect = ii;
116591       }
116592     }
116593   }
116594   aiUsed[iSelect] = 1;
116595   return &aCell[iSelect];
116596 }
116597
116598 /*
116599 ** Implementation of the quadratic variant of the PickSeeds() function from
116600 ** Guttman[84].
116601 */
116602 static void QuadraticPickSeeds(
116603   Rtree *pRtree,
116604   RtreeCell *aCell, 
116605   int nCell, 
116606   int *piLeftSeed, 
116607   int *piRightSeed
116608 ){
116609   int ii;
116610   int jj;
116611
116612   int iLeftSeed = 0;
116613   int iRightSeed = 1;
116614   float fWaste = 0.0;
116615
116616   for(ii=0; ii<nCell; ii++){
116617     for(jj=ii+1; jj<nCell; jj++){
116618       float right = cellArea(pRtree, &aCell[jj]);
116619       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
116620       float waste = growth - right;
116621
116622       if( waste>fWaste ){
116623         iLeftSeed = ii;
116624         iRightSeed = jj;
116625         fWaste = waste;
116626       }
116627     }
116628   }
116629
116630   *piLeftSeed = iLeftSeed;
116631   *piRightSeed = iRightSeed;
116632 }
116633 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
116634
116635 /*
116636 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
116637 ** nIdx. The aIdx array contains the set of integers from 0 to 
116638 ** (nIdx-1) in no particular order. This function sorts the values
116639 ** in aIdx according to the indexed values in aDistance. For
116640 ** example, assuming the inputs:
116641 **
116642 **   aIdx      = { 0,   1,   2,   3 }
116643 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
116644 **
116645 ** this function sets the aIdx array to contain:
116646 **
116647 **   aIdx      = { 0,   1,   2,   3 }
116648 **
116649 ** The aSpare array is used as temporary working space by the
116650 ** sorting algorithm.
116651 */
116652 static void SortByDistance(
116653   int *aIdx, 
116654   int nIdx, 
116655   float *aDistance, 
116656   int *aSpare
116657 ){
116658   if( nIdx>1 ){
116659     int iLeft = 0;
116660     int iRight = 0;
116661
116662     int nLeft = nIdx/2;
116663     int nRight = nIdx-nLeft;
116664     int *aLeft = aIdx;
116665     int *aRight = &aIdx[nLeft];
116666
116667     SortByDistance(aLeft, nLeft, aDistance, aSpare);
116668     SortByDistance(aRight, nRight, aDistance, aSpare);
116669
116670     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116671     aLeft = aSpare;
116672
116673     while( iLeft<nLeft || iRight<nRight ){
116674       if( iLeft==nLeft ){
116675         aIdx[iLeft+iRight] = aRight[iRight];
116676         iRight++;
116677       }else if( iRight==nRight ){
116678         aIdx[iLeft+iRight] = aLeft[iLeft];
116679         iLeft++;
116680       }else{
116681         float fLeft = aDistance[aLeft[iLeft]];
116682         float fRight = aDistance[aRight[iRight]];
116683         if( fLeft<fRight ){
116684           aIdx[iLeft+iRight] = aLeft[iLeft];
116685           iLeft++;
116686         }else{
116687           aIdx[iLeft+iRight] = aRight[iRight];
116688           iRight++;
116689         }
116690       }
116691     }
116692
116693 #if 0
116694     /* Check that the sort worked */
116695     {
116696       int jj;
116697       for(jj=1; jj<nIdx; jj++){
116698         float left = aDistance[aIdx[jj-1]];
116699         float right = aDistance[aIdx[jj]];
116700         assert( left<=right );
116701       }
116702     }
116703 #endif
116704   }
116705 }
116706
116707 /*
116708 ** Arguments aIdx, aCell and aSpare all point to arrays of size
116709 ** nIdx. The aIdx array contains the set of integers from 0 to 
116710 ** (nIdx-1) in no particular order. This function sorts the values
116711 ** in aIdx according to dimension iDim of the cells in aCell. The
116712 ** minimum value of dimension iDim is considered first, the
116713 ** maximum used to break ties.
116714 **
116715 ** The aSpare array is used as temporary working space by the
116716 ** sorting algorithm.
116717 */
116718 static void SortByDimension(
116719   Rtree *pRtree,
116720   int *aIdx, 
116721   int nIdx, 
116722   int iDim, 
116723   RtreeCell *aCell, 
116724   int *aSpare
116725 ){
116726   if( nIdx>1 ){
116727
116728     int iLeft = 0;
116729     int iRight = 0;
116730
116731     int nLeft = nIdx/2;
116732     int nRight = nIdx-nLeft;
116733     int *aLeft = aIdx;
116734     int *aRight = &aIdx[nLeft];
116735
116736     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
116737     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
116738
116739     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116740     aLeft = aSpare;
116741     while( iLeft<nLeft || iRight<nRight ){
116742       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
116743       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
116744       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
116745       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
116746       if( (iLeft!=nLeft) && ((iRight==nRight)
116747        || (xleft1<xright1)
116748        || (xleft1==xright1 && xleft2<xright2)
116749       )){
116750         aIdx[iLeft+iRight] = aLeft[iLeft];
116751         iLeft++;
116752       }else{
116753         aIdx[iLeft+iRight] = aRight[iRight];
116754         iRight++;
116755       }
116756     }
116757
116758 #if 0
116759     /* Check that the sort worked */
116760     {
116761       int jj;
116762       for(jj=1; jj<nIdx; jj++){
116763         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
116764         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
116765         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
116766         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
116767         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
116768       }
116769     }
116770 #endif
116771   }
116772 }
116773
116774 #if VARIANT_RSTARTREE_SPLIT
116775 /*
116776 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
116777 */
116778 static int splitNodeStartree(
116779   Rtree *pRtree,
116780   RtreeCell *aCell,
116781   int nCell,
116782   RtreeNode *pLeft,
116783   RtreeNode *pRight,
116784   RtreeCell *pBboxLeft,
116785   RtreeCell *pBboxRight
116786 ){
116787   int **aaSorted;
116788   int *aSpare;
116789   int ii;
116790
116791   int iBestDim;
116792   int iBestSplit;
116793   float fBestMargin;
116794
116795   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
116796
116797   aaSorted = (int **)sqlite3_malloc(nByte);
116798   if( !aaSorted ){
116799     return SQLITE_NOMEM;
116800   }
116801
116802   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
116803   memset(aaSorted, 0, nByte);
116804   for(ii=0; ii<pRtree->nDim; ii++){
116805     int jj;
116806     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
116807     for(jj=0; jj<nCell; jj++){
116808       aaSorted[ii][jj] = jj;
116809     }
116810     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
116811   }
116812
116813   for(ii=0; ii<pRtree->nDim; ii++){
116814     float margin = 0.0;
116815     float fBestOverlap;
116816     float fBestArea;
116817     int iBestLeft;
116818     int nLeft;
116819
116820     for(
116821       nLeft=RTREE_MINCELLS(pRtree); 
116822       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
116823       nLeft++
116824     ){
116825       RtreeCell left;
116826       RtreeCell right;
116827       int kk;
116828       float overlap;
116829       float area;
116830
116831       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
116832       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
116833       for(kk=1; kk<(nCell-1); kk++){
116834         if( kk<nLeft ){
116835           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
116836         }else{
116837           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
116838         }
116839       }
116840       margin += cellMargin(pRtree, &left);
116841       margin += cellMargin(pRtree, &right);
116842       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
116843       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
116844       if( (nLeft==RTREE_MINCELLS(pRtree))
116845        || (overlap<fBestOverlap)
116846        || (overlap==fBestOverlap && area<fBestArea)
116847       ){
116848         iBestLeft = nLeft;
116849         fBestOverlap = overlap;
116850         fBestArea = area;
116851       }
116852     }
116853
116854     if( ii==0 || margin<fBestMargin ){
116855       iBestDim = ii;
116856       fBestMargin = margin;
116857       iBestSplit = iBestLeft;
116858     }
116859   }
116860
116861   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
116862   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
116863   for(ii=0; ii<nCell; ii++){
116864     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
116865     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
116866     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
116867     nodeInsertCell(pRtree, pTarget, pCell);
116868     cellUnion(pRtree, pBbox, pCell);
116869   }
116870
116871   sqlite3_free(aaSorted);
116872   return SQLITE_OK;
116873 }
116874 #endif
116875
116876 #if VARIANT_GUTTMAN_SPLIT
116877 /*
116878 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
116879 */
116880 static int splitNodeGuttman(
116881   Rtree *pRtree,
116882   RtreeCell *aCell,
116883   int nCell,
116884   RtreeNode *pLeft,
116885   RtreeNode *pRight,
116886   RtreeCell *pBboxLeft,
116887   RtreeCell *pBboxRight
116888 ){
116889   int iLeftSeed = 0;
116890   int iRightSeed = 1;
116891   int *aiUsed;
116892   int i;
116893
116894   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
116895   if( !aiUsed ){
116896     return SQLITE_NOMEM;
116897   }
116898   memset(aiUsed, 0, sizeof(int)*nCell);
116899
116900   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
116901
116902   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
116903   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
116904   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
116905   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
116906   aiUsed[iLeftSeed] = 1;
116907   aiUsed[iRightSeed] = 1;
116908
116909   for(i=nCell-2; i>0; i--){
116910     RtreeCell *pNext;
116911     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
116912     float diff =  
116913       cellGrowth(pRtree, pBboxLeft, pNext) - 
116914       cellGrowth(pRtree, pBboxRight, pNext)
116915     ;
116916     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
116917      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
116918     ){
116919       nodeInsertCell(pRtree, pRight, pNext);
116920       cellUnion(pRtree, pBboxRight, pNext);
116921     }else{
116922       nodeInsertCell(pRtree, pLeft, pNext);
116923       cellUnion(pRtree, pBboxLeft, pNext);
116924     }
116925   }
116926
116927   sqlite3_free(aiUsed);
116928   return SQLITE_OK;
116929 }
116930 #endif
116931
116932 static int updateMapping(
116933   Rtree *pRtree, 
116934   i64 iRowid, 
116935   RtreeNode *pNode, 
116936   int iHeight
116937 ){
116938   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
116939   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
116940   if( iHeight>0 ){
116941     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
116942     if( pChild ){
116943       nodeRelease(pRtree, pChild->pParent);
116944       nodeReference(pNode);
116945       pChild->pParent = pNode;
116946     }
116947   }
116948   return xSetMapping(pRtree, iRowid, pNode->iNode);
116949 }
116950
116951 static int SplitNode(
116952   Rtree *pRtree,
116953   RtreeNode *pNode,
116954   RtreeCell *pCell,
116955   int iHeight
116956 ){
116957   int i;
116958   int newCellIsRight = 0;
116959
116960   int rc = SQLITE_OK;
116961   int nCell = NCELL(pNode);
116962   RtreeCell *aCell;
116963   int *aiUsed;
116964
116965   RtreeNode *pLeft = 0;
116966   RtreeNode *pRight = 0;
116967
116968   RtreeCell leftbbox;
116969   RtreeCell rightbbox;
116970
116971   /* Allocate an array and populate it with a copy of pCell and 
116972   ** all cells from node pLeft. Then zero the original node.
116973   */
116974   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
116975   if( !aCell ){
116976     rc = SQLITE_NOMEM;
116977     goto splitnode_out;
116978   }
116979   aiUsed = (int *)&aCell[nCell+1];
116980   memset(aiUsed, 0, sizeof(int)*(nCell+1));
116981   for(i=0; i<nCell; i++){
116982     nodeGetCell(pRtree, pNode, i, &aCell[i]);
116983   }
116984   nodeZero(pRtree, pNode);
116985   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
116986   nCell++;
116987
116988   if( pNode->iNode==1 ){
116989     pRight = nodeNew(pRtree, pNode, 1);
116990     pLeft = nodeNew(pRtree, pNode, 1);
116991     pRtree->iDepth++;
116992     pNode->isDirty = 1;
116993     writeInt16(pNode->zData, pRtree->iDepth);
116994   }else{
116995     pLeft = pNode;
116996     pRight = nodeNew(pRtree, pLeft->pParent, 1);
116997     nodeReference(pLeft);
116998   }
116999
117000   if( !pLeft || !pRight ){
117001     rc = SQLITE_NOMEM;
117002     goto splitnode_out;
117003   }
117004
117005   memset(pLeft->zData, 0, pRtree->iNodeSize);
117006   memset(pRight->zData, 0, pRtree->iNodeSize);
117007
117008   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
117009   if( rc!=SQLITE_OK ){
117010     goto splitnode_out;
117011   }
117012
117013   /* Ensure both child nodes have node numbers assigned to them. */
117014   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
117015    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
117016   ){
117017     goto splitnode_out;
117018   }
117019
117020   rightbbox.iRowid = pRight->iNode;
117021   leftbbox.iRowid = pLeft->iNode;
117022
117023   if( pNode->iNode==1 ){
117024     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
117025     if( rc!=SQLITE_OK ){
117026       goto splitnode_out;
117027     }
117028   }else{
117029     RtreeNode *pParent = pLeft->pParent;
117030     int iCell = nodeParentIndex(pRtree, pLeft);
117031     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
117032     AdjustTree(pRtree, pParent, &leftbbox);
117033   }
117034   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
117035     goto splitnode_out;
117036   }
117037
117038   for(i=0; i<NCELL(pRight); i++){
117039     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
117040     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
117041     if( iRowid==pCell->iRowid ){
117042       newCellIsRight = 1;
117043     }
117044     if( rc!=SQLITE_OK ){
117045       goto splitnode_out;
117046     }
117047   }
117048   if( pNode->iNode==1 ){
117049     for(i=0; i<NCELL(pLeft); i++){
117050       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
117051       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
117052       if( rc!=SQLITE_OK ){
117053         goto splitnode_out;
117054       }
117055     }
117056   }else if( newCellIsRight==0 ){
117057     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
117058   }
117059
117060   if( rc==SQLITE_OK ){
117061     rc = nodeRelease(pRtree, pRight);
117062     pRight = 0;
117063   }
117064   if( rc==SQLITE_OK ){
117065     rc = nodeRelease(pRtree, pLeft);
117066     pLeft = 0;
117067   }
117068
117069 splitnode_out:
117070   nodeRelease(pRtree, pRight);
117071   nodeRelease(pRtree, pLeft);
117072   sqlite3_free(aCell);
117073   return rc;
117074 }
117075
117076 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
117077   int rc = SQLITE_OK;
117078   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
117079     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
117080     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
117081       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
117082       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
117083     }else{
117084       rc = SQLITE_ERROR;
117085     }
117086     sqlite3_reset(pRtree->pReadParent);
117087     if( rc==SQLITE_OK ){
117088       rc = fixLeafParent(pRtree, pLeaf->pParent);
117089     }
117090   }
117091   return rc;
117092 }
117093
117094 static int deleteCell(Rtree *, RtreeNode *, int, int);
117095
117096 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
117097   int rc;
117098   RtreeNode *pParent;
117099   int iCell;
117100
117101   assert( pNode->nRef==1 );
117102
117103   /* Remove the entry in the parent cell. */
117104   iCell = nodeParentIndex(pRtree, pNode);
117105   pParent = pNode->pParent;
117106   pNode->pParent = 0;
117107   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
117108    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
117109   ){
117110     return rc;
117111   }
117112
117113   /* Remove the xxx_node entry. */
117114   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
117115   sqlite3_step(pRtree->pDeleteNode);
117116   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
117117     return rc;
117118   }
117119
117120   /* Remove the xxx_parent entry. */
117121   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
117122   sqlite3_step(pRtree->pDeleteParent);
117123   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
117124     return rc;
117125   }
117126   
117127   /* Remove the node from the in-memory hash table and link it into
117128   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
117129   */
117130   nodeHashDelete(pRtree, pNode);
117131   pNode->iNode = iHeight;
117132   pNode->pNext = pRtree->pDeleted;
117133   pNode->nRef++;
117134   pRtree->pDeleted = pNode;
117135
117136   return SQLITE_OK;
117137 }
117138
117139 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
117140   RtreeNode *pParent = pNode->pParent;
117141   if( pParent ){
117142     int ii; 
117143     int nCell = NCELL(pNode);
117144     RtreeCell box;                            /* Bounding box for pNode */
117145     nodeGetCell(pRtree, pNode, 0, &box);
117146     for(ii=1; ii<nCell; ii++){
117147       RtreeCell cell;
117148       nodeGetCell(pRtree, pNode, ii, &cell);
117149       cellUnion(pRtree, &box, &cell);
117150     }
117151     box.iRowid = pNode->iNode;
117152     ii = nodeParentIndex(pRtree, pNode);
117153     nodeOverwriteCell(pRtree, pParent, &box, ii);
117154     fixBoundingBox(pRtree, pParent);
117155   }
117156 }
117157
117158 /*
117159 ** Delete the cell at index iCell of node pNode. After removing the
117160 ** cell, adjust the r-tree data structure if required.
117161 */
117162 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
117163   int rc;
117164
117165   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
117166     return rc;
117167   }
117168
117169   /* Remove the cell from the node. This call just moves bytes around
117170   ** the in-memory node image, so it cannot fail.
117171   */
117172   nodeDeleteCell(pRtree, pNode, iCell);
117173
117174   /* If the node is not the tree root and now has less than the minimum
117175   ** number of cells, remove it from the tree. Otherwise, update the
117176   ** cell in the parent node so that it tightly contains the updated
117177   ** node.
117178   */
117179   if( pNode->iNode!=1 ){
117180     RtreeNode *pParent = pNode->pParent;
117181     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
117182      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
117183     ){
117184       rc = removeNode(pRtree, pNode, iHeight);
117185     }else{
117186       fixBoundingBox(pRtree, pNode);
117187     }
117188   }
117189
117190   return rc;
117191 }
117192
117193 static int Reinsert(
117194   Rtree *pRtree, 
117195   RtreeNode *pNode, 
117196   RtreeCell *pCell, 
117197   int iHeight
117198 ){
117199   int *aOrder;
117200   int *aSpare;
117201   RtreeCell *aCell;
117202   float *aDistance;
117203   int nCell;
117204   float aCenterCoord[RTREE_MAX_DIMENSIONS];
117205   int iDim;
117206   int ii;
117207   int rc = SQLITE_OK;
117208
117209   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
117210
117211   nCell = NCELL(pNode)+1;
117212
117213   /* Allocate the buffers used by this operation. The allocation is
117214   ** relinquished before this function returns.
117215   */
117216   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
117217     sizeof(RtreeCell) +         /* aCell array */
117218     sizeof(int)       +         /* aOrder array */
117219     sizeof(int)       +         /* aSpare array */
117220     sizeof(float)               /* aDistance array */
117221   ));
117222   if( !aCell ){
117223     return SQLITE_NOMEM;
117224   }
117225   aOrder    = (int *)&aCell[nCell];
117226   aSpare    = (int *)&aOrder[nCell];
117227   aDistance = (float *)&aSpare[nCell];
117228
117229   for(ii=0; ii<nCell; ii++){
117230     if( ii==(nCell-1) ){
117231       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
117232     }else{
117233       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
117234     }
117235     aOrder[ii] = ii;
117236     for(iDim=0; iDim<pRtree->nDim; iDim++){
117237       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
117238       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
117239     }
117240   }
117241   for(iDim=0; iDim<pRtree->nDim; iDim++){
117242     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
117243   }
117244
117245   for(ii=0; ii<nCell; ii++){
117246     aDistance[ii] = 0.0;
117247     for(iDim=0; iDim<pRtree->nDim; iDim++){
117248       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
117249           DCOORD(aCell[ii].aCoord[iDim*2]);
117250       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
117251     }
117252   }
117253
117254   SortByDistance(aOrder, nCell, aDistance, aSpare);
117255   nodeZero(pRtree, pNode);
117256
117257   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
117258     RtreeCell *p = &aCell[aOrder[ii]];
117259     nodeInsertCell(pRtree, pNode, p);
117260     if( p->iRowid==pCell->iRowid ){
117261       if( iHeight==0 ){
117262         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
117263       }else{
117264         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
117265       }
117266     }
117267   }
117268   if( rc==SQLITE_OK ){
117269     fixBoundingBox(pRtree, pNode);
117270   }
117271   for(; rc==SQLITE_OK && ii<nCell; ii++){
117272     /* Find a node to store this cell in. pNode->iNode currently contains
117273     ** the height of the sub-tree headed by the cell.
117274     */
117275     RtreeNode *pInsert;
117276     RtreeCell *p = &aCell[aOrder[ii]];
117277     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
117278     if( rc==SQLITE_OK ){
117279       int rc2;
117280       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
117281       rc2 = nodeRelease(pRtree, pInsert);
117282       if( rc==SQLITE_OK ){
117283         rc = rc2;
117284       }
117285     }
117286   }
117287
117288   sqlite3_free(aCell);
117289   return rc;
117290 }
117291
117292 /*
117293 ** Insert cell pCell into node pNode. Node pNode is the head of a 
117294 ** subtree iHeight high (leaf nodes have iHeight==0).
117295 */
117296 static int rtreeInsertCell(
117297   Rtree *pRtree,
117298   RtreeNode *pNode,
117299   RtreeCell *pCell,
117300   int iHeight
117301 ){
117302   int rc = SQLITE_OK;
117303   if( iHeight>0 ){
117304     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
117305     if( pChild ){
117306       nodeRelease(pRtree, pChild->pParent);
117307       nodeReference(pNode);
117308       pChild->pParent = pNode;
117309     }
117310   }
117311   if( nodeInsertCell(pRtree, pNode, pCell) ){
117312 #if VARIANT_RSTARTREE_REINSERT
117313     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
117314       rc = SplitNode(pRtree, pNode, pCell, iHeight);
117315     }else{
117316       pRtree->iReinsertHeight = iHeight;
117317       rc = Reinsert(pRtree, pNode, pCell, iHeight);
117318     }
117319 #else
117320     rc = SplitNode(pRtree, pNode, pCell, iHeight);
117321 #endif
117322   }else{
117323     AdjustTree(pRtree, pNode, pCell);
117324     if( iHeight==0 ){
117325       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
117326     }else{
117327       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
117328     }
117329   }
117330   return rc;
117331 }
117332
117333 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
117334   int ii;
117335   int rc = SQLITE_OK;
117336   int nCell = NCELL(pNode);
117337
117338   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
117339     RtreeNode *pInsert;
117340     RtreeCell cell;
117341     nodeGetCell(pRtree, pNode, ii, &cell);
117342
117343     /* Find a node to store this cell in. pNode->iNode currently contains
117344     ** the height of the sub-tree headed by the cell.
117345     */
117346     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
117347     if( rc==SQLITE_OK ){
117348       int rc2;
117349       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
117350       rc2 = nodeRelease(pRtree, pInsert);
117351       if( rc==SQLITE_OK ){
117352         rc = rc2;
117353       }
117354     }
117355   }
117356   return rc;
117357 }
117358
117359 /*
117360 ** Select a currently unused rowid for a new r-tree record.
117361 */
117362 static int newRowid(Rtree *pRtree, i64 *piRowid){
117363   int rc;
117364   sqlite3_bind_null(pRtree->pWriteRowid, 1);
117365   sqlite3_bind_null(pRtree->pWriteRowid, 2);
117366   sqlite3_step(pRtree->pWriteRowid);
117367   rc = sqlite3_reset(pRtree->pWriteRowid);
117368   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
117369   return rc;
117370 }
117371
117372 #ifndef NDEBUG
117373 static int hashIsEmpty(Rtree *pRtree){
117374   int ii;
117375   for(ii=0; ii<HASHSIZE; ii++){
117376     assert( !pRtree->aHash[ii] );
117377   }
117378   return 1;
117379 }
117380 #endif
117381
117382 /*
117383 ** The xUpdate method for rtree module virtual tables.
117384 */
117385 static int rtreeUpdate(
117386   sqlite3_vtab *pVtab, 
117387   int nData, 
117388   sqlite3_value **azData, 
117389   sqlite_int64 *pRowid
117390 ){
117391   Rtree *pRtree = (Rtree *)pVtab;
117392   int rc = SQLITE_OK;
117393
117394   rtreeReference(pRtree);
117395
117396   assert(nData>=1);
117397   assert(hashIsEmpty(pRtree));
117398
117399   /* If azData[0] is not an SQL NULL value, it is the rowid of a
117400   ** record to delete from the r-tree table. The following block does
117401   ** just that.
117402   */
117403   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
117404     i64 iDelete;                /* The rowid to delete */
117405     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
117406     int iCell;                  /* Index of iDelete cell in pLeaf */
117407     RtreeNode *pRoot;
117408
117409     /* Obtain a reference to the root node to initialise Rtree.iDepth */
117410     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
117411
117412     /* Obtain a reference to the leaf node that contains the entry 
117413     ** about to be deleted. 
117414     */
117415     if( rc==SQLITE_OK ){
117416       iDelete = sqlite3_value_int64(azData[0]);
117417       rc = findLeafNode(pRtree, iDelete, &pLeaf);
117418     }
117419
117420     /* Delete the cell in question from the leaf node. */
117421     if( rc==SQLITE_OK ){
117422       int rc2;
117423       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
117424       rc = deleteCell(pRtree, pLeaf, iCell, 0);
117425       rc2 = nodeRelease(pRtree, pLeaf);
117426       if( rc==SQLITE_OK ){
117427         rc = rc2;
117428       }
117429     }
117430
117431     /* Delete the corresponding entry in the <rtree>_rowid table. */
117432     if( rc==SQLITE_OK ){
117433       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
117434       sqlite3_step(pRtree->pDeleteRowid);
117435       rc = sqlite3_reset(pRtree->pDeleteRowid);
117436     }
117437
117438     /* Check if the root node now has exactly one child. If so, remove
117439     ** it, schedule the contents of the child for reinsertion and 
117440     ** reduce the tree height by one.
117441     **
117442     ** This is equivalent to copying the contents of the child into
117443     ** the root node (the operation that Gutman's paper says to perform 
117444     ** in this scenario).
117445     */
117446     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
117447       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
117448         RtreeNode *pChild;
117449         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
117450         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
117451         if( rc==SQLITE_OK ){
117452           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
117453         }
117454         if( rc==SQLITE_OK ){
117455           pRtree->iDepth--;
117456           writeInt16(pRoot->zData, pRtree->iDepth);
117457           pRoot->isDirty = 1;
117458         }
117459       }
117460     }
117461
117462     /* Re-insert the contents of any underfull nodes removed from the tree. */
117463     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
117464       if( rc==SQLITE_OK ){
117465         rc = reinsertNodeContent(pRtree, pLeaf);
117466       }
117467       pRtree->pDeleted = pLeaf->pNext;
117468       sqlite3_free(pLeaf);
117469     }
117470
117471     /* Release the reference to the root node. */
117472     if( rc==SQLITE_OK ){
117473       rc = nodeRelease(pRtree, pRoot);
117474     }else{
117475       nodeRelease(pRtree, pRoot);
117476     }
117477   }
117478
117479   /* If the azData[] array contains more than one element, elements
117480   ** (azData[2]..azData[argc-1]) contain a new record to insert into
117481   ** the r-tree structure.
117482   */
117483   if( rc==SQLITE_OK && nData>1 ){
117484     /* Insert a new record into the r-tree */
117485     RtreeCell cell;
117486     int ii;
117487     RtreeNode *pLeaf;
117488
117489     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
117490     assert( nData==(pRtree->nDim*2 + 3) );
117491     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
117492       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117493         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
117494         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
117495         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
117496           rc = SQLITE_CONSTRAINT;
117497           goto constraint;
117498         }
117499       }
117500     }else{
117501       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117502         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
117503         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
117504         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
117505           rc = SQLITE_CONSTRAINT;
117506           goto constraint;
117507         }
117508       }
117509     }
117510
117511     /* Figure out the rowid of the new row. */
117512     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
117513       rc = newRowid(pRtree, &cell.iRowid);
117514     }else{
117515       cell.iRowid = sqlite3_value_int64(azData[2]);
117516       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
117517       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
117518         sqlite3_reset(pRtree->pReadRowid);
117519         rc = SQLITE_CONSTRAINT;
117520         goto constraint;
117521       }
117522       rc = sqlite3_reset(pRtree->pReadRowid);
117523     }
117524     *pRowid = cell.iRowid;
117525
117526     if( rc==SQLITE_OK ){
117527       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
117528     }
117529     if( rc==SQLITE_OK ){
117530       int rc2;
117531       pRtree->iReinsertHeight = -1;
117532       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
117533       rc2 = nodeRelease(pRtree, pLeaf);
117534       if( rc==SQLITE_OK ){
117535         rc = rc2;
117536       }
117537     }
117538   }
117539
117540 constraint:
117541   rtreeRelease(pRtree);
117542   return rc;
117543 }
117544
117545 /*
117546 ** The xRename method for rtree module virtual tables.
117547 */
117548 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
117549   Rtree *pRtree = (Rtree *)pVtab;
117550   int rc = SQLITE_NOMEM;
117551   char *zSql = sqlite3_mprintf(
117552     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
117553     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
117554     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
117555     , pRtree->zDb, pRtree->zName, zNewName 
117556     , pRtree->zDb, pRtree->zName, zNewName 
117557     , pRtree->zDb, pRtree->zName, zNewName
117558   );
117559   if( zSql ){
117560     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
117561     sqlite3_free(zSql);
117562   }
117563   return rc;
117564 }
117565
117566 static sqlite3_module rtreeModule = {
117567   0,                         /* iVersion */
117568   rtreeCreate,                /* xCreate - create a table */
117569   rtreeConnect,               /* xConnect - connect to an existing table */
117570   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
117571   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
117572   rtreeDestroy,               /* xDestroy - Drop a table */
117573   rtreeOpen,                  /* xOpen - open a cursor */
117574   rtreeClose,                 /* xClose - close a cursor */
117575   rtreeFilter,                /* xFilter - configure scan constraints */
117576   rtreeNext,                  /* xNext - advance a cursor */
117577   rtreeEof,                   /* xEof */
117578   rtreeColumn,                /* xColumn - read data */
117579   rtreeRowid,                 /* xRowid - read data */
117580   rtreeUpdate,                /* xUpdate - write data */
117581   0,                          /* xBegin - begin transaction */
117582   0,                          /* xSync - sync transaction */
117583   0,                          /* xCommit - commit transaction */
117584   0,                          /* xRollback - rollback transaction */
117585   0,                          /* xFindFunction - function overloading */
117586   rtreeRename                 /* xRename - rename the table */
117587 };
117588
117589 static int rtreeSqlInit(
117590   Rtree *pRtree, 
117591   sqlite3 *db, 
117592   const char *zDb, 
117593   const char *zPrefix, 
117594   int isCreate
117595 ){
117596   int rc = SQLITE_OK;
117597
117598   #define N_STATEMENT 9
117599   static const char *azSql[N_STATEMENT] = {
117600     /* Read and write the xxx_node table */
117601     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
117602     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
117603     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
117604
117605     /* Read and write the xxx_rowid table */
117606     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
117607     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
117608     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
117609
117610     /* Read and write the xxx_parent table */
117611     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
117612     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
117613     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
117614   };
117615   sqlite3_stmt **appStmt[N_STATEMENT];
117616   int i;
117617
117618   pRtree->db = db;
117619
117620   if( isCreate ){
117621     char *zCreate = sqlite3_mprintf(
117622 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
117623 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
117624 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
117625 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
117626       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
117627     );
117628     if( !zCreate ){
117629       return SQLITE_NOMEM;
117630     }
117631     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
117632     sqlite3_free(zCreate);
117633     if( rc!=SQLITE_OK ){
117634       return rc;
117635     }
117636   }
117637
117638   appStmt[0] = &pRtree->pReadNode;
117639   appStmt[1] = &pRtree->pWriteNode;
117640   appStmt[2] = &pRtree->pDeleteNode;
117641   appStmt[3] = &pRtree->pReadRowid;
117642   appStmt[4] = &pRtree->pWriteRowid;
117643   appStmt[5] = &pRtree->pDeleteRowid;
117644   appStmt[6] = &pRtree->pReadParent;
117645   appStmt[7] = &pRtree->pWriteParent;
117646   appStmt[8] = &pRtree->pDeleteParent;
117647
117648   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
117649     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
117650     if( zSql ){
117651       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
117652     }else{
117653       rc = SQLITE_NOMEM;
117654     }
117655     sqlite3_free(zSql);
117656   }
117657
117658   return rc;
117659 }
117660
117661 /*
117662 ** The second argument to this function contains the text of an SQL statement
117663 ** that returns a single integer value. The statement is compiled and executed
117664 ** using database connection db. If successful, the integer value returned
117665 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
117666 ** code is returned and the value of *piVal after returning is not defined.
117667 */
117668 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
117669   int rc = SQLITE_NOMEM;
117670   if( zSql ){
117671     sqlite3_stmt *pStmt = 0;
117672     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117673     if( rc==SQLITE_OK ){
117674       if( SQLITE_ROW==sqlite3_step(pStmt) ){
117675         *piVal = sqlite3_column_int(pStmt, 0);
117676       }
117677       rc = sqlite3_finalize(pStmt);
117678     }
117679   }
117680   return rc;
117681 }
117682
117683 /*
117684 ** This function is called from within the xConnect() or xCreate() method to
117685 ** determine the node-size used by the rtree table being created or connected
117686 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
117687 ** Otherwise, an SQLite error code is returned.
117688 **
117689 ** If this function is being called as part of an xConnect(), then the rtree
117690 ** table already exists. In this case the node-size is determined by inspecting
117691 ** the root node of the tree.
117692 **
117693 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
117694 ** This ensures that each node is stored on a single database page. If the 
117695 ** database page-size is so large that more than RTREE_MAXCELLS entries 
117696 ** would fit in a single node, use a smaller node-size.
117697 */
117698 static int getNodeSize(
117699   sqlite3 *db,                    /* Database handle */
117700   Rtree *pRtree,                  /* Rtree handle */
117701   int isCreate                    /* True for xCreate, false for xConnect */
117702 ){
117703   int rc;
117704   char *zSql;
117705   if( isCreate ){
117706     int iPageSize;
117707     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
117708     rc = getIntFromStmt(db, zSql, &iPageSize);
117709     if( rc==SQLITE_OK ){
117710       pRtree->iNodeSize = iPageSize-64;
117711       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
117712         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
117713       }
117714     }
117715   }else{
117716     zSql = sqlite3_mprintf(
117717         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
117718         pRtree->zDb, pRtree->zName
117719     );
117720     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
117721   }
117722
117723   sqlite3_free(zSql);
117724   return rc;
117725 }
117726
117727 /* 
117728 ** This function is the implementation of both the xConnect and xCreate
117729 ** methods of the r-tree virtual table.
117730 **
117731 **   argv[0]   -> module name
117732 **   argv[1]   -> database name
117733 **   argv[2]   -> table name
117734 **   argv[...] -> column names...
117735 */
117736 static int rtreeInit(
117737   sqlite3 *db,                        /* Database connection */
117738   void *pAux,                         /* One of the RTREE_COORD_* constants */
117739   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
117740   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
117741   char **pzErr,                       /* OUT: Error message, if any */
117742   int isCreate                        /* True for xCreate, false for xConnect */
117743 ){
117744   int rc = SQLITE_OK;
117745   Rtree *pRtree;
117746   int nDb;              /* Length of string argv[1] */
117747   int nName;            /* Length of string argv[2] */
117748   int eCoordType = (int)pAux;
117749
117750   const char *aErrMsg[] = {
117751     0,                                                    /* 0 */
117752     "Wrong number of columns for an rtree table",         /* 1 */
117753     "Too few columns for an rtree table",                 /* 2 */
117754     "Too many columns for an rtree table"                 /* 3 */
117755   };
117756
117757   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
117758   if( aErrMsg[iErr] ){
117759     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
117760     return SQLITE_ERROR;
117761   }
117762
117763   /* Allocate the sqlite3_vtab structure */
117764   nDb = strlen(argv[1]);
117765   nName = strlen(argv[2]);
117766   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
117767   if( !pRtree ){
117768     return SQLITE_NOMEM;
117769   }
117770   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
117771   pRtree->nBusy = 1;
117772   pRtree->base.pModule = &rtreeModule;
117773   pRtree->zDb = (char *)&pRtree[1];
117774   pRtree->zName = &pRtree->zDb[nDb+1];
117775   pRtree->nDim = (argc-4)/2;
117776   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
117777   pRtree->eCoordType = eCoordType;
117778   memcpy(pRtree->zDb, argv[1], nDb);
117779   memcpy(pRtree->zName, argv[2], nName);
117780
117781   /* Figure out the node size to use. */
117782   rc = getNodeSize(db, pRtree, isCreate);
117783
117784   /* Create/Connect to the underlying relational database schema. If
117785   ** that is successful, call sqlite3_declare_vtab() to configure
117786   ** the r-tree table schema.
117787   */
117788   if( rc==SQLITE_OK ){
117789     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
117790       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117791     }else{
117792       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
117793       char *zTmp;
117794       int ii;
117795       for(ii=4; zSql && ii<argc; ii++){
117796         zTmp = zSql;
117797         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
117798         sqlite3_free(zTmp);
117799       }
117800       if( zSql ){
117801         zTmp = zSql;
117802         zSql = sqlite3_mprintf("%s);", zTmp);
117803         sqlite3_free(zTmp);
117804       }
117805       if( !zSql ){
117806         rc = SQLITE_NOMEM;
117807       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
117808         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117809       }
117810       sqlite3_free(zSql);
117811     }
117812   }
117813
117814   if( rc==SQLITE_OK ){
117815     *ppVtab = (sqlite3_vtab *)pRtree;
117816   }else{
117817     rtreeRelease(pRtree);
117818   }
117819   return rc;
117820 }
117821
117822
117823 /*
117824 ** Implementation of a scalar function that decodes r-tree nodes to
117825 ** human readable strings. This can be used for debugging and analysis.
117826 **
117827 ** The scalar function takes two arguments, a blob of data containing
117828 ** an r-tree node, and the number of dimensions the r-tree indexes.
117829 ** For a two-dimensional r-tree structure called "rt", to deserialize
117830 ** all nodes, a statement like:
117831 **
117832 **   SELECT rtreenode(2, data) FROM rt_node;
117833 **
117834 ** The human readable string takes the form of a Tcl list with one
117835 ** entry for each cell in the r-tree node. Each entry is itself a
117836 ** list, containing the 8-byte rowid/pageno followed by the 
117837 ** <num-dimension>*2 coordinates.
117838 */
117839 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117840   char *zText = 0;
117841   RtreeNode node;
117842   Rtree tree;
117843   int ii;
117844
117845   memset(&node, 0, sizeof(RtreeNode));
117846   memset(&tree, 0, sizeof(Rtree));
117847   tree.nDim = sqlite3_value_int(apArg[0]);
117848   tree.nBytesPerCell = 8 + 8 * tree.nDim;
117849   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
117850
117851   for(ii=0; ii<NCELL(&node); ii++){
117852     char zCell[512];
117853     int nCell = 0;
117854     RtreeCell cell;
117855     int jj;
117856
117857     nodeGetCell(&tree, &node, ii, &cell);
117858     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
117859     nCell = strlen(zCell);
117860     for(jj=0; jj<tree.nDim*2; jj++){
117861       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
117862       nCell = strlen(zCell);
117863     }
117864
117865     if( zText ){
117866       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
117867       sqlite3_free(zText);
117868       zText = zTextNew;
117869     }else{
117870       zText = sqlite3_mprintf("{%s}", zCell);
117871     }
117872   }
117873   
117874   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
117875 }
117876
117877 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117878   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
117879    || sqlite3_value_bytes(apArg[0])<2
117880   ){
117881     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
117882   }else{
117883     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
117884     sqlite3_result_int(ctx, readInt16(zBlob));
117885   }
117886 }
117887
117888 /*
117889 ** Register the r-tree module with database handle db. This creates the
117890 ** virtual table module "rtree" and the debugging/analysis scalar 
117891 ** function "rtreenode".
117892 */
117893 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
117894   int rc = SQLITE_OK;
117895
117896   if( rc==SQLITE_OK ){
117897     int utf8 = SQLITE_UTF8;
117898     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
117899   }
117900   if( rc==SQLITE_OK ){
117901     int utf8 = SQLITE_UTF8;
117902     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
117903   }
117904   if( rc==SQLITE_OK ){
117905     void *c = (void *)RTREE_COORD_REAL32;
117906     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
117907   }
117908   if( rc==SQLITE_OK ){
117909     void *c = (void *)RTREE_COORD_INT32;
117910     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
117911   }
117912
117913   return rc;
117914 }
117915
117916 #if !SQLITE_CORE
117917 SQLITE_API int sqlite3_extension_init(
117918   sqlite3 *db,
117919   char **pzErrMsg,
117920   const sqlite3_api_routines *pApi
117921 ){
117922   SQLITE_EXTENSION_INIT2(pApi)
117923   return sqlite3RtreeInit(db);
117924 }
117925 #endif
117926
117927 #endif
117928
117929 /************** End of rtree.c ***********************************************/
117930 /************** Begin file icu.c *********************************************/
117931 /*
117932 ** 2007 May 6
117933 **
117934 ** The author disclaims copyright to this source code.  In place of
117935 ** a legal notice, here is a blessing:
117936 **
117937 **    May you do good and not evil.
117938 **    May you find forgiveness for yourself and forgive others.
117939 **    May you share freely, never taking more than you give.
117940 **
117941 *************************************************************************
117942 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
117943 **
117944 ** This file implements an integration between the ICU library 
117945 ** ("International Components for Unicode", an open-source library 
117946 ** for handling unicode data) and SQLite. The integration uses 
117947 ** ICU to provide the following to SQLite:
117948 **
117949 **   * An implementation of the SQL regexp() function (and hence REGEXP
117950 **     operator) using the ICU uregex_XX() APIs.
117951 **
117952 **   * Implementations of the SQL scalar upper() and lower() functions
117953 **     for case mapping.
117954 **
117955 **   * Integration of ICU and SQLite collation seqences.
117956 **
117957 **   * An implementation of the LIKE operator that uses ICU to 
117958 **     provide case-independent matching.
117959 */
117960
117961 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
117962
117963 /* Include ICU headers */
117964 #include <unicode/utypes.h>
117965 #include <unicode/uregex.h>
117966 #include <unicode/ustring.h>
117967 #include <unicode/ucol.h>
117968
117969
117970 #ifndef SQLITE_CORE
117971   SQLITE_EXTENSION_INIT1
117972 #else
117973 #endif
117974
117975 /*
117976 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
117977 ** operator.
117978 */
117979 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
117980 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
117981 #endif
117982
117983 /*
117984 ** Version of sqlite3_free() that is always a function, never a macro.
117985 */
117986 static void xFree(void *p){
117987   sqlite3_free(p);
117988 }
117989
117990 /*
117991 ** Compare two UTF-8 strings for equality where the first string is
117992 ** a "LIKE" expression. Return true (1) if they are the same and 
117993 ** false (0) if they are different.
117994 */
117995 static int icuLikeCompare(
117996   const uint8_t *zPattern,   /* LIKE pattern */
117997   const uint8_t *zString,    /* The UTF-8 string to compare against */
117998   const UChar32 uEsc         /* The escape character */
117999 ){
118000   static const int MATCH_ONE = (UChar32)'_';
118001   static const int MATCH_ALL = (UChar32)'%';
118002
118003   int iPattern = 0;       /* Current byte index in zPattern */
118004   int iString = 0;        /* Current byte index in zString */
118005
118006   int prevEscape = 0;     /* True if the previous character was uEsc */
118007
118008   while( zPattern[iPattern]!=0 ){
118009
118010     /* Read (and consume) the next character from the input pattern. */
118011     UChar32 uPattern;
118012     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
118013     assert(uPattern!=0);
118014
118015     /* There are now 4 possibilities:
118016     **
118017     **     1. uPattern is an unescaped match-all character "%",
118018     **     2. uPattern is an unescaped match-one character "_",
118019     **     3. uPattern is an unescaped escape character, or
118020     **     4. uPattern is to be handled as an ordinary character
118021     */
118022     if( !prevEscape && uPattern==MATCH_ALL ){
118023       /* Case 1. */
118024       uint8_t c;
118025
118026       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
118027       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
118028       ** test string.
118029       */
118030       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
118031         if( c==MATCH_ONE ){
118032           if( zString[iString]==0 ) return 0;
118033           U8_FWD_1_UNSAFE(zString, iString);
118034         }
118035         iPattern++;
118036       }
118037
118038       if( zPattern[iPattern]==0 ) return 1;
118039
118040       while( zString[iString] ){
118041         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
118042           return 1;
118043         }
118044         U8_FWD_1_UNSAFE(zString, iString);
118045       }
118046       return 0;
118047
118048     }else if( !prevEscape && uPattern==MATCH_ONE ){
118049       /* Case 2. */
118050       if( zString[iString]==0 ) return 0;
118051       U8_FWD_1_UNSAFE(zString, iString);
118052
118053     }else if( !prevEscape && uPattern==uEsc){
118054       /* Case 3. */
118055       prevEscape = 1;
118056
118057     }else{
118058       /* Case 4. */
118059       UChar32 uString;
118060       U8_NEXT_UNSAFE(zString, iString, uString);
118061       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
118062       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
118063       if( uString!=uPattern ){
118064         return 0;
118065       }
118066       prevEscape = 0;
118067     }
118068   }
118069
118070   return zString[iString]==0;
118071 }
118072
118073 /*
118074 ** Implementation of the like() SQL function.  This function implements
118075 ** the build-in LIKE operator.  The first argument to the function is the
118076 ** pattern and the second argument is the string.  So, the SQL statements:
118077 **
118078 **       A LIKE B
118079 **
118080 ** is implemented as like(B, A). If there is an escape character E, 
118081 **
118082 **       A LIKE B ESCAPE E
118083 **
118084 ** is mapped to like(B, A, E).
118085 */
118086 static void icuLikeFunc(
118087   sqlite3_context *context, 
118088   int argc, 
118089   sqlite3_value **argv
118090 ){
118091   const unsigned char *zA = sqlite3_value_text(argv[0]);
118092   const unsigned char *zB = sqlite3_value_text(argv[1]);
118093   UChar32 uEsc = 0;
118094
118095   /* Limit the length of the LIKE or GLOB pattern to avoid problems
118096   ** of deep recursion and N*N behavior in patternCompare().
118097   */
118098   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
118099     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
118100     return;
118101   }
118102
118103
118104   if( argc==3 ){
118105     /* The escape character string must consist of a single UTF-8 character.
118106     ** Otherwise, return an error.
118107     */
118108     int nE= sqlite3_value_bytes(argv[2]);
118109     const unsigned char *zE = sqlite3_value_text(argv[2]);
118110     int i = 0;
118111     if( zE==0 ) return;
118112     U8_NEXT(zE, i, nE, uEsc);
118113     if( i!=nE){
118114       sqlite3_result_error(context, 
118115           "ESCAPE expression must be a single character", -1);
118116       return;
118117     }
118118   }
118119
118120   if( zA && zB ){
118121     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
118122   }
118123 }
118124
118125 /*
118126 ** This function is called when an ICU function called from within
118127 ** the implementation of an SQL scalar function returns an error.
118128 **
118129 ** The scalar function context passed as the first argument is 
118130 ** loaded with an error message based on the following two args.
118131 */
118132 static void icuFunctionError(
118133   sqlite3_context *pCtx,       /* SQLite scalar function context */
118134   const char *zName,           /* Name of ICU function that failed */
118135   UErrorCode e                 /* Error code returned by ICU function */
118136 ){
118137   char zBuf[128];
118138   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
118139   zBuf[127] = '\0';
118140   sqlite3_result_error(pCtx, zBuf, -1);
118141 }
118142
118143 /*
118144 ** Function to delete compiled regexp objects. Registered as
118145 ** a destructor function with sqlite3_set_auxdata().
118146 */
118147 static void icuRegexpDelete(void *p){
118148   URegularExpression *pExpr = (URegularExpression *)p;
118149   uregex_close(pExpr);
118150 }
118151
118152 /*
118153 ** Implementation of SQLite REGEXP operator. This scalar function takes
118154 ** two arguments. The first is a regular expression pattern to compile
118155 ** the second is a string to match against that pattern. If either 
118156 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
118157 ** is 1 if the string matches the pattern, or 0 otherwise.
118158 **
118159 ** SQLite maps the regexp() function to the regexp() operator such
118160 ** that the following two are equivalent:
118161 **
118162 **     zString REGEXP zPattern
118163 **     regexp(zPattern, zString)
118164 **
118165 ** Uses the following ICU regexp APIs:
118166 **
118167 **     uregex_open()
118168 **     uregex_matches()
118169 **     uregex_close()
118170 */
118171 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
118172   UErrorCode status = U_ZERO_ERROR;
118173   URegularExpression *pExpr;
118174   UBool res;
118175   const UChar *zString = sqlite3_value_text16(apArg[1]);
118176
118177   /* If the left hand side of the regexp operator is NULL, 
118178   ** then the result is also NULL. 
118179   */
118180   if( !zString ){
118181     return;
118182   }
118183
118184   pExpr = sqlite3_get_auxdata(p, 0);
118185   if( !pExpr ){
118186     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
118187     if( !zPattern ){
118188       return;
118189     }
118190     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
118191
118192     if( U_SUCCESS(status) ){
118193       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
118194     }else{
118195       assert(!pExpr);
118196       icuFunctionError(p, "uregex_open", status);
118197       return;
118198     }
118199   }
118200
118201   /* Configure the text that the regular expression operates on. */
118202   uregex_setText(pExpr, zString, -1, &status);
118203   if( !U_SUCCESS(status) ){
118204     icuFunctionError(p, "uregex_setText", status);
118205     return;
118206   }
118207
118208   /* Attempt the match */
118209   res = uregex_matches(pExpr, 0, &status);
118210   if( !U_SUCCESS(status) ){
118211     icuFunctionError(p, "uregex_matches", status);
118212     return;
118213   }
118214
118215   /* Set the text that the regular expression operates on to a NULL
118216   ** pointer. This is not really necessary, but it is tidier than 
118217   ** leaving the regular expression object configured with an invalid
118218   ** pointer after this function returns.
118219   */
118220   uregex_setText(pExpr, 0, 0, &status);
118221
118222   /* Return 1 or 0. */
118223   sqlite3_result_int(p, res ? 1 : 0);
118224 }
118225
118226 /*
118227 ** Implementations of scalar functions for case mapping - upper() and 
118228 ** lower(). Function upper() converts its input to upper-case (ABC).
118229 ** Function lower() converts to lower-case (abc).
118230 **
118231 ** ICU provides two types of case mapping, "general" case mapping and
118232 ** "language specific". Refer to ICU documentation for the differences
118233 ** between the two.
118234 **
118235 ** To utilise "general" case mapping, the upper() or lower() scalar 
118236 ** functions are invoked with one argument:
118237 **
118238 **     upper('ABC') -> 'abc'
118239 **     lower('abc') -> 'ABC'
118240 **
118241 ** To access ICU "language specific" case mapping, upper() or lower()
118242 ** should be invoked with two arguments. The second argument is the name
118243 ** of the locale to use. Passing an empty string ("") or SQL NULL value
118244 ** as the second argument is the same as invoking the 1 argument version
118245 ** of upper() or lower().
118246 **
118247 **     lower('I', 'en_us') -> 'i'
118248 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
118249 **
118250 ** http://www.icu-project.org/userguide/posix.html#case_mappings
118251 */
118252 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
118253   const UChar *zInput;
118254   UChar *zOutput;
118255   int nInput;
118256   int nOutput;
118257
118258   UErrorCode status = U_ZERO_ERROR;
118259   const char *zLocale = 0;
118260
118261   assert(nArg==1 || nArg==2);
118262   if( nArg==2 ){
118263     zLocale = (const char *)sqlite3_value_text(apArg[1]);
118264   }
118265
118266   zInput = sqlite3_value_text16(apArg[0]);
118267   if( !zInput ){
118268     return;
118269   }
118270   nInput = sqlite3_value_bytes16(apArg[0]);
118271
118272   nOutput = nInput * 2 + 2;
118273   zOutput = sqlite3_malloc(nOutput);
118274   if( !zOutput ){
118275     return;
118276   }
118277
118278   if( sqlite3_user_data(p) ){
118279     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
118280   }else{
118281     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
118282   }
118283
118284   if( !U_SUCCESS(status) ){
118285     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
118286     return;
118287   }
118288
118289   sqlite3_result_text16(p, zOutput, -1, xFree);
118290 }
118291
118292 /*
118293 ** Collation sequence destructor function. The pCtx argument points to
118294 ** a UCollator structure previously allocated using ucol_open().
118295 */
118296 static void icuCollationDel(void *pCtx){
118297   UCollator *p = (UCollator *)pCtx;
118298   ucol_close(p);
118299 }
118300
118301 /*
118302 ** Collation sequence comparison function. The pCtx argument points to
118303 ** a UCollator structure previously allocated using ucol_open().
118304 */
118305 static int icuCollationColl(
118306   void *pCtx,
118307   int nLeft,
118308   const void *zLeft,
118309   int nRight,
118310   const void *zRight
118311 ){
118312   UCollationResult res;
118313   UCollator *p = (UCollator *)pCtx;
118314   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
118315   switch( res ){
118316     case UCOL_LESS:    return -1;
118317     case UCOL_GREATER: return +1;
118318     case UCOL_EQUAL:   return 0;
118319   }
118320   assert(!"Unexpected return value from ucol_strcoll()");
118321   return 0;
118322 }
118323
118324 /*
118325 ** Implementation of the scalar function icu_load_collation().
118326 **
118327 ** This scalar function is used to add ICU collation based collation 
118328 ** types to an SQLite database connection. It is intended to be called
118329 ** as follows:
118330 **
118331 **     SELECT icu_load_collation(<locale>, <collation-name>);
118332 **
118333 ** Where <locale> is a string containing an ICU locale identifier (i.e.
118334 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
118335 ** collation sequence to create.
118336 */
118337 static void icuLoadCollation(
118338   sqlite3_context *p, 
118339   int nArg, 
118340   sqlite3_value **apArg
118341 ){
118342   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
118343   UErrorCode status = U_ZERO_ERROR;
118344   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
118345   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
118346   UCollator *pUCollator;    /* ICU library collation object */
118347   int rc;                   /* Return code from sqlite3_create_collation_x() */
118348
118349   assert(nArg==2);
118350   zLocale = (const char *)sqlite3_value_text(apArg[0]);
118351   zName = (const char *)sqlite3_value_text(apArg[1]);
118352
118353   if( !zLocale || !zName ){
118354     return;
118355   }
118356
118357   pUCollator = ucol_open(zLocale, &status);
118358   if( !U_SUCCESS(status) ){
118359     icuFunctionError(p, "ucol_open", status);
118360     return;
118361   }
118362   assert(p);
118363
118364   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
118365       icuCollationColl, icuCollationDel
118366   );
118367   if( rc!=SQLITE_OK ){
118368     ucol_close(pUCollator);
118369     sqlite3_result_error(p, "Error registering collation function", -1);
118370   }
118371 }
118372
118373 /*
118374 ** Register the ICU extension functions with database db.
118375 */
118376 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
118377   struct IcuScalar {
118378     const char *zName;                        /* Function name */
118379     int nArg;                                 /* Number of arguments */
118380     int enc;                                  /* Optimal text encoding */
118381     void *pContext;                           /* sqlite3_user_data() context */
118382     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
118383   } scalars[] = {
118384     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
118385
118386     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
118387     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
118388     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
118389     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
118390
118391     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
118392     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
118393     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
118394     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
118395
118396     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
118397     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
118398
118399     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
118400   };
118401
118402   int rc = SQLITE_OK;
118403   int i;
118404
118405   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
118406     struct IcuScalar *p = &scalars[i];
118407     rc = sqlite3_create_function(
118408         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
118409     );
118410   }
118411
118412   return rc;
118413 }
118414
118415 #if !SQLITE_CORE
118416 SQLITE_API int sqlite3_extension_init(
118417   sqlite3 *db, 
118418   char **pzErrMsg,
118419   const sqlite3_api_routines *pApi
118420 ){
118421   SQLITE_EXTENSION_INIT2(pApi)
118422   return sqlite3IcuInit(db);
118423 }
118424 #endif
118425
118426 #endif
118427
118428 /************** End of icu.c *************************************************/
118429 /************** Begin file fts3_icu.c ****************************************/
118430 /*
118431 ** 2007 June 22
118432 **
118433 ** The author disclaims copyright to this source code.  In place of
118434 ** a legal notice, here is a blessing:
118435 **
118436 **    May you do good and not evil.
118437 **    May you find forgiveness for yourself and forgive others.
118438 **    May you share freely, never taking more than you give.
118439 **
118440 *************************************************************************
118441 ** This file implements a tokenizer for fts3 based on the ICU library.
118442 ** 
118443 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
118444 */
118445
118446 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118447 #ifdef SQLITE_ENABLE_ICU
118448
118449
118450 #include <unicode/ubrk.h>
118451 #include <unicode/utf16.h>
118452
118453 typedef struct IcuTokenizer IcuTokenizer;
118454 typedef struct IcuCursor IcuCursor;
118455
118456 struct IcuTokenizer {
118457   sqlite3_tokenizer base;
118458   char *zLocale;
118459 };
118460
118461 struct IcuCursor {
118462   sqlite3_tokenizer_cursor base;
118463
118464   UBreakIterator *pIter;      /* ICU break-iterator object */
118465   int nChar;                  /* Number of UChar elements in pInput */
118466   UChar *aChar;               /* Copy of input using utf-16 encoding */
118467   int *aOffset;               /* Offsets of each character in utf-8 input */
118468
118469   int nBuffer;
118470   char *zBuffer;
118471
118472   int iToken;
118473 };
118474
118475 /*
118476 ** Create a new tokenizer instance.
118477 */
118478 static int icuCreate(
118479   int argc,                            /* Number of entries in argv[] */
118480   const char * const *argv,            /* Tokenizer creation arguments */
118481   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
118482 ){
118483   IcuTokenizer *p;
118484   int n = 0;
118485
118486   if( argc>0 ){
118487     n = strlen(argv[0])+1;
118488   }
118489   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
118490   if( !p ){
118491     return SQLITE_NOMEM;
118492   }
118493   memset(p, 0, sizeof(IcuTokenizer));
118494
118495   if( n ){
118496     p->zLocale = (char *)&p[1];
118497     memcpy(p->zLocale, argv[0], n);
118498   }
118499
118500   *ppTokenizer = (sqlite3_tokenizer *)p;
118501
118502   return SQLITE_OK;
118503 }
118504
118505 /*
118506 ** Destroy a tokenizer
118507 */
118508 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
118509   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118510   sqlite3_free(p);
118511   return SQLITE_OK;
118512 }
118513
118514 /*
118515 ** Prepare to begin tokenizing a particular string.  The input
118516 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
118517 ** used to incrementally tokenize this string is returned in 
118518 ** *ppCursor.
118519 */
118520 static int icuOpen(
118521   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
118522   const char *zInput,                    /* Input string */
118523   int nInput,                            /* Length of zInput in bytes */
118524   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
118525 ){
118526   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118527   IcuCursor *pCsr;
118528
118529   const int32_t opt = U_FOLD_CASE_DEFAULT;
118530   UErrorCode status = U_ZERO_ERROR;
118531   int nChar;
118532
118533   UChar32 c;
118534   int iInput = 0;
118535   int iOut = 0;
118536
118537   *ppCursor = 0;
118538
118539   if( nInput<0 ){
118540     nInput = strlen(zInput);
118541   }
118542   nChar = nInput+1;
118543   pCsr = (IcuCursor *)sqlite3_malloc(
118544       sizeof(IcuCursor) +                /* IcuCursor */
118545       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
118546       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
118547   );
118548   if( !pCsr ){
118549     return SQLITE_NOMEM;
118550   }
118551   memset(pCsr, 0, sizeof(IcuCursor));
118552   pCsr->aChar = (UChar *)&pCsr[1];
118553   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
118554
118555   pCsr->aOffset[iOut] = iInput;
118556   U8_NEXT(zInput, iInput, nInput, c); 
118557   while( c>0 ){
118558     int isError = 0;
118559     c = u_foldCase(c, opt);
118560     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
118561     if( isError ){
118562       sqlite3_free(pCsr);
118563       return SQLITE_ERROR;
118564     }
118565     pCsr->aOffset[iOut] = iInput;
118566
118567     if( iInput<nInput ){
118568       U8_NEXT(zInput, iInput, nInput, c);
118569     }else{
118570       c = 0;
118571     }
118572   }
118573
118574   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
118575   if( !U_SUCCESS(status) ){
118576     sqlite3_free(pCsr);
118577     return SQLITE_ERROR;
118578   }
118579   pCsr->nChar = iOut;
118580
118581   ubrk_first(pCsr->pIter);
118582   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
118583   return SQLITE_OK;
118584 }
118585
118586 /*
118587 ** Close a tokenization cursor previously opened by a call to icuOpen().
118588 */
118589 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
118590   IcuCursor *pCsr = (IcuCursor *)pCursor;
118591   ubrk_close(pCsr->pIter);
118592   sqlite3_free(pCsr->zBuffer);
118593   sqlite3_free(pCsr);
118594   return SQLITE_OK;
118595 }
118596
118597 /*
118598 ** Extract the next token from a tokenization cursor.
118599 */
118600 static int icuNext(
118601   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
118602   const char **ppToken,               /* OUT: *ppToken is the token text */
118603   int *pnBytes,                       /* OUT: Number of bytes in token */
118604   int *piStartOffset,                 /* OUT: Starting offset of token */
118605   int *piEndOffset,                   /* OUT: Ending offset of token */
118606   int *piPosition                     /* OUT: Position integer of token */
118607 ){
118608   IcuCursor *pCsr = (IcuCursor *)pCursor;
118609
118610   int iStart = 0;
118611   int iEnd = 0;
118612   int nByte = 0;
118613
118614   while( iStart==iEnd ){
118615     UChar32 c;
118616
118617     iStart = ubrk_current(pCsr->pIter);
118618     iEnd = ubrk_next(pCsr->pIter);
118619     if( iEnd==UBRK_DONE ){
118620       return SQLITE_DONE;
118621     }
118622
118623     while( iStart<iEnd ){
118624       int iWhite = iStart;
118625       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
118626       if( u_isspace(c) ){
118627         iStart = iWhite;
118628       }else{
118629         break;
118630       }
118631     }
118632     assert(iStart<=iEnd);
118633   }
118634
118635   do {
118636     UErrorCode status = U_ZERO_ERROR;
118637     if( nByte ){
118638       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
118639       if( !zNew ){
118640         return SQLITE_NOMEM;
118641       }
118642       pCsr->zBuffer = zNew;
118643       pCsr->nBuffer = nByte;
118644     }
118645
118646     u_strToUTF8(
118647         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
118648         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
118649         &status                                  /* Output success/failure */
118650     );
118651   } while( nByte>pCsr->nBuffer );
118652
118653   *ppToken = pCsr->zBuffer;
118654   *pnBytes = nByte;
118655   *piStartOffset = pCsr->aOffset[iStart];
118656   *piEndOffset = pCsr->aOffset[iEnd];
118657   *piPosition = pCsr->iToken++;
118658
118659   return SQLITE_OK;
118660 }
118661
118662 /*
118663 ** The set of routines that implement the simple tokenizer
118664 */
118665 static const sqlite3_tokenizer_module icuTokenizerModule = {
118666   0,                           /* iVersion */
118667   icuCreate,                   /* xCreate  */
118668   icuDestroy,                  /* xCreate  */
118669   icuOpen,                     /* xOpen    */
118670   icuClose,                    /* xClose   */
118671   icuNext,                     /* xNext    */
118672 };
118673
118674 /*
118675 ** Set *ppModule to point at the implementation of the ICU tokenizer.
118676 */
118677 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
118678   sqlite3_tokenizer_module const**ppModule
118679 ){
118680   *ppModule = &icuTokenizerModule;
118681 }
118682
118683 #endif /* defined(SQLITE_ENABLE_ICU) */
118684 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118685
118686 /************** End of fts3_icu.c ********************************************/